← 中文资源

简体中文版本

reduceRight 从最后一个元素向左折叠

reduceRight 从右端开始折叠:右结合运算(如 2^3^2)和从右到左的函数组合用它表达最自然;与 reduce 只是方向相反,方向搞错累加顺序就会反过来。

阅读英文原文

运行结果

以下输出由构建管线在沙箱中真实运行该示例捕获。

2^3^2 = 512
compose: v42
reduce : L-1-2-3
reduceR: R-3-2-1

实现说明

全部逻辑都在函数 compose、parse、double、label中。

使用要点

  • 跑完文件,输出里会留下标记——2^3^2 =、compose:、reduce :。

常见问题

有第三方依赖吗?

没有。依赖清单是空的,代码只用标准库。 文件在加载时定义 compose、parse、double。

主签名形如 const compose = (...fns)

核心语句

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);

代码示例

// 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);