In this article, we will see how to negate a predicate function in JavaScript. Predicate functions are the ones that check the condition and return true and false based on the argument. Our task is to get the opposite of the predicate function.
We follow the following method to get the desired result.
Method 1: 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.
Example: This example shows the above-explained approach.
Javascript
<script> // 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; } // Outputs: true console.log(isOdd(5)); // Outputs: true console.log(isNotOdd(2)); // Output: false console.log(isEven(3)); // Output> false console.log(isNotEven(4)); </script> |
Output:
true true false false
Method 2: 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.
Example: This example shows the above-explained approach.
Javascript
<script> // 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); } // Outputs: true console.log(isOdd(5)); // Outputs: true console.log(isNotOdd(10)); // Output: false console.log(isEven(3)); // Output> false console.log(isNotEven(4)); </script> |
Output :
true true false false
Method 3: 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.
Example: This example shows the above-explained approach.
Javascript
<script> // 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); // Outputs: true console.log(isOdd(5)); // Outputs: true console.log(isNotOdd(10)); // Output: false console.log(isEven(3)); // Output: false console.log(isNotEven(4)); </script> |
Output :
true true false false