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]
0

2 Answers 2

6

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);
Sign up to request clarification or add additional context in comments.

Comments

4

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)});

1 Comment

Thanks for showing me this. I used function(v) {return !evens(v)}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.