2

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)))
  • Will you please edit your question to show what you have tried so far? – Michael Jasper Jul 25 '18 at 01:10
  • not exact duplicate, but see https://stackoverflow.com/questions/36273977/are-currying-and-composition-the-same-concept-in-javascript for reference – Michael Jasper Jul 25 '18 at 01:12
  • Did you consider using https://ramdajs.com/docs/#compose ? – webNeat Jul 25 '18 at 01:12
  • Possible duplicate of [JavaScript function composition from 3 functions](https://stackoverflow.com/questions/41590061/javascript-function-composition-from-3-functions) – Michael Jasper Jul 25 '18 at 01:14
  • @webNeat is it possible to do it without importing libraries? –  Jul 25 '18 at 01:14
  • Of course it's possible without library, you can simply look at the source code and learn from it https://github.com/ramda/ramda/blob/master/source/compose.js – webNeat Jul 25 '18 at 01:25

1 Answers1

6

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)))
CertainPerformance
  • 356,069
  • 52
  • 309
  • 320
  • cool! works like a charm to me! I further shorten it into `const myFunction = (...fns) => arg => fns.reduce((a, fn) => fn(a), arg);` Thanks! –  Jul 25 '18 at 01:16