Created
January 3, 2020 23:45
-
-
Save jamiebuilds/7322021dd6584ef7d2cbd08cd637d683 to your computer and use it in GitHub Desktop.
This file contains 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
class Tree { | |
constructor() { | |
this.children = [] | |
} | |
add(value, parentValue) { | |
let newNode = { value, children: [] } | |
if (parentValue === null) { | |
this.children.push(newNode) | |
return | |
} | |
for (let node of this.traverse()) { | |
if (node.value === parentValue) { | |
node.children.push(newNode) | |
break | |
} | |
} | |
} | |
*traverse() { | |
let queue = [...this.children] | |
while (queue.length) { | |
let node = queue.shift() | |
yield node | |
queue = [...node.children, ...queue] | |
} | |
} | |
} | |
let tree = new Tree() | |
tree.add("a", null) | |
tree.add("a.a", "a") | |
tree.add("a.b", "a") | |
tree.add("b", null) | |
tree.add("b.a", "b") | |
tree.add("b.b", "b") | |
for (let node of tree.traverse()) { | |
console.log(node.value) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thanks! — right, didn’t click that I hadn’t wrapped it in anything and it was just an ordinary array there.