Skip to content

Instantly share code, notes, and snippets.

@gtindo
Created February 5, 2021 17:12
Show Gist options
  • Save gtindo/f15a2222e510b7ec9d37ca9f1a69836f to your computer and use it in GitHub Desktop.
Save gtindo/f15a2222e510b7ec9d37ca9f1a69836f to your computer and use it in GitHub Desktop.
Category Tree js
class Node{
constructor(value){
this.value = value;
this.children = [];
}
}
class CategoryTree{
constructor() {
this.roots = [];
}
addCategory (value, parent) {
this.addNode(this.roots, value, parent);
}
addNode(roots, value, parent) {
const children = [];
let added = false;
roots.forEach(node => {
if(node.value === parent){
node.children.push(new Node(value));
added = true;
}else{
node.children.forEach(child => children.push(child))
}
if(node.value === value) {
throw Error(`Category ${value} has already been added`);
}
});
if(!added && children.length > 0) {
added = this.addNode(children, value, parent);
}
if(roots == this.roots && parent === null){
this.roots.push(new Node(value));
}else if(roots == this.roots && added === false) {
throw Error(`Parent ${parent} does not exisits`);
}
return added
}
getChildren(value) {
const nodes = this.visitNodes(this.roots, value);
return nodes.map((node) => node.value);
}
visitNodes(roots, value) {
let children = [];
let subNodes = [];
roots.forEach(node => {
if(node.value === value) {
children = node.children;
}else {
node.children.forEach(child => subNodes.push(child))
}
});
if(subNodes.length > 0) {
children = this.visitNodes(subNodes, value);
}
return children;
}
}
function main() {
const tree = new CategoryTree();
tree.addCategory('A', null);
tree.addCategory('B', 'A');
tree.addCategory('C', 'A');
console.log(tree.getChildren('A'));
}
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment