Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
qappleh opened this issue Aug 31, 2021 · 2 comments
Open

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

qappleh opened this issue Aug 31, 2021 · 2 comments

Comments

@qappleh
Copy link
Owner

qappleh commented Aug 31, 2021

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

@JoeWrights
Copy link

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
Copy link

测试:

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

2 participants