简体   繁体   中英

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 loops through the array and turns the first function it finds into a composed function.

I hate that found = false variable / counter. How do I get rid of it?

As 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

I don't know if this answers your need for elegance, but it seems to me like _.each() or forEach is wasting extra loops after the item has been found. With a traditional for or while loop, you could call break at that point. Not a big deal with a small array, but it could become an issue for a larger array or a complex condition check. If you want to avoid the constant array[x] references, you could get a little fancier than the obvious option:

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

assuming short-circuit evaluation: (which I promptly bastardise)

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM