Skip to content

Commit

Permalink
Add sum() for any kind of sequence when a mapper is provided
Browse files Browse the repository at this point in the history
  • Loading branch information
Jeehut committed Jan 11, 2024
1 parent 8e537dc commit c63a6ed
Showing 1 changed file with 8 additions and 0 deletions.
8 changes: 8 additions & 0 deletions Sources/HandySwift/Extensions/CollectionExt.swift
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,14 @@ extension Sequence where Element: Numeric {
}
}

extension Sequence {
/// Returns the sum of all elements mapped to a numeric value.
@inlinable
public func sum<N: Numeric>(mapToNumeric: (Element) -> N) -> N {
self.reduce(into: 0) { $0 += mapToNumeric($1) }
}
}

extension Collection where Element: DivisibleArithmetic {
/// Returns the average of all elements.
@inlinable
Expand Down

0 comments on commit c63a6ed

Please sign in to comment.