We’ll see how to create a function that returns the opposite result of a predicate function.
- Predicate functions return
true or falsebased on a condition. - Negation flips the result of the predicate function.
- Makes your code more reusable and easier to maintain.
[Approach 1]: Recursive Iteration
Our Predicate function is checking for odd and even numbers. If the number is a module with 2, it returns 1 then it is odd, else it is even. Negate the logic while checking conditions for argument.
// Predicate function check odd
function isOdd(number) {
return number % 2 == 1;
}
// negation of isOdd function
function isNotOdd(number) {
return number % 2 !== 1;
}
// Predicate function check Even
function isEven(number) {
return number % 2 == 0;
}
// negation of isEven function
function isNotEven(number) {
return number % 2 !== 0;
}
console.log(isOdd(5));
console.log(isNotOdd(2));
console.log(isEven(3));
console.log(isNotEven(4));
Output:
true
true
false
false[Approach 2]: Predicate Negation
The problem with the above method is to we are hard-coding our logic at each negation. We probably have more chances to make mistakes in negation conditions. More effective is to negate the predicate function by checking the condition.
// Predicate function check odd
function isOdd(number) {
return number % 2 == 1;
}
// negation of isOdd function
function isNotOdd(number) {
return !isOdd(number);
}
// Predicate function check Even
function isEven(number) {
return number % 2 == 0;
}
// negation of isEven function
function isNotEven(number) {
return !isEven(number);
}
console.log(isOdd(5));
console.log(isNotOdd(10));
console.log(isEven(3));
console.log(isNotEven(4));
Output :
true
true
false
false[Approach 3]: Unified Predicate Negation
In the previous method, we are negating the function for all the predicate functions. But our solution can be more effective if we create one function that negates all the predicate functions. We make a predicate function and bind negate function with all predicate functions.
// Predicate function check odd
function isOdd(number) {
return number % 2 == 1;
}
// Predicate function check Even
function isEven(number) {
return number % 2 == 0;
}
// function that negate all function
function negate(pre) {
return function (number) {
return !pre(number);
};
}
// Wrapping predicate function to negate function
var isNotOdd = negate(isOdd);
var isNotEven = negate(isEven);
console.log(isOdd(5));
console.log(isNotOdd(10));
console.log(isEven(3));
console.log(isNotEven(4));
Output :
true
true
false
false