每天一個lodash方法(5)

Array method 系列之五 —— 數(shù)組扁平化:flatten && flattenDeep && flattenDepth
flattenflattenDeep、flattenDepth提供了將數(shù)組扁平化的思路。三者唯一的不同在于扁平數(shù)組的層次不同。flatten對數(shù)組進(jìn)行一次扁平操作,flattenDeep扁平數(shù)組所有元素為一維為止。flattenDepth可以制定扁平數(shù)組的深度。

進(jìn)行扁平化的核心代碼是baseFlatten,其實(shí)現(xiàn)思路是遞歸。
源碼如下:

// 判斷數(shù)組元素是否可扁平化
import isFlattenable from './isFlattenable.js' 

function baseFlatten(array, depth, predicate, isStrict, result) {
  predicate || (predicate = isFlattenable)
  result || (result = [])

  if (array == null) {
    return result
  }

  for (const value of array) {
    if (depth > 0 && predicate(value)) {
      if (depth > 1) {
        // 遞歸執(zhí)行扁平函數(shù),直至達(dá)到所要的結(jié)果
        baseFlatten(value, depth - 1, predicate, isStrict, result)
      } else {
        result.push(...value)
      }
    } else if (!isStrict) {
      result[result.length] = value
    }
  }
  return result
}

比較flatten、flattenDeep、flattenDepth在執(zhí)行baseFlatten的傳參,即可看到差異。

// flatten
function flatten(array) {
  const length = array == null ? 0 : array.length
  // depth = 1,執(zhí)行一次扁平操作
  return length ? baseFlatten(array, 1) : []
}

// flattenDeep
const INFINITY = 1 / 0
function flattenDeep(array) {
  const length = array == null ? 0 : array.length
  // 無限次執(zhí)行扁平操作,直至所有元素都為一維。
  return length ? baseFlatten(array, INFINITY) : []
}

// flattenDepth
function flattenDepth(array, depth) {
  const length = array == null ? 0 : array.length
  if (!length) {
    return []
  }
 // 執(zhí)行扁平數(shù)組操作次數(shù)為depth
  depth = depth === undefined ? 1 : +depth
  return baseFlatten(array, depth)
}

這里有個想法,在flattenDeep中傳參判斷,反倒沒有源碼寫的簡潔。
自己想了下,實(shí)現(xiàn)如下。

for (const value of array) {
    if (depth > 0 && predicate(value)) {
      if (deepEnd) { // 即flattenDeep執(zhí)行這一步
        baseFlatten(value, depth, predicate, isStrict, result, deepEnd)
      } else if (depth > 1) { 
        baseFlatten(value, depth - 1, predicate, isStrict, result, deepEnd)
      } else {
        result.push(...value)
      }
    } else if (!isStrict) {
      result[result.length] = value
    }
  }

實(shí)在是沒有源碼簡潔。
所以源碼實(shí)現(xiàn)可以說是非常高明了。

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • Android 自定義View的各種姿勢1 Activity的顯示之ViewRootImpl詳解 Activity...
    passiontim閱讀 179,323評論 25 708
  • 我嘗試過的酒還有伏特加和金酒。 關(guān)于伏特加是如何發(fā)明的一直有多種說法,傳說在公元15世紀(jì)末當(dāng)俄羅斯終於從蒙古人的統(tǒng)...
    陳之平閱讀 501評論 0 2
  • 今天,向大家介紹幾種花: 細(xì)心的朋友可能留意到:這是假花,為什么我要發(fā)假花呢?其實(shí),我覺得它和裝飾品差不多,可拿來...
    書自由閱讀 238評論 0 0
  • 只要不去想你 就不會痛苦了 可是不去想你 過去的時光都失色 隔壁房的舍友和他女朋友 還是去年的樣子 還是你知道的樣...
    更向遠(yuǎn)行閱讀 154評論 0 2

友情鏈接更多精彩內(nèi)容