reduceRight Folds From The Last Element
reduceRight folds from the last element toward the first, which is exactly the shape of right-associative evaluation and right-to-left function composition.
Code
// reduceRight 从最后一个元素开始向左折叠:右结合运算天然匹配
// 2 ^ 3 ^ 2 数学上右结合,等于 2 ^ (3 ^ 2)
const operands = [2, 3, 2];
console.log('2^3^2 =', operands.reduceRight((acc, base) => base ** acc, 1));
// 经典用途:从右到左组合函数 compose(f, g)(x) 等于 f(g(x))
const compose = (...fns) => (value) =>
fns.reduceRight((acc, fn) => fn(acc), value);
const parse = (s) => Number.parseInt(s, 10);
const double = (n) => n * 2;
const label = (n) => 'v' + n;
// compose(label, double, parse)('21'):从右往左依次执行 parse、double、label
console.log('compose:', compose(label, double, parse)('21'));
// 与 reduce 的方向对照:累加顺序正好相反
const left = [1, 2, 3].reduce((acc, n) => acc + '-' + n, 'L');
const right = [1, 2, 3].reduceRight((acc, n) => acc + '-' + n, 'R');
console.log('reduce :', left);
console.log('reduceR:', right);Output
Captured from a sandboxed run of this snippet in the build pipeline.
2^3^2 = 512
compose: v42
reduce : L-1-2-3
reduceR: R-3-2-1Inside the snippet
reduceRight Folds From The Last Element keeps everything in the functions compose, parse, double and label.
Putting it to use
Entry signature: const compose = (...fns)
The demo output is labeled (2^3^2 =, compose:, reduce :), so every printed line maps back to its originating operation.
Core lines
const left = [1, 2, 3].reduce((acc, n) => acc + '-' + n, 'L');
const right = [1, 2, 3].reduceRight((acc, n) => acc + '-' + n, 'R');
fns.reduceRight((acc, fn) => fn(acc), value);
Interactive Tools for This Topic
FAQ
- Are there third-party dependencies?
- No. The dependency list is empty; the code stays inside the standard library. The file defines `compose`, `parse`, `double` at load time.
Report a problem with this exampleOpens a pre-filled issue on GitHub.