Created
March 8, 2018 21:47
-
-
Save elliottsj/9a2814ade4a78885583d0a930b18cf26 to your computer and use it in GitHub Desktop.
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
/** | |
* Scan the given array to find the index of the element which satisfies the predicate, | |
* which receives the previous, current, and next elements every iteration. | |
* | |
* The `current` element is the element at the "current" index, so returning true in the predicate | |
* will cause `findIndex3` to return the index of the `current` element. | |
* | |
* `previous` will be undefined on the first iteration, and `current` and `next` will be undefined | |
* on the previous iteration. | |
* | |
* If the predicate is not satisfied, a value of -1 is returned. | |
* | |
* @example | |
* > findIndex3([1, 2, 3], (previous, current, next) => { console.log(previous, current, next) }); | |
* undefined, 1, 2 | |
* 1, 2, 3 | |
* 2, 3, undefined | |
* 3, undefined, undefined | |
* < -1 | |
* | |
* @example | |
* > findIndex3( | |
* [1, 2, 3], | |
* (previous, current, next) => previous && previous % 2 === 1 && next && next % 2 === 1 | |
* ); | |
* < 1 | |
*/ | |
export function findIndex3<T>(array: T[], predicate: (previous?: T, current?: T, next?: T) => boolean) { | |
for (let i = 0; i <= array.length; i++) { | |
if (predicate(array[i - 1], array[i], array[i + 1])) { | |
return i; | |
} | |
} | |
return -1; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment