编程语言
首页 > 编程语言> > javascript-使简单的搜索算法更优雅

javascript-使简单的搜索算法更优雅

作者:互联网

// 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;
}));

这遍历数组并将找到的第一个函数转换为组合函数.

我讨厌发现=虚假变量/计数器.我如何摆脱它?

作为一种算法.

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

更新资料

使用for循环

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

_.map__.isFunction_.compose

解决方法:

假设有短路评估:(我很快就混蛋了)

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)

编辑的问题,编辑的答案:

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

标签:underscore-js,ecmascript-5,javascript,algorithm
来源: https://codeday.me/bug/20191102/1992826.html