Skip to content

Instantly share code, notes, and snippets.

@khanlou
Last active March 26, 2024 12:27
Show Gist options
  • Select an option

  • Save khanlou/7d3029056459d1b495c012d624614ed2 to your computer and use it in GitHub Desktop.

Select an option

Save khanlou/7d3029056459d1b495c012d624614ed2 to your computer and use it in GitHub Desktop.
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