times.js 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. var baseTimes = require('./_baseTimes'),
  2. castFunction = require('./_castFunction'),
  3. toInteger = require('./toInteger');
  4. /** Used as references for various `Number` constants. */
  5. var MAX_SAFE_INTEGER = 9007199254740991;
  6. /** Used as references for the maximum length and index of an array. */
  7. var MAX_ARRAY_LENGTH = 4294967295;
  8. /* Built-in method references for those with the same name as other `lodash` methods. */
  9. var nativeMin = Math.min;
  10. /**
  11. * Invokes the iteratee `n` times, returning an array of the results of
  12. * each invocation. The iteratee is invoked with one argument; (index).
  13. *
  14. * @static
  15. * @since 0.1.0
  16. * @memberOf _
  17. * @category Util
  18. * @param {number} n The number of times to invoke `iteratee`.
  19. * @param {Function} [iteratee=_.identity] The function invoked per iteration.
  20. * @returns {Array} Returns the array of results.
  21. * @example
  22. *
  23. * _.times(3, String);
  24. * // => ['0', '1', '2']
  25. *
  26. * _.times(4, _.constant(0));
  27. * // => [0, 0, 0, 0]
  28. */
  29. function times(n, iteratee) {
  30. n = toInteger(n);
  31. if (n < 1 || n > MAX_SAFE_INTEGER) {
  32. return [];
  33. }
  34. var index = MAX_ARRAY_LENGTH,
  35. length = nativeMin(n, MAX_ARRAY_LENGTH);
  36. iteratee = castFunction(iteratee);
  37. n -= MAX_ARRAY_LENGTH;
  38. var result = baseTimes(length, iteratee);
  39. while (++index < n) {
  40. iteratee(index);
  41. }
  42. return result;
  43. }
  44. module.exports = times;