UNPKG

1.65 kBJavaScriptView Raw
1var _curry3 =
2/*#__PURE__*/
3require("./internal/_curry3");
4/**
5 * The `mapAccumRight` function behaves like a combination of map and reduce; it
6 * applies a function to each element of a list, passing an accumulating
7 * parameter from right to left, and returning a final value of this
8 * accumulator together with the new list.
9 *
10 * Similar to [`mapAccum`](#mapAccum), except moves through the input list from
11 * the right to the left.
12 *
13 * The iterator function receives two arguments, *acc* and *value*, and should
14 * return a tuple *[acc, value]*.
15 *
16 * @func
17 * @memberOf R
18 * @since v0.10.0
19 * @category List
20 * @sig ((acc, x) -> (acc, y)) -> acc -> [x] -> (acc, [y])
21 * @param {Function} fn The function to be called on every element of the input `list`.
22 * @param {*} acc The accumulator value.
23 * @param {Array} list The list to iterate over.
24 * @return {*} The final, accumulated value.
25 * @see R.addIndex, R.mapAccum
26 * @example
27 *
28 * const digits = ['1', '2', '3', '4'];
29 * const appender = (a, b) => [b + a, b + a];
30 *
31 * R.mapAccumRight(appender, 5, digits); //=> ['12345', ['12345', '2345', '345', '45']]
32 * @symb R.mapAccumRight(f, a, [b, c, d]) = [
33 * f(f(f(a, d)[0], c)[0], b)[0],
34 * [
35 * f(a, d)[1],
36 * f(f(a, d)[0], c)[1],
37 * f(f(f(a, d)[0], c)[0], b)[1]
38 * ]
39 * ]
40 */
41
42
43var mapAccumRight =
44/*#__PURE__*/
45_curry3(function mapAccumRight(fn, acc, list) {
46 var idx = list.length - 1;
47 var result = [];
48 var tuple = [acc];
49
50 while (idx >= 0) {
51 tuple = fn(tuple[0], list[idx]);
52 result[idx] = tuple[1];
53 idx -= 1;
54 }
55
56 return [tuple[0], result];
57});
58
59module.exports = mapAccumRight;
\No newline at end of file