How to test a value x against predicate function and returns fn(x) or x in JavaScript ?
Last Updated :
03 Jan, 2023
In this article, we are given a value x, and the task is to check the value against the predicate function. If the value satisfies the condition or predicate return fn(x) else return x.
Predicate functions are the function that takes one item as input and returns true or false based on the whether item satisfies that condition or not.
Example 1: In this example, we have given a number and a condition, if condition is true then it returns the fn(number) otherwise it returns a simple numeric value.
Javascript
<script>
function fn(x) {
let fact = 1;
for (i = 1; i <= x; i++) {
fact *= i;
}
return fact;
}
function isEven(x) {
return (x % 2 === 0);
}
function test(x) {
let e = isEven(x);
if (e) {
return fn(x);
} else
return x;
}
let ans = test(6);
console.log(`This function returns ${ans}`);
</script>
|
Output: Here the condition is a number that should be even because our input data is even so it returns the fn(6) value.
This function returns 720
Example 2: In this example, we have given a number and a test condition, if condition is true then it returns the fn(number) otherwise it returns number value only.
Javascript
<script>
let max_Integer = 20;
function fn(x) {
var b = 0;
var a = 1;
var sum;
for (i = 0; i < x - 1; i++) {
sum = a + b;
b = a;
a = sum;
}
return a;
}
function isless(x) {
return (x < max_Integer);
}
function test(x) {
let e = isless(x);
if (e) {
return fn(x);
} else
return x;
}
let ans = test(15);
console.log(`This function returns ${ans}`);
</script>
|
Output:
The function returns 610
Example 3: In this example, we have given a number and a test condition, if condition is true then it returns the fn(number) otherwise it returns number value only.
Javascript
<script>
function fn(x) {
let j = 1;
for (i = 0; i < x - 1; i++) {
j = j * x;
}
return j;
}
function ismultiple(x) {
return (x % 3 == 0);
}
function test(x) {
let e = ismultiple(x);
if (e) {
return fn(x);
} else
return x;
}
let ans = test(6);
console.log(`This function returns ${ans}`);
</script>
|
Output:
This function returns 7776
Share your thoughts in the comments
Please Login to comment...