Skip to content

Commit

Permalink
Implement Colletion.partitioined method
Browse files Browse the repository at this point in the history
  • Loading branch information
Alkenso committed Jan 24, 2024
1 parent d0330a5 commit 72fb090
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 0 deletions.
23 changes: 23 additions & 0 deletions Sources/SpellbookFoundation/Common/Extensions - Collections.swift
Original file line number Diff line number Diff line change
Expand Up @@ -155,6 +155,29 @@ extension Collection {
}
}

extension Collection {
/// Split the elements of the collection into two parts, where first part
/// contains all the elements that match the given predicate and the second part
/// contains all the elements that don't match.
///
/// - Parameter belongsToFirstPartition: A predicate used to partition
/// the collection. All elements satisfying this predicate are gathered
/// into the fist part.
/// - Returns: Tuple of two part of the collection: (matched, not_matched)
/// the predicate.
///
/// - Complexity: O(*n*), where *n* is the length of the collection.
public func partitioned(first belongsToFirstPartition: (Element) throws -> Bool) rethrows -> ([Element], [Element]) {
try reduce(into: (Array(), Array())) { partialResult, element in
if try belongsToFirstPartition(element) {
partialResult.0.append(element)
} else {
partialResult.1.append(element)
}
}
}
}

extension RangeReplaceableCollection {
@discardableResult
public mutating func removeFirst(where predicate: (Element) throws -> Bool) rethrows -> Element? {
Expand Down
7 changes: 7 additions & 0 deletions Tests/SpellbookTests/Extensions Tests/CollectionsTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -80,4 +80,11 @@ class CollectionTests: XCTestCase {
XCTAssertEqual(arr.removeFirst { $0 < 10 }, 2)
XCTAssertEqual(arr.removeFirst { $0 < 10 }, nil)
}

func test_partitioned() {
let arr = [1, 5, 11, 10]
let (first, second) = arr.partitioned(first: { $0 % 5 == 0 })
XCTAssertEqual(first, [5, 10])
XCTAssertEqual(second, [1, 11])
}
}

0 comments on commit 72fb090

Please sign in to comment.