JAVASCRIPT   6

chunk.js

Guest on 11th June 2021 03:41:43 AM

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

Raw Paste


Login or Register to edit or fork this paste. It's free.