Skip to content

Instantly share code, notes, and snippets.

@pinkmomo027
Created June 11, 2018 21:05
Show Gist options
  • Save pinkmomo027/d4b53fc85ad2e888c3214a1dfa069a2f to your computer and use it in GitHub Desktop.
Save pinkmomo027/d4b53fc85ad2e888c3214a1dfa069a2f to your computer and use it in GitHub Desktop.
hash to tree illustration
// A - B, C
// B - X,
// C - T, W
class Node {
constructor(value) {
this.value = value;
this.children = [];
}
add(child) {
this.children.push(child);
}
print(level=0) {
let indent = "";
for (let i = 0; i < level * 2; i++) {
indent += " ";
}
process.stdout.write(`${indent}value : ${this.value} \n`);
if(this.children.length == 0) {
process.stdout.write(`${indent}children: --- none\n`);
} else {
process.stdout.write(`${indent}children: --- below\n`);
this.children.forEach(child => {
child.print(level+1);
});
}
}
}
let hash = {
'C' : 'A',
'A' : null,
'B' : 'A',
'T' : 'C',
'X' : 'B',
'W' : 'C',
}
let result = {}
let root = null;
function generateChar(hash) {
for (let k in hash) {
let parentValue = hash[k];
result[k] = result[k] || new Node(k);
result[parentValue] = result[parentValue] || new Node(parentValue);
let currentNode = result[k];
let parentNode = result[parentValue];
if (parentValue == null) {
root = currentNode;
} else {
parentNode.add(currentNode);
}
}
}
generateChar(hash);
root.print();
// value : A
// children: --- below
// value : C
// children: --- below
// value : T
// children: --- none
// value : W
// children: --- none
// value : B
// children: --- below
// value : X
// children: --- none
// [Finished in 0.1s]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment