Also known as function pipelines.
Functional composition is the idea of creating a new function by passing the output of one function directly into another. It allows complex behavior to emerge from small, simple pieces. It can be pictured as a relay race where one runner hands the baton to the next. Each function does its part, and the final result comes from their combined flow.
Instead of writing: Math.sqrt(minusOne(double(square(42))));
It can be rewritten to be more readable and modular by looping over an array of functions.
Defining simple functions (actions):
const double = x => x * 2;
const minusOne = x => x - 1;
const square = x => x * x;
These small arrow functions:
-
double(x): multiplies by 2 -
minusOne(x): subtracts 1 -
square(x): multiplies a number by itself -
Math.sqrt: built-in function taking the square root
Then building an array from these functions:
const functions = [
square,
double,
minusOne,
Math.sqrt,
];
Order here matters too. Keep in mind that it's not calling the functions here; instead, it's storing their references in an array.
Next, call each function (in order) with a starting value defined (as a number):
let result = 42; // starting magic number
for (const fn of functions) {
result = fn(result);
}
This loop:
1. Takes the current result.
2. Passes it into the next function.
3. Stores the output back into the result.
Which will perform as:
result = square(42)
result = double(result)
result = minusOne(result)
result = Math.sqrt(result)
To understand this fully, let's compute the steps:
-
Step 1:
square(42)= 42 * 42 = 1764 -
Step 2:
double(1764)= 1764 * 2 = 3528 -
Step 3:
minusOne(3528)= 3528 - 1 = 3527 -
Step 4:
Math.sqrt(3527)= ≈ 59.380
And so, the final output and final code:
const double = x => x * 2;
const minusOne = x => x - 1;
const square = x => x * x;
const functions = [
square,
double,
minusOne,
Math.sqrt,
];
let result = 42; // starting number
for (const fn of functions) {
result = fn(result);
}
console.log('The answer is ' + result);
// The answer is 59.380217
Top comments (0)