The reduceRight() method of Array instances applies a function against an accumulator and each value of the array (from right-to-left) to reduce it to a single value.
See also Array.prototype.reduce() for left-to-right.
Difference between reduce and reduceRight
const a = ["1", "2", "3", "4", "5"];
const left = a.reduce((prev, cur) => prev + cur);
const right = a.reduceRight((prev, cur) => prev + cur);
console.log(left); // "12345"
console.log(right); // "54321"
[0, 1, 2, 3, 4].reduceRight(
(accumulator, currentValue, index, array) => accumulator + currentValue,
);
![](https://img.haomeiwen.com/i16851255/78f6ab22fbf34919.png)
[0, 1, 2, 3, 4].reduceRight(
(accumulator, currentValue, index, array) => accumulator + currentValue,
10,
);
![](https://img.haomeiwen.com/i16851255/75c780ac00821198.png)
accumulator
The value resulting from the previous call to callbackFn. On the first call, its value is initialValue if the latter is specified; otherwise its value is the last element of the array.
currentValue
The value of the current element. On the first call, its value is the last element if initialValue is specified; otherwise its value is the second-to-last element.
currentIndex
The index position of currentValue in the typed array. On the first call, its value is array.length - 1 if initialValue is specified, otherwise array.length - 2.
array
The array reduceRight() was called upon.
initialValue Optional
Value to use as accumulator to the first call of the callbackFn. If no initial value is supplied, the last element in the array will be used and skipped. Calling reduceRight() on an empty array without an initial value creates a TypeError.
const compose =
(...args) =>
(value) =>
args.reduceRight((acc, fn) => fn(acc), value);
// Increment passed number
const inc = (n) => n + 1;
// Doubles the passed value
const double = (n) => n * 2;
// using composition function
console.log(compose(double, inc)(2)); // 6
// using composition function
console.log(compose(inc, double)(2)); // 5
网友评论