How to negate a boolean function?
Such that using something like:
_.filter = function(collection, test) {
var tmp = []
_.each(collection, function(value){
if (test(value)) {
tmp.push(value);
}
})
return tmp
};
var bag = [1,2,3];
var evens = function(v) { return v % 2 === 0};
This is wrong:
// So that it returns the opposite of evens
var result = _.filter(bag, !evens);
result:
[1,3]
Underscore has a .negate() API for this:
_.filter(bag, _.negate(evens));
You could of course stash that as its own predicate:
var odds = _.negate(evens);
then
_.filter(bag, odds);
Try making a function that returns a function:
function negate(other) {
return function(v) {return !other(v)};
};
Used like this:
var result = _.filter(bag, negate(evens));
Or just declare a function when you call it:
var result = _.filter(bag, function(v) {return evens(v)});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With