-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathSequence+MinMax.swift
33 lines (29 loc) · 1.03 KB
/
Sequence+MinMax.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
33
//
// Sequence+MinMax.swift
//
// Advent of Code Tools
//
extension Sequence {
public func min<Value: Comparable>(of keyPath: KeyPath<Element, Value>) -> Value? {
let element = self.min(by: { $0[keyPath: keyPath] < $1[keyPath: keyPath] })
return element?[keyPath: keyPath]
}
public func max<Value: Comparable>(of keyPath: KeyPath<Element, Value>) -> Value? {
let element = self.max(by: { $0[keyPath: keyPath] < $1[keyPath: keyPath] })
return element?[keyPath: keyPath]
}
}
extension Sequence where Element: Comparable {
public func minAndMax<Value: Comparable>(of keyPath: KeyPath<Element, Value>) -> (Value, Value)? {
var iter = makeIterator()
guard let first = iter.next() else { return nil }
var min = first[keyPath: keyPath]
var max = min
while let elem = iter.next() {
let value = elem[keyPath: keyPath]
if value < min { min = value }
if value > max { max = value }
}
return (min, max)
}
}