Sequence+Extension.swift 1.99 KB
//
//  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)
    }
   
}