Home > Net >  How to create a composition from functions
How to create a composition from functions

Time:10-25

I have 5 functions: func1(), func2(), func3(), func4(), func5(). I need to implement the compositionFunc() function, which can take any number of functions as arguments, and create a composition from them. The compositionFunc() function takes my 5 functions as arguments. The compositionFunc() function returns a function that takes its initial value as an argument. This nested function successively passing through an array of functions with each iteration returns the result of calling the accumulated value of the current function-argument. The result of one function can be passed as an argument to another function. How can i do this?

const func1 = (arg1) => {
  return arg1;
};
const func2 = (arg2) => {
  return arg2;
};
const func3 = (arg3) => {
  return arg3;
};
const func4 = (arg4) => {
  return arg4;
};
const func5 = (arg5) => {
  return arg5;
};

const compositionFunc = () => {
  ...
};

CodePudding user response:

A simple reduce can accomplish that:

function pipe(input, ...func) {
    return func.reduce((res, f) => f(res), input);
}

You pass it an initial value chain of functions that all take same-type value...

Example:

function f1(val) {
    return val   1;
}

function f2(val) {
    return val * 10;
}

console.log(pipe(2, f1, f2)); //=> 30

CodePudding user response:

you can define a function like this

const pipe = (...functions) => args => functions.reduce((res, f) => f(res), args)

const combine = (...functions) => args => functions.reduceRight((res, f) => f(res), args)

const plus1 = x => x   1

const double = x => x * 2

const pipeFunction = pipe(plus1, double)
const combineFunction = combine(plus1, double)


console.log(combineFunction(1)) // (1 * 2)   1 
console.log(pipeFunction(1)) // (1   1) * 2

  • Related