From d2ab6bfc910a846c909170d3df37bbfa717d6434 Mon Sep 17 00:00:00 2001 From: Zach Date: Thu, 15 Sep 2022 21:07:55 -0600 Subject: [PATCH] Add asyncCompactMap (#14) * Add asyncCompactMap --- Sources/Fork/Extensions/Array+ForkedArray.swift | 7 +++++++ Tests/ForkTests/ForkedArrayTests.swift | 13 +++++++++++++ 2 files changed, 20 insertions(+) diff --git a/Sources/Fork/Extensions/Array+ForkedArray.swift b/Sources/Fork/Extensions/Array+ForkedArray.swift index 9efd8f0..6af7071 100644 --- a/Sources/Fork/Extensions/Array+ForkedArray.swift +++ b/Sources/Fork/Extensions/Array+ForkedArray.swift @@ -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( + _ 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 diff --git a/Tests/ForkTests/ForkedArrayTests.swift b/Tests/ForkTests/ForkedArrayTests.swift index c410803..d3ffc7a 100644 --- a/Tests/ForkTests/ForkedArrayTests.swift +++ b/Tests/ForkTests/ForkedArrayTests.swift @@ -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 }