Skip to content

Instantly share code, notes, and snippets.

@jamiebuilds jamiebuilds/tree.js
Created Jan 3, 2020

Embed
What would you like to do?
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)
}
@bathos

This comment has been minimized.

Copy link

bathos commented Jan 4, 2020

I wanted to ask (but figured it would be drifting too far off-topic) what the ‘manual queue’ approach above might provide over:

  * traverse() {
    for (const child of this.children) {
      yield child;
      yield * child.children;
    }
  }

Is it about ‘locking in’ each child list at the point its parent is first hit to prevent mutations to that child list from influencing what gets yielded?

@bathos

This comment has been minimized.

Copy link

bathos commented Jan 4, 2020

(Tried IRC and twitter w/ no luck but then remembered gists have comments of their own :)

@jamiebuilds

This comment has been minimized.

Copy link
Owner Author

jamiebuilds commented Jan 7, 2020

@bathos yield* isn't going to recurse the entire tree, only the first level. But you could also make it so each node in the tree had its own Symbol.iterator so that it used them to recurse the tree:

class TreeNode {
  constructor(value) {
    this.value = value
    this.children = []
  }
  
  add(value, parentValue) {
    for (let node of this) {
      if (node.value === parentValue) {
        node.children.push(new TreeNode(value))
        break
      }
    }
  }
  
  *[Symbol.iterator]() {
    yield this
    for (let node of this.children) {
      yield* node
    }
  }
}

let tree = new TreeNode("root")

tree.add("a", "root")
tree.add("a.a", "a")
tree.add("a.b", "a")
tree.add("b", "root")
tree.add("b.a", "b")
tree.add("b.b", "b")

for (let node of tree) {
  console.log(node.value)
}
@bathos

This comment has been minimized.

Copy link

bathos commented Jan 7, 2020

Thanks! — right, didn’t click that I hadn’t wrapped it in anything and it was just an ordinary array there.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.