Skip to content

Commit

Permalink
Add asyncCompactMap (#14)
Browse files Browse the repository at this point in the history
* Add asyncCompactMap
  • Loading branch information
0xLeif authored Sep 16, 2022
1 parent 9be93fb commit d2ab6bf
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 0 deletions.
7 changes: 7 additions & 0 deletions Sources/Fork/Extensions/Array+ForkedArray.swift
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,13 @@ extension Array {
try await fork(map: transform).output()
}

/// Returns an array containing the results, that aren't nil, of mapping the given closure over the sequence’s elements.
public func asyncCompactMap<Output>(
_ transform: @escaping (Element) async throws -> Output?
) async throws -> [Output] {
try await fork(map: transform).output().compactMap { $0 }
}

/// Returns an array containing only the true results from the given closure over the sequence’s elements.
public func asyncFilter(
_ isIncluded: @escaping (Element) async throws -> Bool
Expand Down
13 changes: 13 additions & 0 deletions Tests/ForkTests/ForkedArrayTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -70,6 +70,19 @@ class ForkedArrayTests: XCTestCase {
XCTAssertEqual(photos, photoNames)
}

func testForkedArrayCompactMap_x() async throws {
let photoNames = [Int](0 ..< 100)
@Sendable func asyncFilter(number: Int) async -> String? {
guard number.isMultiple(of: 2) else { return nil }

return number.description
}

let compactedArray = try await photoNames.asyncCompactMap(asyncFilter(number:))

XCTAssertEqual(compactedArray.count, photoNames.count / 2)
}

func testForkedArray_order() async throws {
let photoNames = ["Hello", " ", "World", "!"]
@Sendable func downloadPhoto(named: String) async -> String { named }
Expand Down

0 comments on commit d2ab6bf

Please sign in to comment.