times.js 1.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. import _curry2 from "./internal/_curry2.js";
  2. /**
  3. * Calls an input function `n` times, returning an array containing the results
  4. * of those function calls.
  5. *
  6. * `fn` is passed one argument: The current value of `n`, which begins at `0`
  7. * and is gradually incremented to `n - 1`.
  8. *
  9. * @func
  10. * @memberOf R
  11. * @since v0.2.3
  12. * @category List
  13. * @sig (Number -> a) -> Number -> [a]
  14. * @param {Function} fn The function to invoke. Passed one argument, the current value of `n`.
  15. * @param {Number} n A value between `0` and `n - 1`. Increments after each function call.
  16. * @return {Array} An array containing the return values of all calls to `fn`.
  17. * @see R.repeat
  18. * @example
  19. *
  20. * R.times(R.identity, 5); //=> [0, 1, 2, 3, 4]
  21. * @symb R.times(f, 0) = []
  22. * @symb R.times(f, 1) = [f(0)]
  23. * @symb R.times(f, 2) = [f(0), f(1)]
  24. */
  25. var times =
  26. /*#__PURE__*/
  27. _curry2(function times(fn, n) {
  28. var len = Number(n);
  29. var idx = 0;
  30. var list;
  31. if (len < 0 || isNaN(len)) {
  32. throw new RangeError('n must be a non-negative number');
  33. }
  34. list = [];
  35. while (idx < len) {
  36. list.push(fn(idx));
  37. idx += 1;
  38. }
  39. return list;
  40. });
  41. export default times;