times.js 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. var bindCallback = require('../internal/bindCallback');
  2. /* Native method references for those with the same name as other `lodash` methods. */
  3. var nativeFloor = Math.floor,
  4. nativeIsFinite = global.isFinite,
  5. nativeMin = Math.min;
  6. /** Used as references for the maximum length and index of an array. */
  7. var MAX_ARRAY_LENGTH = 4294967295;
  8. /**
  9. * Invokes the iteratee function `n` times, returning an array of the results
  10. * of each invocation. The `iteratee` is bound to `thisArg` and invoked with
  11. * one argument; (index).
  12. *
  13. * @static
  14. * @memberOf _
  15. * @category Utility
  16. * @param {number} n The number of times to invoke `iteratee`.
  17. * @param {Function} [iteratee=_.identity] The function invoked per iteration.
  18. * @param {*} [thisArg] The `this` binding of `iteratee`.
  19. * @returns {Array} Returns the array of results.
  20. * @example
  21. *
  22. * var diceRolls = _.times(3, _.partial(_.random, 1, 6, false));
  23. * // => [3, 6, 4]
  24. *
  25. * _.times(3, function(n) {
  26. * mage.castSpell(n);
  27. * });
  28. * // => invokes `mage.castSpell(n)` three times with `n` of `0`, `1`, and `2`
  29. *
  30. * _.times(3, function(n) {
  31. * this.cast(n);
  32. * }, mage);
  33. * // => also invokes `mage.castSpell(n)` three times
  34. */
  35. function times(n, iteratee, thisArg) {
  36. n = nativeFloor(n);
  37. // Exit early to avoid a JSC JIT bug in Safari 8
  38. // where `Array(0)` is treated as `Array(1)`.
  39. if (n < 1 || !nativeIsFinite(n)) {
  40. return [];
  41. }
  42. var index = -1,
  43. result = Array(nativeMin(n, MAX_ARRAY_LENGTH));
  44. iteratee = bindCallback(iteratee, thisArg, 1);
  45. while (++index < n) {
  46. if (index < MAX_ARRAY_LENGTH) {
  47. result[index] = iteratee(index);
  48. } else {
  49. iteratee(index);
  50. }
  51. }
  52. return result;
  53. }
  54. module.exports = times;