将数组拆分成多个size长度的区块

/**
 * 将数组拆分成多个size长度的区块,并将这些区块组成一个新的数组。如果数组儒法被分隔成全部等长的区块,那么最后剩余的元素将组成一个区块
 * Create an array of elements split into grounps the length of 'size'.
 * if 'array' cant be split evenly, the final chunk will be the remaining elements.
 *
 * @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']]
 *
 * chunk(['a', 'b', 'c', 'd'], -1)
 * // => []
 *
 * chunk('66666', 2)
 * // => [['6', '6'], ['6', '6'], ['6']]
 */

import toInteger from "../Lang/toInteger" //请搜索之前的文章 ‘转换为整数’

function slice(array, start, end) {
  let length = array == null ? 0 : array.length
  if (!length) {
    return []
  }
  start = start == null ? 0 : toInteger(start)
  end = end === undefined ? length : toInteger(end)

  if (start < 0) {
    start = -start > length ? 0 : length + start
  }
  end = end > length ? length : end
  if (end < 0) {
    end += length
  }
  length = start > end ? 0 : (end - start) >>> 0 // 向上取整
  start >>>= 0 // 向下取整

  let index = -1
  const result = new Array(length)
  while (++index < length) {
    result[index] = array[index + start]
  }
  return result
}

function chunk(array, size = 1) {
  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

 

你可能感兴趣的:(lodash)