AniUI Academy

Negate a predicate

easyFunctions & Closures+150 XPPractice

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 true when the predicate returns a falsy value, and false when 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 this so 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 so this reaches the predicate when the result is used as a method.

Stuck? The javascript course covers everything this challenge needs.

Try it yourself
Loading playground...
5 tests · +150 XP

Discussion

Sign in to post
Sign in to join the conversation.Sign in

No comments yet. Be the first to say something.