Skip to content

Instantly share code, notes, and snippets.

@Shuumatsu
Created November 14, 2017 06:48
Show Gist options
  • Save Shuumatsu/bf2f1cd446c52609fa39b32d705f5028 to your computer and use it in GitHub Desktop.
Save Shuumatsu/bf2f1cd446c52609fa39b32d705f5028 to your computer and use it in GitHub Desktop.
// 常规的递归方法
const flatten1 = arr => {
const result = []
for (const v of arr) {
Array.isArray(v) ?
result.push(...flatten(v)) :
result.push(v)
}
return result
}
// GeneratorFunction 版的递归,配合 take 还可以达到仅打平到前多少位的效果
const flatten2 = function* (arr) {
for (const v of arr) {
if (Array.isArray(v)) {
yield* flatten(v)
continue
}
yield v
}
}
// 幽灵打平法,假设数字元素均为数字
const flatten3 = arr => arr.toString().split(',')
const flatten4 = arr => JSON.parse(`[${arr}]`)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment