Introduction
In this lab, we will explore the concept of function composition in JavaScript. Specifically, we will focus on the composeRight function, which allows us to combine multiple functions into a single function that is executed from left to right. Through practical examples, we will see how function composition can simplify our code and make it more modular.
Reversing Function Composition
To start practicing coding, open the Terminal/SSH and type node.
Here's how to perform left-to-right function composition:
- Use
Array.prototype.reduce()method to perform left-to-right function composition. - The first (leftmost) function can accept one or more arguments, while the remaining functions must be unary.
const composeRight = (...fns) =>
fns.reduce(
(f, g) =>
(...args) =>
g(f(...args))
);
For example:
const add = (x, y) => x + y;
const square = (x) => x * x;
const addAndSquare = composeRight(add, square);
addAndSquare(1, 2); // 9
Summary
Congratulations! You have completed the Reverse Compose Functions lab. You can practice more labs in LabEx to improve your skills.