reduceRight((acc, curVal, index, array)

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,

);

How reduceRight() works without an initial value

[0, 1, 2, 3, 4].reduceRight(

  (accumulator, currentValue, index, array) => accumulator + currentValue,

  10,

);

How reduceRight() works with an initial value

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.


Defining composable functions

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

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容