最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

negate boolean function in javascript - Stack Overflow

programmeradmin5浏览0评论

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
Add a ment  | 

2 Answers 2

Reset to default 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);

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)});
发布评论

评论列表(0)

  1. 暂无评论