百忙之中(闲来无事)想抽点时间好好读一下源码,因而就选了Lodash来写一个系列罢。读源码顺序就按照loadsh文档顺序来。javascript
_.chunk(array, [size=1])
将数组array
拆分红多个 size
长度的区块,并将这些区块组成一个新数组。 若是array
没法被分割成所有等长的区块,那么最后剩余的元素将组成一个区块。java
例:git
chunk(['a', 'b', 'c', 'd'], 2) // => [['a', 'b'], ['c', 'd']] chunk(['a', 'b', 'c', 'd'], 3) // => [['a', 'b', 'c'], ['d']]
很实用的一个函数,下面来看下具体实现:github
能够看到,chunk
依赖了slice.js
,具体实现解析已经讲过了:传送门segmentfault
import slice from './slice.js'
首先是参数的验证数组
size = Math.max(size, 0) const length = array == null ? 0 : array.length if (!length || size < 1) { return [] }
根据length/size
向上取整来肯定新的数组长度,循环调用切片函数slice
,最后返回结果函数
let index = 0 let resIndex = 0 const result = new Array(Math.ceil(length / size)) while (index < length) { result[resIndex++] = slice(array, index, (index += size)) } return result
最后贴个源码:spa
import slice from './slice.js' /** * Creates an array of elements split into groups the length of `size`. * If `array` can't be split evenly, the final chunk will be the remaining * elements. * * @since 3.0.0 * @category Array * @param {Array} array The array to process. * @param {number} [size=1] The length of each chunk * @returns {Array} Returns the new array of chunks. * @example * * chunk(['a', 'b', 'c', 'd'], 2) * // => [['a', 'b'], ['c', 'd']] * * chunk(['a', 'b', 'c', 'd'], 3) * // => [['a', 'b', 'c'], ['d']] */ function chunk(array, size) { size = Math.max(size, 0) const length = array == null ? 0 : array.length if (!length || size < 1) { return [] } let index = 0 let resIndex = 0 const result = new Array(Math.ceil(length / size)) while (index < length) { result[resIndex++] = slice(array, index, (index += size)) } return result } export default chunk