// // 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 { 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(_ keyPath: KeyPath) -> T { reduce(.zero) { $0 + $1[keyPath: keyPath] } } func max(_ keyPath: KeyPath) -> Element? { self.max { $0[keyPath: keyPath] < $1[keyPath: keyPath] } } func min(_ keyPath: KeyPath) -> Element? { self.min { $0[keyPath: keyPath] < $1[keyPath: keyPath] } } func sorted(_ keyPath: KeyPath) -> [Self.Element] { self.sorted { $0[keyPath: keyPath] < $1[keyPath: keyPath] } } func count(_ where: (Element) -> Bool) -> Int { self.filter(`where`).count } } extension Collection { func average(_ keyPath: KeyPath) -> I { sum(keyPath) / I(count) } func average(_ keyPath: KeyPath) -> F { F(sum(keyPath)) / F(count) } func average(_ keyPath: KeyPath) -> F { sum(keyPath) / F(count) } func average(_ keyPath: KeyPath) -> Decimal { sum(keyPath) / Decimal(count) } }