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>
function isOdd(number) {
return number % 2 == 1;
}
function isNotOdd(number) {
return number % 2 !== 1;
}
function isEven(number) {
return number % 2 == 0;
}
function isNotEven(number) {
return number % 2 !== 0;
}
console.log(isOdd(5));
console.log(isNotOdd(2));
console.log(isEven(3));
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>
function isOdd(number) {
return number % 2 == 1;
}
function isNotOdd(number) {
return !isOdd(number);
}
function isEven(number) {
return number % 2 == 0;
}
function isNotEven(number) {
return !isEven(number);
}
console.log(isOdd(5));
console.log(isNotOdd(10));
console.log(isEven(3));
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>
function isOdd(number) {
return number % 2 == 1;
}
function isEven(number) {
return number % 2 == 0;
}
function negate(pre) {
return function (number) {
return !pre(number);
};
}
var isNotOdd = negate(isOdd);
var isNotEven = negate(isEven);
console.log(isOdd(5));
console.log(isNotOdd(10));
console.log(isEven(3));
console.log(isNotEven(4));
</script>
|
Output :
true
true
false
false
Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape,
GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out -
check it out now!
Last Updated :
30 Dec, 2022
Like Article
Save Article