You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

55 lines
1.6 KiB

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