Mapping array with the access to previous and next element

Is there any algorithm in Swift Core or Swift Algorithms Package that would allow mapping collection's elements based on the tuple (previousElement, currentElement, nextElement) ?

Example:

let a = [1, 2, 3, 4].withNeighborElements()
// [ (nil, 1, 2), (1, 2, 3), (2, 3, 4), (3, 4, nil) ]

If no, what would be the best way to implement this efficiently?

windows(ofCount: 3) should work for you

1 Like

I think windows are not the best fit here.

  • [1].windows(ofCount: 3) would equal []. wheres we'd like to have [nil, 1, nil]
  • windows will never return nil for next / previous element. So we'd need to manually add the "first" and "last" window. Something like this:
    [nil, array[0], array[1]] + array.windows(ofCount: 3) + [array[lastIdx-1] array[lastIdx], nil]

If you do need the empty neigbours at the start/end of the collection, it shouldn't be too much work to update the implementation for your use case. You can also look at AdjacentPairs.

You can do this in Combine using Zip3 with nil + sequence.dropLast(), sequence, and sequence.dropFirst() + nil.

Terms of Service

Privacy Policy

Cookie Policy