apple / apple/swift-algorithms
`AdjacentPairs`: Ability to also include the (last, first) pair
- Dominant language
- Swift
- Stars
- 6.3k
- Forks
- 483
- PR merge metrics
- No merged PRs in 30d
Description
**Summary:**
Add ability to optionally also include the pair of the last element and the first element at the end of `AdjacentPairs`.
**Use Case:**
For use with circular linked links. Today, I was working with the key view loop on macOS and needed to be able to tie the last element in the loop back to the first. `AdjacentPairs` almost made this really easy, but was missing the pair of (last, first) so I couldn’t connect them together to be a loop.
```swift
for (previousView, nextView) in keyViewLoop.adjacentPairs(wrapping: true) {
previousView.nextKeyView = nextView
}
```
**Possible API:**
I’m not sure if this should be a separate API, or if this extends `AdjacentPairs`
```swift
extension Sequence {
/// …
/// The following example uses `adjacentPairs(wrapping: true)` to iterate over
/// adjacent pairs of integers:
///
/// for pair in (1...).prefix(5).adjacentPairs(wrapping: true) {
/// print(pair)
/// }
/// // Prints "(1, 2)"
/// // Prints "(2, 3)"
/// // Prints "(3, 4)"
/// // Prints "(4, 5)"
/// // Prints "(5, 1)"
@inlinable
public func adjacentPairs(wrapping: Bool = false) -> AdjacentPairsSequence {
AdjacentPairsSequence(base: self, wrapping: wrapping)
}
}
extension Collection {
/// …
/// for pair in (1...5).adjacentPairs(wrapping: true) {
/// print(pair)
/// }
/// // Prints "(1, 2)"
/// // Prints "(2, 3)"
/// // Prints "(3, 4)"
/// // Prints "(4, 5)"
/// // Prints "(5, 1)"
@inlinable
public func adjacentPairs(wrapping: Bool = false) -> AdjacentPairsCollection {
AdjacentPairsCollection(base: self, wrapping: wrapping)
}
}
```
Contributor guide
Research direction
Start by locating the Sequence and Collection implementations of adjacentPairs and the AdjacentPairsSequence and AdjacentPairsCollection types. Check how the wrapping option should affect empty, single-element, and multi-element inputs, then verify that iteration produces the final-to-first pair and preserves the existing behavior when wrapping is false.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- swift
- Domain
- developer-experience
- Issue type
- Feature
- Difficulty
- 3/5
- Estimated time
- 1-2 days
- Activity status
- Stale
- Clarity
- Mostly clear
- Newbie friendliness
- 35/100