简体   繁体   English

我将如何创建逆序高阶函数?

[英]How would I create an invert higher order function?

I need to create a higher-order function called invert. 我需要创建一个称为反转的高阶函数。 It should do the following: 它应该执行以下操作:

Return a new function. 返回一个新函数。 Take a function as its only argument. 将函数作为唯一参数。 The inner function should take any number of arguments and inverts a call to the passed function. 内部函数应采用任意数量的参数,并反转对传递的函数的调用。

What I have so far is just http://prntscr.com/l0rma0 but it only works for functions with no arguments. 到目前为止,我所拥有的只是http://prntscr.com/l0rma0,但它仅适用于不带参数的函数。

Hopefully, this should be enough: 希望这应该足够了:

function invert(fn) {
  return (...args) => !fn(...args);
}

Here's the test case: 这是测试用例:

 function invert(fn) { return (...args) => !fn(...args); } // test 1 const returnsTrue = () => true; const returnsFalse = invert(returnsTrue); console.log( returnsFalse() === false ); // test 2 const isEven = x => x % 2 === 0; const isOdd = invert(isEven); console.log( isOdd(13) === true ); console.log( isOdd(10) === false ); // test 3 const isSumBiggerThan100 = (...args) => args.reduce((acc, val) => acc + val) > 100; const isSumLessThanOrEqualTo100 = invert(isSumBiggerThan100); console.log( isSumLessThanOrEqualTo100(10, 3, 8, 5, 4, 20) === true); console.log( isSumLessThanOrEqualTo100(70, 10, 50, 23) === false) 

const higherFunction = (something) => {
  return function innerFunc(...params) {
    return !something;
  }
};

Do you mean something like that ? 你的意思是那样吗?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM