Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

AdjacentPairs: Ability to also include the (last, first) pair #140

Open
mdznr opened this issue May 7, 2021 · 0 comments
Open

AdjacentPairs: Ability to also include the (last, first) pair #140

mdznr opened this issue May 7, 2021 · 0 comments

Comments

@mdznr
Copy link
Contributor

mdznr commented May 7, 2021

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.

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

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<Self> {
    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<Self> {
    AdjacentPairsCollection(base: self, wrapping: wrapping)
  }
}
@mdznr mdznr linked a pull request May 7, 2021 that will close this issue
7 tasks
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging a pull request may close this issue.

1 participant