Skip to content

Instantly share code, notes, and snippets.

@mweststrate
Created July 17, 2018 12:14
Show Gist options
  • Save mweststrate/8b0ae9ac6d4bfffc86d2a639180c64ee to your computer and use it in GitHub Desktop.
Save mweststrate/8b0ae9ac6d4bfffc86d2a639180c64ee to your computer and use it in GitHub Desktop.
circular-deps-1
export class AbstractNode {
constructor(parent) {
this.parent = parent
}
getDepth() {
if (this.parent) return this.parent.getDepth() + 1
return 0
}
print() {
throw 'abstract; not implemented'
}
static from(thing, parent) {
if (thing && typeof thing === 'object') return new Node(parent, thing)
else return new Leaf(parent, thing)
}
}
export class Node extends AbstractNode {
constructor(parent, thing) {
super(parent)
this.children = {}
Object.keys(thing).forEach(key => {
this.children[key] = AbstractNode.from(thing[key], this)
})
}
print() {
return (
'\n' +
Object.keys(this.children)
.map(key => `${''.padStart(this.getDepth() * 2)}${key}: ${this.children[key].print()}`)
.join('\n')
)
}
}
export class Leaf extends AbstractNode {
constructor(parent, value) {
super(parent)
this.value = value
}
print() {
return this.value
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment