Interview icon indicating copy to clipboard operation
Interview copied to clipboard

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

Open qappleh opened this issue 3 years ago • 2 comments

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

qappleh avatar Aug 31 '21 07:08 qappleh

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 avatar Sep 03 '21 07:09 JoeWrights

测试:

[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]]]

JoeWrights avatar Sep 03 '21 07:09 JoeWrights