user10130560
user10130560

Reputation:

How can I create a function that performs multiple composition?

I wanted to combine two or more functions to produce a new function.

How can I create a function that performs left-to-right function compositions by returning a function that accepts one argument?

For example:

const square = v => v * v;
const double = v => v * 2;
const addOne = v => v + 1;

const cal = myFunction(square, double, addOne);
cal(2) // 9; addOne(double(square(2)))

Upvotes: 2

Views: 127

Answers (1)

CertainPerformance
CertainPerformance

Reputation: 370729

You might have myFunction turn the passed functions into an array with rest parameters, and then return a function that iterates over the array with reduce, passing in the passed argument as the initial value:

const myFunction = (...fns) => arg => fns.reduce(
  (a, fn) => fn(a),
  arg
);

const square = v => v * v;
const double = v => v * 2;
const addOne = v => v + 1;

const cal = myFunction(square, double, addOne);
console.log(cal(2)) // 9; addOne(double(square(2)))

Upvotes: 6

Related Questions