将数组拆分成多个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

 

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值