4de9b3961843b0ad8c6cefe33ae1fb5c594c7f53
[platform/framework/web/crosswalk-tizen.git] /
1 var baseSlice = require('../internal/baseSlice'),
2     isIterateeCall = require('../internal/isIterateeCall');
3
4 /** Native method references. */
5 var ceil = Math.ceil;
6
7 /* Native method references for those with the same name as other `lodash` methods. */
8 var nativeMax = Math.max;
9
10 /**
11  * Creates an array of elements split into groups the length of `size`.
12  * If `collection` can't be split evenly, the final chunk will be the remaining
13  * elements.
14  *
15  * @static
16  * @memberOf _
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 a callback for functions like `_.map`.
21  * @returns {Array} Returns the new array containing 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 == null) {
32     size = 1;
33   } else {
34     size = nativeMax(+size || 1, 1);
35   }
36   var index = 0,
37       length = array ? array.length : 0,
38       resIndex = -1,
39       result = Array(ceil(length / size));
40
41   while (index < length) {
42     result[++resIndex] = baseSlice(array, index, (index += size));
43   }
44   return result;
45 }
46
47 module.exports = chunk;