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.

41 lines
1.4 KiB

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