Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

negate boolean function in javascript

Tags:

javascript

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]
like image 672
jmunsch Avatar asked Aug 12 '26 20:08

jmunsch


2 Answers

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);
like image 57
Pointy Avatar answered Aug 15 '26 08:08

Pointy


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)});
like image 22
Linuxios Avatar answered Aug 15 '26 09:08

Linuxios