-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathArray+Sort.swift
32 lines (27 loc) · 1 KB
/
Array+Sort.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
//
// Array+Sort.swift
//
// Advent of Code Tools
//
// Array.sort and Array.sorted using Keypaths,
extension Sequence {
public func sorted<Value>(by keyPath: KeyPath<Element, Value>,
using valuesAreInIncreasingOrder: (Value, Value) throws -> Bool
) rethrows -> [Element] {
try self.sorted(by: {
try valuesAreInIncreasingOrder($0[keyPath: keyPath], $1[keyPath: keyPath])
})
}
public func sorted<Value: Comparable>(by keyPath: KeyPath<Element, Value>) -> [Element] {
self.sorted(by: keyPath, using: <)
}
}
extension Array {
public mutating func sort<Value>(by keyPath: KeyPath<Element, Value>,
using valuesAreInIncreasingOrder: (Value, Value) throws -> Bool) rethrows {
self = try self.sorted(by: keyPath, using: valuesAreInIncreasingOrder)
}
public mutating func sort<Value: Comparable>(by keyPath: KeyPath<Element, Value>) {
self = self.sorted(by: keyPath)
}
}