Compose函数自定义实现疑问:为何compose1报TypeError错误?
Let's break down exactly why your compose1 fails while compose works perfectly—this all comes down to how reduce is being used in each version.
First, recap your code
Your working compose function:
const compose = (...fns) => fns.reduce((f,g) => (...args) => f(g(...args)));
Your broken compose1 function:
const compose1 = (...fns) => (...args) => fns.reduce((f,g) => f(g(...args)));
And your curried helper functions:
const multi = a => x => x*a; const devide = a => x => x/a; const add = a => x => x+a;
The core difference: What does reduce return at each step?
How compose works (the correct version)
In compose, the reduce runs immediately when you define the composite function—not when you call it later.
Each iteration of reduce returns a new function that chains the previous composite function with the next one. Let's walk through your example compose(add(6), multi(4), devide(5)):
- First iteration:
fisadd(6),gismulti(4). We return(...args) => add(6)(multi(4)(...args))—a function, not a value. - Second iteration:
fis that new function,gisdevide(5). We return(...args) => [previous function](devide(5)(...args))—another function.
By the end of reduce, you have a single function that, when called with (5), will run add(6)(multi(4)(devide(5)(5)))—exactly the function pipeline you want.
How compose1 breaks (the incorrect version)
In compose1, the reduce doesn't run until you call the final composite function (with (5)). Worse, each iteration of reduce returns the result of executing the functions, not a new function.
Let's walk through compose1(add(6), multi(4), devide(5))(5):
- First iteration:
fisadd(6),gismulti(4). We calculatef(g(5))→add(6)(multi(4)(5))→add(6)(20)→26. This is a number, not a function. - Second iteration: Now
fis26(the result from the first step),gisdevide(5). We try to runf(g(5))→26(devide(5)(5))→26(1).
You can't call a number like it's a function—hence the Uncaught TypeError: f is not a function error.
Key takeaway
composeusesreduceto build a reusable function pipeline—every step returns a function that can be chained further.compose1usesreduceto compute a value immediately on call, but since the first step returns a non-function value, the next iteration crashes.
内容的提问来源于stack exchange,提问作者Luke

