JavaScript - 所有功能都是真实的

时间:2017-05-17 20:34:59

标签: javascript

我有n个函数,每个函数都使用'data'{Object}作为参数。每个函数根据给定的参数返回{Boolean}。

我想编写/链接这些函数,实现它的最佳方法是什么?

见下面的代码。

var fn1 = function(data) {
  return data.status === 404;
};
var fn2 = function(data) {
  return data.url === 'any_url';
};

var composed = compose(fn1, fn2);

// The line below must return false:
composed({ status: 404, url: 'foobar'});

// The line below must return true:
composed({ status: 404, url: 'any_url'});

2 个答案:

答案 0 :(得分:4)

如果所有函数都返回true,您想要返回true吗?这可以通过Array#every来实现。我们只是在函数数组上使用Array#every并在回调中返回函数的结果:

function compose() {
  var fns = Array.prototype.slice.call(arguments);
  return function(obj) {
    return fns.every(function(f) {
      return f(obj);
    });
  };
}



function compose() {
  var fns = Array.prototype.slice.call(arguments);
  return function(obj) {
    return fns.every(function(f) {
      return f(obj);
    });
  };
}


var fn1 = function(data) {
  return data.status === 404;
};
var fn2 = function(data) {
  return data.url === 'any_url';
};

var composed = compose(fn1, fn2);

// The line below must return false:
console.log(composed({
  status: 404,
  url: 'foobar'
}));

// The line below must return true:
console.log(composed({
  status: 404,
  url: 'any_url'
}));




这样做的好处是,只要一个返回值为Array#everyfalse就会停止。

使用ES6 +:

function compose(...fns) {
  return obj => fns.every(f => f(obj));
}

注意: compose是一个糟糕的名称选择,因为"composing functions"通常是指将一个函数的结果传递给另一个函数。即compose(f, g)(x)f(g(x))相同。

答案 1 :(得分:0)

你可以做一些简单的事情

function compose(data){
  return fn1(data) && fn2(data)
}

如果所有条件(函数的返回值)都为真,则此函数将返回true