[英]Re-Creating Underscore.js _.reject Using _.filter
I am working on a project where I am re-creating many of the fundamental functions included in Underscore.js. 我正在一个项目中重新创建Underscore.js中包含的许多基本功能。 I have successfully written the _.filter() function, using my implementation of _.each() (both are below). 我已经使用_.each()的实现成功编写了_.filter()函数(均在下面)。
Additionally, I have been able to write the _.reject() function using the "easy" way out (simply copy/pasting the _.filter() code and adding the ! in the appropriate place), but for the learning experience, I am looking to develop an alternate implementation that uses actually calls _.filter(). 此外,我已经能够使用“简单”的方法编写_.reject()函数(只需复制/粘贴_.filter()代码并在适当的位置添加!),但是为了获得学习经验,我正在寻找一个使用实际调用_.filter()的替代实现。
I've seen questions and responses that show how to do this using another Underscore function, _.negate(), but I haven't implemented this function yet in the project, so my question is, is there a way to create _.reject() using a call to the _.filter() function WITHOUT using _.negate()? 我已经看到问题和响应,这些问题和响应显示了如何使用另一个Underscore函数_.negate()来执行此操作,但是我尚未在项目中实现此功能,所以我的问题是,有没有一种创建_的方法。不使用_.negate()而调用_.filter()函数来拒绝()?
_.filter: _。过滤:
_.filter = function(collection, test) {
var results = [];
_.each(collection, function(itemTested) {
if (test(itemTested)) {
results.push(itemTested);
}
});
return results;
};
_.each: _。每:
_.each = function(collection, iterator) {
if(Array.isArray(collection)) {
for(var i = 0; i < collection.length; i++) {
iterator(collection[i], i, collection);
}
}
else {
for(var property in collection) {
iterator(collection[property], property, collection);
}
}
};
Current version of _.reject: _.reject的当前版本:
_.reject = function(collection, test) {
var results = [];
_.each(collection, function(itemTested) {
if (!test(itemTested)) {
results.push(itemTested);
}
});
return results;
};
Reject function using filter: 使用过滤器拒绝功能:
var _ = {};
_.reject = function(col, fn) {
return col.filter(function(v) {
return !fn(v);
});
}
// or using your _.filter function
_.reject = function(col, fn) {
return _.filter(col, function(v) {
return !fn(v);
});
}
var odd = _.reject([1, 2, 3, 4, 5, 6], function(num) { return num % 2 == 0; });
console.log(odd); // [1,3,5]
JS Bin Example JS Bin示例
Well, even if you're not calling _.negate
, you still gives you an idea what it would do: 好吧,即使您没有调用 _.negate
,您仍然可以了解它会做什么:
_.reject = function(collection, test) {
return _.filter(collection, function(el, i, collection) {
return !test(el, i, collection);
});
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.