I am trying to write a simple compose function that takes a series of functions, and composes them like so:
compose(func1, func2, func3)(n) === func1(func2(func3(n)))
I do so by recursing through a rest parameter,
var compose = function(...args) {
return (n) => {
if (args.length) {
return args[0](compose(args.slice(1)));
} else {
return n;
}
};
};
I then attempt to compose a new function made up of a series of other functions,
var plusOneAndTwo = compose((n) => n + 1, (n) => n + 2);
plusOneAndTwo(1);
Instead of returning 4, I get back the body of the inner, anonymous function inside of compose as a string,
"(n) => {
if (args.length) {
return args[0](compose(args.slice(1)));
} else {
return n;
}
}1"
Note the "1" at the end of the string! I have no idea why this is happening, and in particular I'm perplexed by how a 1 is getting appended to the end of that.
Any clarification is appreciated, thanks!
composereturns a function, yes. You're passing the return value ofcompose, which is a function, toargs[0](). I don't think it's a good idea to usecomposerecursively. I'd simply.reducetheargsinstead.compose(args.slice(1))You don't actually call the function returned by compose here as you do in the initial call, you use the function as the argument to args[0] instead of the result of calling it.args[0](compose(...)). This passes a function to(n) => n + 1, which concatenates1to the function body.