chunk.js 1.4 KB

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