Lodash學習筆記 - chunk函數

百忙之中(閒來無事)想抽點時間好好讀一下源碼,因而就選了Lodash來寫一個系列罷。讀源碼順序就按照loadsh文檔順序來。javascript

文檔地址:中文文檔   英文文檔
源碼地址:gayhubcss


_.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

clipboard.png

相關文章
相關標籤/搜索