对于一项任务,我正在努力重新创建下划线的_.every()和_.some()函数以传递一组规范。但是,我无法使用没有回调函数的函数。这是规格(两个功能的规格相同):
it('should work when no callback is provided', function() {
expect(_.some([true, true, true])).to.be.true;
expect(_.some([true, true, false])).to.be.true;
expect(_.some([false, false, false])).to.be.false;
}
这是代码:
// Determine whether all of the elements match a truth test.
197 _.every = function(collection, iterator) {
198 return _.reduce(collection, function(trueCheck, item) {
199 if (!trueCheck) {return false;}
200 if (item === true || iterator(item)){
201 return true;
202 }
203 else return false;
204 }, true);
205 };
206
207 // Determine whether any of the elements pass a truth test. If no iterator is
208 // provided, provide a default one
209 _.some = function(collection, iterator) {
210 var isAllFalse = _.every(collection, function(item) {
211 return !iterator(item);
212 });
213 if (isAllFalse === true) {
214 return false;
215 }
216 return true;
217 };
218
任何建议将不胜感激,谢谢!
最佳答案
我会使用普通的Javascript:
var _ = _ || {};
_.every = function(collection, iterator) {
for (var i = collection.length - 1; i >= 0; i--) {
if (!collection[i]) return false;
}
return true;
};
_.some = function(collection, iterator) {
for (var i = collection.length - 1; i >= 0; i--) {
if (collection[i]) return true;
}
return false;
};
console.log(_.every([true, 'is', 1])); //true
console.log(_.every([true, 'is', false])); //false
console.log(_.some([null, '', 0, false])); //false
console.log(_.some([true, 'is', false])); //true