Last active
January 18, 2018 18:16
-
-
Save derek-knox/681955e1a709b50c17e829938ce2884a to your computer and use it in GitHub Desktop.
Is there a native `reduceLazy()`-like method in JavaScript that has the behavior as below?
This file contains 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
// example list | |
var list = [ { id: 0 }, { id: 1 }, { id: 2 } ]; | |
// desired behavior | |
function reduceLazy(arr, prop, val) { | |
for(var i = 0, len = arr.length; i < len; i++) { | |
console.log('iteration', i); | |
if(arr[i][prop] === val){ | |
console.log('found at', i, 'exit now'); | |
return arr[i]; | |
} | |
} | |
} | |
// example use | |
console.log(reduceLazy(list, 'id', 1)); | |
// reduceLazy() exits early where a reduce() would hit all array elements | |
// Is there a built-in method (sans logs obviously) that accomplishes this? |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment