美文网首页
reduceRight((acc, curVal, index,

reduceRight((acc, curVal, index,

作者: Time_Notes | 来源:发表于2023-09-02 05:02 被阅读0次

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

相关文章

网友评论

      本文标题:reduceRight((acc, curVal, index,

      本文链接:https://www.haomeiwen.com/subject/bflxvdtx.html