reduceWhile.js 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. import _curryN from "./internal/_curryN.js";
  2. import _xReduce from "./internal/_xReduce.js";
  3. import _xwrap from "./internal/_xwrap.js";
  4. import _reduced from "./internal/_reduced.js";
  5. /**
  6. * Like [`reduce`](#reduce), `reduceWhile` returns a single item by iterating
  7. * through the list, successively calling the iterator function. `reduceWhile`
  8. * also takes a predicate that is evaluated before each step. If the predicate
  9. * returns `false`, it "short-circuits" the iteration and returns the current
  10. * value of the accumulator. `reduceWhile` may alternatively be short-circuited
  11. * via [`reduced`](#reduced).
  12. *
  13. * @func
  14. * @memberOf R
  15. * @since v0.22.0
  16. * @category List
  17. * @sig ((a, b) -> Boolean) -> ((a, b) -> a) -> a -> [b] -> a
  18. * @param {Function} pred The predicate. It is passed the accumulator and the
  19. * current element.
  20. * @param {Function} fn The iterator function. Receives two values, the
  21. * accumulator and the current element.
  22. * @param {*} a The accumulator value.
  23. * @param {Array} list The list to iterate over.
  24. * @return {*} The final, accumulated value.
  25. * @see R.reduce, R.reduced
  26. * @example
  27. *
  28. * const isOdd = (acc, x) => x % 2 !== 0;
  29. * const xs = [1, 3, 5, 60, 777, 800];
  30. * R.reduceWhile(isOdd, R.add, 0, xs); //=> 9
  31. *
  32. * const ys = [2, 4, 6]
  33. * R.reduceWhile(isOdd, R.add, 111, ys); //=> 111
  34. */
  35. var reduceWhile =
  36. /*#__PURE__*/
  37. _curryN(4, [], function _reduceWhile(pred, fn, a, list) {
  38. var xf = _xwrap(function (acc, x) {
  39. return pred(acc, x) ? fn(acc, x) : _reduced(acc);
  40. });
  41. return _xReduce(xf, a, list);
  42. });
  43. export default reduceWhile;