-
Notifications
You must be signed in to change notification settings - Fork 1
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
1 parent
c2cbf73
commit 686e500
Showing
5 changed files
with
96 additions
and
21 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,49 @@ | ||
// | ||
// File.swift | ||
// | ||
// | ||
// Created by krishna varshney on 25/10/23. | ||
// | ||
|
||
import Foundation | ||
|
||
public enum SortingStrategy { | ||
case ascending | ||
case descending | ||
case none | ||
} | ||
|
||
class SortedDictionary: Sequence, IteratorProtocol { | ||
private let source: Dictionary<String, Any> | ||
private let strategy: SortingStrategy | ||
private var idx = -1 | ||
|
||
private lazy var sortedData: ([Dictionary<String, Any>.Element]) = { | ||
switch strategy { | ||
case .ascending: | ||
return source.sorted(by: { $0.key < $1.key }) | ||
case .descending: | ||
return source.sorted(by: { $0.key > $1.key }) | ||
case .none: | ||
return source.map({$0}) | ||
} | ||
|
||
}() | ||
|
||
internal init(source: Dictionary<String, Any>, strategy: SortingStrategy) { | ||
self.source = source | ||
self.strategy = strategy | ||
} | ||
|
||
func makeIterator() -> SortedDictionary { | ||
return self | ||
} | ||
|
||
func next() -> (String, Any)? { | ||
idx += 1 | ||
guard sortedData.indices.contains(idx) else { | ||
return nil | ||
} | ||
return (sortedData[idx].key, sortedData[idx].value) | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters