1

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?

4
  • 4
    Not sure what you're asking. Are you just looking for ! (logical 'not')? As in fInv = x => !f(x) ? Commented Dec 3, 2021 at 20:05
  • It seems that you want to negate the result. Commented Dec 3, 2021 at 20:05
  • In your trivial example, fInv is effectively "not f". For arbitrary functions, it depends on what behavior you expect, I suppose. Might work OK for pure functions that simply return boolean. Commented Dec 3, 2021 at 20:06
  • @MarkReed Yes! I totally missed that. Thanks Commented Dec 3, 2021 at 20:10

1 Answer 1

5

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

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

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.