Skip to content

Commit

Permalink
feat: add last() to async sequence (#36)
Browse files Browse the repository at this point in the history
  • Loading branch information
reddavis authored Jul 15, 2022
1 parent 657bfed commit 35024e9
Show file tree
Hide file tree
Showing 3 changed files with 35 additions and 2 deletions.
10 changes: 10 additions & 0 deletions Asynchrone/Source/Extensions/AsyncSequence+Extension.swift
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,16 @@ extension AsyncSequence {
}
}

/// The last element of the sequence, if there is one.
public func last() async rethrows -> Element? {
var latestElement: Element?
for try await element in self {
latestElement = element
}

return latestElement
}

/// Collect elements from a sequence.
///
/// ```swift
Expand Down
11 changes: 9 additions & 2 deletions AsynchroneTests/Tests/Extensions/AsyncSequenceTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -28,8 +28,15 @@ final class AsyncSequenceTests: XCTestCase {
// MARK: First

func testFirst() async {
let firstValue = await self.sequence.first()
XCTAssertEqual(firstValue, 1)
let element = await self.sequence.first()
XCTAssertEqual(element, 1)
}

// MARK: Last

func testLast() async {
let element = await self.sequence.last()
XCTAssertEqual(element, 3)
}

// MARK: Collect
Expand Down
16 changes: 16 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -71,6 +71,22 @@ print(await sequence.first())
// 1
```

#### Last

```swift
let sequence = AsyncStream<Int> { continuation in
continuation.yield(1)
continuation.yield(2)
continuation.yield(3)
continuation.finish()
}

print(await sequence.last())

// Prints:
// 3
```

#### Collect

```swift
Expand Down

0 comments on commit 35024e9

Please sign in to comment.