Created
June 30, 2020 21:10
-
-
Save sam-artuso/7717b793320e56a609066039ddde188d to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// flatten a tree of arbitrary depth and complexity | |
class WalkableTree { | |
constructor(data) { | |
this.data = data | |
} | |
*[Symbol.iterator]() { | |
for (let value of this.data) { | |
if (Array.isArray(value)) { | |
yield* new WalkableTree(value) | |
} else { | |
yield value | |
} | |
} | |
} | |
} | |
const tree = [1, [2, [3, 4, 5], 6], 7, [8, 9]] | |
const walkableTree = new WalkableTree(tree) | |
for (let leaf of walkableTree) { | |
console.log(leaf) | |
} | |
// outputs: | |
// 1 | |
// 2 | |
// 3 | |
// 4 | |
// 5 | |
// 6 | |
// 7 | |
// 8 | |
// 9 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment