I'm re-creating functions from the underscore library but I'm running into a roadblock while trying to implement the _.reject() function. For the purposes of this question, I'll include the code I've written for three functions: _.each(), _.filter(), and _.reject().
_.each = function(collection, iterator) { if (Array.isArray(collection)) { for (var i = 0; i < collection.length; i++) { iterator(collection[i], i, collection); } } else { for (var i in collection) { iterator(collection[i], i, collection); } } }; _.filter = function(collection, test) { var results = []; _.each(collection, function(i) { if (test(i)) { results.push(i); } }) return results; }; And here's the code for the function that I'm getting a problem with, the _.reject() method, along with the isEven() function that I'm passing in as the test argument.
_.reject = function(collection, test) { return _.filter(collection, !test); }; var isEven = function(x) { if (x % 2 === 0) return true; return false; }; According to MDN's page on Expressions and Operators, the Logical NOT (!) operator Returns false if its single operand can be converted to true; otherwise, returns true.
But when I run the following code _.reject([1,2,3], isEven) I get an error saying that test is not a function. Why am I unable to use the ! operator while invoking a function (e.g., _.filter([1,2,3], !isEven))?
!test()instead. Negating a function is meaningless. Negating a function's return value is more useful.!isEvenwould negate the return value.