Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
// 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