qappleh / Interview

我是追梦赤子心,公众号「深圳湾码农」的作者,某上市集团公司高级前端开发,深耕前端领域多年,每天攻破一道题,带你从0到1系统构建web全栈完整的知识体系!
https://github.com/qappleh/Interview
1.14k stars 95 forks source link

Day387:如何实现一个 flatMap 函数 (字节) #390

Open qappleh opened 3 years ago

qappleh commented 3 years ago

提示:Array.prototype.flatMap 已经是 EcmaScript 的标准。

JoeWrights commented 3 years ago
Array.prototype.myFlatMap = function (callback) {
  let array = this
  const result = []

  const getArrayDepth = (arr) => {
    if (!Array.isArray(arr)) throw new Error('参数必须是数组')
    const map = {
      '[': 1,
      ']': -1
    }
    let max = 0
    let sum = 0
    const str = JSON.stringify(arr).split('')

    str.forEach(item => {
     if (map[item]) {
        sum += map[item]
        if (sum > max) {
          max = sum
        }
     }
    })

    return max
  }

  for (let index = 0; index < array.length; index++) {
    const element = array[index]
    let target = callback(element)
    if (Array.isArray(target)) {
      if (getArrayDepth(target) > 1) {
        target = target.flat()
        result.push(target)
      } else {
        result.push(...target)
      }
    } else {
      result.push(target)
    }
  }

  return result
}
JoeWrights commented 3 years ago

测试:

[1,2,3,4].myFlatMap(x => [[x * 2]])  // [[2],[4],[6],[8]]

[1,2,3,4].myFlatMap(x => [[x * 2, x * 3]]) // [[2,3],[4,6],[6,9],[8,12]]

[1,2,3,4].myFlatMap(x => [[[x * 2, x * 3]]]) // [[[2,3]],[[4,6]],[[6,9]],[[8,12]]]