Created
July 17, 2018 12:14
-
-
Save mweststrate/8b0ae9ac6d4bfffc86d2a639180c64ee to your computer and use it in GitHub Desktop.
circular-deps-1
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
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