lodash(chunk)源码复写

202 阅读1分钟
function _chunk(array, size) {
  var index = 0,
    resIndex = 0,
    arrayLength = array.length,
    length = Math.ceil(arrayLength / size),
    result = Array(length)
  while (index < arrayLength) {
    result[resIndex++] = baseSlice(array, index, (index += size))
  }
  return result
}
function baseSlice(array, start, end) {
  var length = array.length,
    end = end > length ? length : end,
    length = end - start >>> 0,
    result = Array(length),
    index = -1;
  start >>>= 0
  while (++index < length) {
    result[index] = array[start + index]
  }
  return result
}
console.log(_chunk([1, 2, 5], 2));  //[[1,2],[5]]

>>>本质上就是保证变量有意义(为数字类型),且为正整数,在有效的数组范围内

0.1 >>> 0 返回 0

1.2 >>> 0 返回 1

-1 >>> 0 返回 4294967295

思想:算出结果数组的长度 通过baseSlice函数将数组分解成以size为数组长度的数组返回 然后通过 _chunk函数循环赋值给新数组并返回