scan.js 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. import _curry3 from "./internal/_curry3.js";
  2. import _dispatchable from "./internal/_dispatchable.js";
  3. import _xscan from "./internal/_xscan.js";
  4. /**
  5. * Scan is similar to [`reduce`](#reduce), but returns a list of successively
  6. * reduced values from the left.
  7. *
  8. * Acts as a transducer if a transformer is given in list position.
  9. *
  10. * @func
  11. * @memberOf R
  12. * @since v0.10.0
  13. * @category List
  14. * @sig ((a, b) -> a) -> a -> [b] -> [a]
  15. * @param {Function} fn The iterator function. Receives two values, the accumulator and the
  16. * current element from the array
  17. * @param {*} acc The accumulator value.
  18. * @param {Array} list The list to iterate over.
  19. * @return {Array} A list of all intermediately reduced values.
  20. * @see R.reduce, R.mapAccum
  21. * @example
  22. *
  23. * const numbers = [1, 2, 3, 4];
  24. * const factorials = R.scan(R.multiply, 1, numbers); //=> [1, 1, 2, 6, 24]
  25. * @symb R.scan(f, a, [b, c]) = [a, f(a, b), f(f(a, b), c)]
  26. */
  27. var scan =
  28. /*#__PURE__*/
  29. _curry3(
  30. /*#__PURE__*/
  31. _dispatchable([], _xscan, function scan(fn, acc, list) {
  32. var idx = 0;
  33. var len = list.length;
  34. var result = [acc];
  35. while (idx < len) {
  36. acc = fn(acc, list[idx]);
  37. result[idx + 1] = acc;
  38. idx += 1;
  39. }
  40. return result;
  41. }));
  42. export default scan;