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]
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]
Share
Improve this question
asked Apr 9, 2015 at 18:09
jmunschjmunsch
24.2k11 gold badges100 silver badges120 bronze badges
0
2 Answers
Reset to default 6Underscore 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)});