使用函数-not(callback)反转回调的返回值



我有一个过滤函数,并向其中传递一个测试函数:

var array = [1,3,5,7,9]
function bigger(n){return n > 5}
function filterArray(data,testfn){
return data.filter(e=> testfn(e))}
console.log(filterArray(array,bigger))
>>>[7,9]

现在我想能够写

console.log(filterArray(array,not(bigger)))
>>>[1,3,5]

您可以创建一个函数not,该函数接收一个函数并返回另一个函数,该函数返回调用原始函数的结果的倒数:

var array = [1, 3, 5, 7, 9];
function bigger(n) {
return n > 5
}
function filterArray(data, testfn) {
return data.filter(e => testfn(e))
}
function not(f) {
return function(n) {
return !f(n);
}
}
console.log(filterArray(array, bigger));
console.log(filterArray(array, not(bigger)));

您可以这样做:

var array = [1, 3, 5, 7, 9]
const isBiggerThan = (n) => n > 5
const isNot = (fn) => (n) => !fn(n)
const filterArray = (data, testfn) => data.filter(e => testfn(e))    
console.log(filterArray(array, isBiggerThan))
console.log(filterArray(array, isNot(isBiggerThan)))

其思想是让isNot函数返回一个函数,该函数简单地否定作为参数传递的函数的结果。

我会做如下操作。

var array = [1,3,5,7,9]
function bigger(n){return n > 5}
console.log(array.filter(element => !bigger(element)))

要考虑可变函数:在数组"arguments"中收集参数并将其传递给函数。

function not(myFunction){
if (typeof myFunction != "function"){return !myFunction } 
return function (...arguments) {
return !myFunction.apply(null,arguments)
}
}

简而言之:

const not = f => (...a) => !f.apply(null,a)

此外,为了使其适用于所有值,请检查是否已传递函数。这也允许像这样使用not(bigger(1,2)):

function not(anything){
if (typeof anything != "function"){return !anything } 
return function (...arguments) {
return !anything.apply(null,arguments)
}
}

var variable = true
console.log(not(bigger(6))) >>> true
console.log(not(variable))) >>> false
console.log(not(false))) >>> true

简而言之:

const not = f => typeof f != "function" ? !f : (...a) => !f.apply(null,a)

最新更新