Created
May 18, 2020 20:07
-
-
Save jakehawken/0ec0d8a2b81e774ca0b8441815213ca6 to your computer and use it in GitHub Desktop.
A helper for comparing neighbors in an array
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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