range.js 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. var isIterateeCall = require('../internal/isIterateeCall');
  2. /* Native method references for those with the same name as other `lodash` methods. */
  3. var nativeCeil = Math.ceil,
  4. nativeMax = Math.max;
  5. /**
  6. * Creates an array of numbers (positive and/or negative) progressing from
  7. * `start` up to, but not including, `end`. If `end` is not specified it's
  8. * set to `start` with `start` then set to `0`. If `end` is less than `start`
  9. * a zero-length range is created unless a negative `step` is specified.
  10. *
  11. * @static
  12. * @memberOf _
  13. * @category Utility
  14. * @param {number} [start=0] The start of the range.
  15. * @param {number} end The end of the range.
  16. * @param {number} [step=1] The value to increment or decrement by.
  17. * @returns {Array} Returns the new array of numbers.
  18. * @example
  19. *
  20. * _.range(4);
  21. * // => [0, 1, 2, 3]
  22. *
  23. * _.range(1, 5);
  24. * // => [1, 2, 3, 4]
  25. *
  26. * _.range(0, 20, 5);
  27. * // => [0, 5, 10, 15]
  28. *
  29. * _.range(0, -4, -1);
  30. * // => [0, -1, -2, -3]
  31. *
  32. * _.range(1, 4, 0);
  33. * // => [1, 1, 1]
  34. *
  35. * _.range(0);
  36. * // => []
  37. */
  38. function range(start, end, step) {
  39. if (step && isIterateeCall(start, end, step)) {
  40. end = step = undefined;
  41. }
  42. start = +start || 0;
  43. step = step == null ? 1 : (+step || 0);
  44. if (end == null) {
  45. end = start;
  46. start = 0;
  47. } else {
  48. end = +end || 0;
  49. }
  50. // Use `Array(length)` so engines like Chakra and V8 avoid slower modes.
  51. // See https://youtu.be/XAqIpGU8ZZk#t=17m25s for more details.
  52. var index = -1,
  53. length = nativeMax(nativeCeil((end - start) / (step || 1)), 0),
  54. result = Array(length);
  55. while (++index < length) {
  56. result[index] = start;
  57. start += step;
  58. }
  59. return result;
  60. }
  61. module.exports = range;