In C#, we have Enumerable.First(predicate). Given this JavaScript code:
function process() {
var firstMatch = ['a', 'b', 'c'].filter(function(e) {
return applyConditions(e);
}).shift();
if(!firstMatch) {
return;
}
// do something else
}
function applyConditions(element) {
var min = 97;
var max = 122;
var random = Math.floor(Math.random() * (max - min + 1) + min);
return element === String.fromCharCode(random);
}
other than forEach, using loop, using multiple or operators or implicitly calling some(predicate), is there a smarter way of finding the firstMatch? Preferably a JavaScript function (something like filterFirst(pedicate)) which short-circuits on first match resembling C#'s Enumerable.First() implementation?
FWIW, I am targeting node.js / io.js runtimes.
No need to reinvent the wheel, the correct way to do it is to use .find:
var firstMatch = ['a', 'b', 'c'].find(applyConditions);
If you're using a browser that does not support .find you can polyfill it
LINQ users call first and firstOrDefault a lot with no predicate, which is not possible with find. So,
first() {
var firstOrDefault = this.firstOrDefault();
if(firstOrDefault !== undefined)
return firstOrDefault;
else
throw new Error('No element satisfies the condition in predicate.');
}
firstOrDefault() {
return this.find(o => true);
}
You could emulate this in the case where you want to return the first truthy value with reduce.
['a', 'b', 'c'].reduce(function(prev, curr) {
return prev || predicate(curr) && curr;
}, false);
edit: made more terse with @BenjaminGruenbaum suggestion