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