开发者

Make a simple search algorithm more elegant

开发者 https://www.devze.com 2023-03-06 19:58 出处:网络
// temp data var array = [1,2,function() { }, 3, function() { }]; var cb = function() { console.log(\"foo\"); }
// 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;
}));
开发者_如何学C

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
0

精彩评论

暂无评论...
验证码 换一张
取 消