Skip to content

Commit

Permalink
Add Sequence<AdditiveArithmetic>.sum()
Browse files Browse the repository at this point in the history
  • Loading branch information
NachoSoto committed Jun 22, 2023
1 parent bb1b3e4 commit 100b824
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 0 deletions.
9 changes: 9 additions & 0 deletions Sources/FoundationExtensions/Array+Extensions.swift
Original file line number Diff line number Diff line change
Expand Up @@ -36,3 +36,12 @@ extension Collection {
}

}

extension Sequence where Element: AdditiveArithmetic {

/// - Returns: the sum of the elements in the sequence.
func sum() -> Element {
return reduce(.zero, +)
}

}
14 changes: 14 additions & 0 deletions Tests/UnitTests/FoundationExtensions/ArrayExtensionsTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -57,4 +57,18 @@ class ArrayExtensionsTests: TestCase {
expect([1].onlyElement) == 1
}

// MARK: - sum

func testSumEmptyArray() {
expect([Int]().sum()) == 0
}

func testSumSingleElementArray() {
expect([5].sum()) == 5
}

func testSumArrayWithMultipleElements() {
expect([1, 2, 3].sum()) == 6
}

}

0 comments on commit 100b824

Please sign in to comment.