Skip to content

Instantly share code, notes, and snippets.

@jakehawken
Created May 18, 2020 20:07
Show Gist options
  • Save jakehawken/0ec0d8a2b81e774ca0b8441815213ca6 to your computer and use it in GitHub Desktop.
Save jakehawken/0ec0d8a2b81e774ca0b8441815213ca6 to your computer and use it in GitHub Desktop.
A helper for comparing neighbors in an array
extension Array {
func forEachAdjacent(do block: ((Element, Element))->()) {
guard count > 1 else {
return
}
var secondIndex = 1
while secondIndex < count {
let firstVal = self[secondIndex - 1]
let secndVal = self[secondIndex]
block(firstVal, secndVal)
secondIndex += 1
}
}
func adjacentMap<T>(_ block: (Element, Element)->T) -> [T] {
var newArray = [T]()
forEachAdjacent { (current, next) in
let newElement = block(current, next)
newArray.append(newElement)
}
return newArray
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment