DEV Community

Cover image for Functional composition and lodash
ajay komirishetty
ajay komirishetty

Posted on

Functional composition and lodash

In functional programming, functional composition is snapping together a series of functions.
for example:

// code to trim a string
let trim = str => str.trim();
// code to convert string into lowercase
let lowerCase = str => str.toLowerCase();
//code tp wrap a string inside a div
let wrapper = str => <div>${str}</div>;
console.log(wrapper(lowerCase(trim(" HELLO WORLD! "))))
Enter fullscreen mode Exit fullscreen mode

Here, i have a string “ HELLO WORLD! ” , i want to to
a. trim the string (removing spaces on both the sides)

b. convert the string into lowercase

c. wrap the string inside a div
in the above example, I have called a function and passing the output of a function as a parameter to another.
Here, as the functions increase, the complexity to read the code increases, debugging will be difficult as well.

To solve this problem, we can use lodash

Steps to use lodash in your project:

a. Install lodash package

npm install lodash
Enter fullscreen mode Exit fullscreen mode

b. include lodash reference

include {compose, pipe } from "lodash/fp"
let trim = str => str.trim();
let lowerCase = str => str.toLowerCase();
let wrapper = str => `<div>${str}</div>`;
const newString = pipe(trim, lowerCase, wrapper);
console.log(newString("HEllo WORLD"))
Enter fullscreen mode Exit fullscreen mode

In the above example, i have used pipe, where we can give a sequence of functions that needs to be executed on a given input. (executed from left to right)

c. If you wish to give the sequence of functions from right to left, we can use compose

include {compose, pipe } from "lodash/fp"
let trim = str => str.trim();
let lowerCase = str => str.toLowerCase();
let wrapper = str => `<div>${str}</div>`;
const newString = compose(wrapper, lowercase, trim);
console.log(newString("HEllo WORLD"))
Enter fullscreen mode Exit fullscreen mode

Top comments (0)