Negate a predicate
You have a predicate and you need its opposite. Writing items.filter((x) => !isArchived(x)) works, but once you are composing filters you want the negated predicate as a value you can pass around and name.
Implement negate(predicate). It returns a new function that forwards every argument, and its this, to predicate, and returns the boolean opposite of the result. The return value is always a real boolean: a truthy result such as the string "hello" becomes false, and a falsy result such as 0 becomes true.
Arguments
predicateFunction- A function returning a value that should be coerced and negated.
Returns
Function — A new predicate that returns true where predicate was falsy, and false where it was truthy.
Examples
const isEven = (n) => n % 2 === 0;
const isOdd = negate(isEven);
[1, 2, 3, 4].filter(isOdd); // [1, 3]Negating gives you a named predicate you can hand off instead of an inline !….
const alwaysTruthy = negate(() => "hello");
alwaysTruthy(); // false — the string becomes false, not "hello"What it has to do
- Return
truewhen the predicate returns a falsy value, andfalsewhen it returns a truthy one. - Always return an actual boolean, never the negated operand itself.
- Forward every argument the wrapper receives to the predicate.
- Preserve
thisso a negated predicate works as an object method.
Notes
!predicate.apply(this, args)does the boolean coercion for free — the!operator always returns a true boolean, which the spec requires.- Use
function (...args)rather than an arrow function sothisreaches the predicate when the result is used as a method.
Stuck? The javascript course covers everything this challenge needs.
- 1.flips a simple predicate
- 2.forwards every argument
- 3.returns a real boolean for truthy and falsy results
- 4.works inside filter
- 5.preserves this
These assertions run in your browser the moment you hit Run. Pass all of them to claim the XP.
Discussion
Sign in to postNo comments yet. Be the first to say something.