chunk.js 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. var baseSlice = require('../internal/baseSlice'),
  2. isIterateeCall = require('../internal/isIterateeCall');
  3. /* Native method references for those with the same name as other `lodash` methods. */
  4. var nativeCeil = Math.ceil,
  5. nativeFloor = Math.floor,
  6. nativeMax = Math.max;
  7. /**
  8. * Creates an array of elements split into groups the length of `size`.
  9. * If `collection` can't be split evenly, the final chunk will be the remaining
  10. * elements.
  11. *
  12. * @static
  13. * @memberOf _
  14. * @category Array
  15. * @param {Array} array The array to process.
  16. * @param {number} [size=1] The length of each chunk.
  17. * @param- {Object} [guard] Enables use as a callback for functions like `_.map`.
  18. * @returns {Array} Returns the new array containing chunks.
  19. * @example
  20. *
  21. * _.chunk(['a', 'b', 'c', 'd'], 2);
  22. * // => [['a', 'b'], ['c', 'd']]
  23. *
  24. * _.chunk(['a', 'b', 'c', 'd'], 3);
  25. * // => [['a', 'b', 'c'], ['d']]
  26. */
  27. function chunk(array, size, guard) {
  28. if (guard ? isIterateeCall(array, size, guard) : size == null) {
  29. size = 1;
  30. } else {
  31. size = nativeMax(nativeFloor(size) || 1, 1);
  32. }
  33. var index = 0,
  34. length = array ? array.length : 0,
  35. resIndex = -1,
  36. result = Array(nativeCeil(length / size));
  37. while (index < length) {
  38. result[++resIndex] = baseSlice(array, index, (index += size));
  39. }
  40. return result;
  41. }
  42. module.exports = chunk;