让简单的搜索算法变得更加优雅
// 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;
}));
这会循环遍历数组,并将找到的第一个函数转换为组合函数。
我讨厌那个 found = false
变量/计数器。我该如何摆脱它?
作为一种算法。
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;
}
}
// 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;
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我不知道这是否满足您对优雅的需求,但在我看来,
_.each()
或forEach
在找到该项目后浪费了额外的循环。使用传统的for
或while
循环,您可以在此时调用break
。对于小数组来说并不是什么大问题,但对于较大的数组或复杂的条件检查可能会成为问题。如果您想避免常量array[x]
引用,您可以比明显的选项更奇特:I don't know if this answers your need for elegance, but it seems to me like
_.each()
orforEach
is wasting extra loops after the item has been found. With a traditionalfor
orwhile
loop, you could callbreak
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 constantarray[x]
references, you could get a little fancier than the obvious option:假设短路评估:(我立即将其混为一谈)
编辑问题,编辑答案:
assuming short-circuit evaluation: (which I promptly bastardise)
edited problem, edited answer: