Reputation: 1500
I am trying to re-implement function composition using reduceRight
. Here is a function composition that I am trying to re-implement:
const compose = function([func1, func2, func3]) {
return function(value1, value2) {
return func1(func2(func3(value1, value2)));
};
};
const func3 = (x, y) => {
return y > 0 ? x + 3 : x - 3;
};
const func2 = x => {
return x ** 2;
};
const func1 = x => {
return x - 8;
};
const fn = compose([func1, func2, func3]);
console.log(fn('3', 1)); // 1081
console.log(fn('3', -1)); // -8
The following code is re-implementation of the above function. It looks like the argument y
is getting undefined
I am not sure why.
const compose = (...args) => value =>
args.reduceRight((acc, fn) => fn(acc), value);
const func3 = (x, y) => {
return y > 0 ? x + 3 : x - 3;
};
const func2 = x => {
return x ** 2;
};
const func1 = x => {
return x - 8;
};
const fnOne = compose(
func1,
func2,
func3
)('3', 1);
console.log(fnOne);//-8
const fnTwo = compose(
func1,
func2,
func3
)('3', -1);
console.log(fnTwo);//-8
Upvotes: 2
Views: 182
Reputation: 35253
Similar to compose
, you could use rest parameter syntax get an an array of values
. Then destructure the func3
arguments to get x
and y
like this:
const compose = (...args) => (...values) =>
args.reduceRight((acc, fn) => fn(acc), values);
// an array of values is passed here
// destructure to get the x and y values
const func3 = ([x, y]) => y > 0 ? x + 3 : x - 3;
const func2 = x => x ** 2;
const func1 = x => x - 8;
const fnOne = compose(
func1,
func2,
func3
)('3', 1);
console.log(fnOne);//1081
const fnTwo = compose(
func1,
func2,
func3
)('3', -1);
console.log(fnTwo);//-8
Upvotes: 1