1

I have a filtering function and i pass a testing function into it:

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]

now id like to be able to write

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

4 Answers 4

4

You can create a function not that takes in a function and returns another function which returns the inverse of the result of calling the original function:

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)));

Sign up to request clarification or add additional context in comments.

Comments

1

You can do something like this:

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)))

The idea is to have the isNot function return a function which simply negates the result of the passed as parameter function.

Comments

0

I would do something like the following.

var array = [1,3,5,7,9]
function bigger(n){return n > 5}

console.log(array.filter(element => !bigger(element)))

1 Comment

the point was to make it modular so i can exchange bigger with: larger,fewer,longer, etc.
0

To account for variadic functions: Collecting arguments in an array "arguments" and passing them on to the function.

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

in short:

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

Also to make it work for all values - check if a function has been passed. which also allows to use it like so 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

in short:

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.