In JavaScript, we can test a value against a predicate function and apply another function to it when the condition is satisfied. If the predicate returns true, fn(x) is returned; otherwise, the original value x is returned.
- A predicate function takes a value as input and returns true or false.
- The specified function is executed only when the predicate returns true.
- If the predicate returns false, the original value is returned.
- This approach is useful for performing conditional transformations on values.
Approach 1: Using an Even Number Predicate
In this approach, the value is checked using an isEven() predicate function. If the value is even, its factorial is calculated; otherwise, the original value is returned.
function factorial(x) {
let fact = 1;
for (let i = 1; i <= x; i++) {
fact *= i;
}
return fact;
}
function isEven(x) {
return x % 2 === 0;
}
function test(x) {
if (isEven(x)) {
return factorial(x);
}
return x;
}
const result = test(6);
console.log(`This function returns ${result}`);
Output
This function returns 720
Approach 2: Using a Comparison Predicate
In this approach, the predicate function checks whether the given value is less than a specified maximum value. If the condition is satisfied, the Fibonacci value is returned; otherwise, the original value is returned.
const maxValue = 20;
function fibonacci(x) {
if (x <= 1) {
return x;
}
let previous = 0;
let current = 1;
for (let i = 2; i <= x; i++) {
const next = previous + current;
previous = current;
current = next;
}
return current;
}
function isLess(x) {
return x < maxValue;
}
function test(x) {
if (isLess(x)) {
return fibonacci(x);
}
return x;
}
const result = test(15);
console.log(`This function returns ${result}`);
Output
This function returns 610
Approach 3: Using a Multiple-of-Three Predicate
In this approach, the predicate function checks whether the given value is a multiple of 3. If the condition is satisfied, the value is raised to its own power; otherwise, the original value is returned.
function powerOfSelf(x) {
return x ** x;
}
function isMultipleOfThree(x) {
return x % 3 === 0;
}
function test(x) {
if (isMultipleOfThree(x)) {
return powerOfSelf(x);
}
return x;
}
const result = test(6);
console.log(`This function returns ${result}`);
Output
This function returns 46656
Approach 4: Using a Higher-Order Function
A more reusable approach is to pass the predicate function and the function to be executed as arguments to a higher-order function.
- The predicate function checks the condition.
- The fn function performs the required operation.
- If the predicate returns true, fn(x) is returned.
- Otherwise, x is returned.
function test(x, predicate, fn) {
if (predicate(x)) {
return fn(x);
}
return x;
}
function isEven(x) {
return x % 2 === 0;
}
function square(x) {
return x * x;
}
console.log(test(6, isEven, square));
console.log(test(5, isEven, square));
Output
36 5