亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定

每天一個lodash方法(5)

標簽:
JavaScript

Array method 系列之五 —— 数组扁平化:flatten && flattenDeep && flattenDepth
flattenflattenDeepflattenDepth提供了将数组扁平化的思路。三者唯一的不同在于扁平数组的层次不同。flatten对数组进行一次扁平操作,flattenDeep扁平数组所有元素为一维为止。flattenDepth可以制定扁平数组的深度。

进行扁平化的核心代码是baseFlatten,其实现思路是递归。
源码如下:

// 判断数组元素是否可扁平化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) {        // 递归执行扁平函数,直至达到所要的结果
        baseFlatten(value, depth - 1, predicate, isStrict, result)
      } else {
        result.push(...value)
      }
    } else if (!isStrict) {
      result[result.length] = value
    }
  }  return result
}

比较flattenflattenDeepflattenDepth在执行baseFlatten的传参,即可看到差异。

// flattenfunction flatten(array) {  const length = array == null ? 0 : array.length  // depth = 1,执行一次扁平操作
  return length ? baseFlatten(array, 1) : []
}// flattenDeepconst INFINITY = 1 / 0function flattenDeep(array) {  const length = array == null ? 0 : array.length  // 无限次执行扁平操作,直至所有元素都为一维。
  return length ? baseFlatten(array, INFINITY) : []
}// flattenDepthfunction flattenDepth(array, depth) {  const length = array == null ? 0 : array.length  if (!length) {    return []
  } // 执行扁平数组操作次数为depth
  depth = depth === undefined ? 1 : +depth  return baseFlatten(array, depth)
}

这里有个想法,在flattenDeep中传参判断,反倒没有源码写的简洁。
自己想了下,实现如下。

for (const value of array) {    if (depth > 0 && predicate(value)) {      if (deepEnd) { // 即flattenDeep执行这一步
        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
    }
  }

实在是没有源码简洁。
所以源码实现可以说是非常高明了。



作者:公子七
链接:https://www.jianshu.com/p/8eed7dc12f68


點擊查看更多內容
TA 點贊

若覺得本文不錯,就分享一下吧!

評論

作者其他優質文章

正在加載中
  • 推薦
  • 評論
  • 收藏
  • 共同學習,寫下你的評論
感謝您的支持,我會繼續努力的~
掃碼打賞,你說多少就多少
贊賞金額會直接到老師賬戶
支付方式
打開微信掃一掃,即可進行掃碼打賞哦
今天注冊有機會得

100積分直接送

付費專欄免費學

大額優惠券免費領

立即參與 放棄機會
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號

舉報

0/150
提交
取消