Skip to content

Instantly share code, notes, and snippets.

@sam-artuso
Created June 30, 2020 21:10
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sam-artuso/7717b793320e56a609066039ddde188d to your computer and use it in GitHub Desktop.
Save sam-artuso/7717b793320e56a609066039ddde188d to your computer and use it in GitHub Desktop.
// 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