Last active
March 26, 2024 12:27
-
-
Save khanlou/7d3029056459d1b495c012d624614ed2 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
| public enum NilOrdering { | |
| case first, last | |
| } | |
| public enum SortOrdering { | |
| case ascending, descending | |
| } | |
| public extension Sequence { | |
| func sorted(on accessor: (Element) -> some Comparable, ordering: SortOrdering = .ascending) -> [Element] { | |
| return sorted { a, b in | |
| let propertyA = accessor(a) | |
| let propertyB = accessor(b) | |
| return ordering == .ascending ? propertyA < propertyB : propertyA > propertyB | |
| } | |
| } | |
| func sorted( | |
| on accessor: (Element) -> (some Comparable)?, | |
| ordering: SortOrdering = .ascending, | |
| nilOrdering: NilOrdering = .last | |
| ) -> [Element] { | |
| return sorted { a, b in | |
| guard let valueA = accessor(a) else { | |
| return nilOrdering == .first | |
| } | |
| guard let valueB = accessor(b) else { | |
| return nilOrdering == .last | |
| } | |
| return ordering == .ascending ? valueA < valueB : valueA > valueB | |
| } | |
| } | |
| func min(of propertyAccessor: (Element) throws -> some Comparable) rethrows -> Element? { | |
| try self.min(by: { lhs, rhs in | |
| try propertyAccessor(lhs) < propertyAccessor(rhs) | |
| }) | |
| } | |
| func max(of propertyAccessor: (Element) throws -> some Comparable) rethrows -> Element? { | |
| try self.max(by: { lhs, rhs in | |
| try propertyAccessor(lhs) < propertyAccessor(rhs) | |
| }) | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment