Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Is it possible to get an "inverse" function of a Boolean function in javascript?

I was looking to write an "all-or-nothing" function over an array. One approach is, of course, to leverage Array.prototype.every and do something like

function allOrNothing(arr, f, fInv) {
  return arr.every(f) || arr.every(fInv);
}

where f and fInv are indicator functions, and fInv is an "inverse" function of f. For example, if f = (x) => x != null, then fInv = (x) => x == null.

This leads me to think: is it possible to get the function fInv from f?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

This function, given a function f as an input, returns its boolean inverse:

let invert = (f) => (x) => !f(x)

e.g.

let invert = (f) => (x) => !f(x)

let eq_five = (x) => x == 5
let neq_five = invert(eq_five)

console.log(eq_five(5)) // true
console.log(neq_five(5)) // false
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading