Negate a predicate, preserving this and async thenable results
A form library lets you combine validators: isEmpty, isTaken, isInRange, and so on. Instead of writing an “is not” version of each one, the library ships a helper that flips any predicate. Some validators are methods that read this, and some are async because they ask the server.
Implement invert(predicate). It returns a new function that answers the opposite question.
const isNotX = invert(isX);
isNotX(...args) // => boolean, or Promise<boolean> for async predicates
predicate exactly once, with the same this and all of the same arguments.true when that value is falsy and false when it is truthy. Always a real boolean.then method, such as a promise), return a native Promise that resolves to the negated boolean of the awaited value. If it rejects, the returned promise rejects with the same reason.length equals predicate.length, so libraries that look at a validator’s arity keep working.invert throws a TypeError right away if predicate is not a function.const isEven = (n) => n % 2 === 0;
[1, 2, 3, 4].filter(invert(isEven)); // => [1, 3]
invert((value) => value)(0); // => true
const range = {
min: 1,
max: 5,
contains(n) { return n >= this.min && n <= this.max; },
};
range.excludes = invert(range.contains);
range.excludes(7); // => true
const isTaken = async (name) => name === 'admin';
await invert(isTaken)('mina'); // => true
invert((a, b) => a < b).length; // => 2
invert('nope'); // throws TypeError