msmialko
(Michal)
1
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?
jjatie
2
windows(ofCount: 3) should work for you
1 Like
msmialko
(Michal)
3
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]
jjatie
4
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.
Jon_Shier
(Jon Shier)
5
You can do this in Combine using Zip3 with nil + sequence.dropLast(), sequence, and sequence.dropFirst() + nil.