Skip to content

Instantly share code, notes, and snippets.

@derek-knox
Last active January 18, 2018 18:16
Show Gist options
  • Save derek-knox/681955e1a709b50c17e829938ce2884a to your computer and use it in GitHub Desktop.
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?
// 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