mapAccum.js 1.5 KB

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