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.3 KiB

4 years ago
  1. import _curry2 from "./internal/_curry2.js";
  2. /**
  3. * Builds a list from a seed value. Accepts an iterator function, which returns
  4. * either false to stop iteration or an array of length 2 containing the value
  5. * to add to the resulting list and the seed to be used in the next call to the
  6. * iterator function.
  7. *
  8. * The iterator function receives one argument: *(seed)*.
  9. *
  10. * @func
  11. * @memberOf R
  12. * @since v0.10.0
  13. * @category List
  14. * @sig (a -> [b]) -> * -> [b]
  15. * @param {Function} fn The iterator function. receives one argument, `seed`, and returns
  16. * either false to quit iteration or an array of length two to proceed. The element
  17. * at index 0 of this array will be added to the resulting array, and the element
  18. * at index 1 will be passed to the next call to `fn`.
  19. * @param {*} seed The seed value.
  20. * @return {Array} The final list.
  21. * @example
  22. *
  23. * const f = n => n > 50 ? false : [-n, n + 10];
  24. * R.unfold(f, 10); //=> [-10, -20, -30, -40, -50]
  25. * @symb R.unfold(f, x) = [f(x)[0], f(f(x)[1])[0], f(f(f(x)[1])[1])[0], ...]
  26. */
  27. var unfold =
  28. /*#__PURE__*/
  29. _curry2(function unfold(fn, seed) {
  30. var pair = fn(seed);
  31. var result = [];
  32. while (pair && pair.length) {
  33. result[result.length] = pair[0];
  34. pair = fn(pair[1]);
  35. }
  36. return result;
  37. });
  38. export default unfold;