Make a simple search algorithm more elegant

// temp data
var array = [1,2,function() { }, 3, function() { }];
var cb = function() { console.log("foo"); }


var found = false;
console.log(_.map(array, function(val) {
    if (_.isFunction(val) && !found) {
        return found = true, _.compose(cb, val);
    } 
    return val;
}));

This loop goes through the array and turns the first function that it finds into a folded function.

I hate this variable / counter found = false. How can I get rid of it?

Like an algorithm.

let found be 0
map value in array
    if value satisfies condition and found is 0
        let found be 1
        return mutate(value)
    else
        return value

Update

Using a for loop

for (var i = 0; i < array.length; i++) {
    if (_.isFunction(array[i])) {
        array[i] = _.compose(cb, array[i]);
        break;
    }
}

_.map, _, _.isFunction,_.compose

+3
source share
2 answers

assuming short circuit rating: (which I quickly tire)

let found be 0
for each value in array
    if value satisfies condition and found is 0 and let found be not found
        let value be mutate(value)

edited problem, edited answer:

let found be 0
for each value in array
  return ( value satisfies condition and found is 0 and let found be not found ) ? mutate(value) : value
+1
source

, , , _.each() forEach , . for while break . , . array[x], , :

for (var val, x=0; x<array.length; val=array[++x]) {
    if (_.isFunction(val)) {
        array[x] = _.compose(cb, val);
        break;
    }
}
+3

All Articles