Sequence+Extension.swift
1.99 KB
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
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
//
// Sequence.swift
// Twear
//
// Created by yangbin on 2021/12/4.
//
import Foundation
extension Sequence where Element: AdditiveArithmetic {
/// Returns the total sum of all elements in the sequence
func sum() -> Element { reduce(.zero, +) }
}
extension Collection where Element: BinaryInteger {
/// Returns the average of all elements in the array
func average() -> Element { isEmpty ? .zero : sum() / Element(count) }
/// Returns the average of all elements in the array as Floating Point type
func average<T: FloatingPoint>() -> T { isEmpty ? .zero : T(sum()) / T(count) }
}
extension Collection where Element: BinaryFloatingPoint {
/// Returns the average of all elements in the array
func average() -> Element { isEmpty ? .zero : Element(sum()) / Element(count) }
}
extension Sequence {
func sum<T: AdditiveArithmetic>(_ keyPath: KeyPath<Element, T>) -> T {
reduce(.zero) { $0 + $1[keyPath: keyPath] }
}
func max<T: Comparable>(_ keyPath: KeyPath<Element, T>) -> Element? {
self.max { $0[keyPath: keyPath] < $1[keyPath: keyPath] }
}
func min<T: Comparable>(_ keyPath: KeyPath<Element, T>) -> Element? {
self.min { $0[keyPath: keyPath] < $1[keyPath: keyPath] }
}
func sorted<T: Comparable>(_ keyPath: KeyPath<Element, T>) -> [Self.Element] {
self.sorted { $0[keyPath: keyPath] < $1[keyPath: keyPath] }
}
func count(_ where: (Element) -> Bool) -> Int {
self.filter(`where`).count
}
}
extension Collection {
func average<I: BinaryInteger>(_ keyPath: KeyPath<Element, I>) -> I {
sum(keyPath) / I(count)
}
func average<I: BinaryInteger, F: BinaryFloatingPoint>(_ keyPath: KeyPath<Element, I>) -> F {
F(sum(keyPath)) / F(count)
}
func average<F: BinaryFloatingPoint>(_ keyPath: KeyPath<Element, F>) -> F {
sum(keyPath) / F(count)
}
func average(_ keyPath: KeyPath<Element, Decimal>) -> Decimal {
sum(keyPath) / Decimal(count)
}
}