Skip to content

Instantly share code, notes, and snippets.

@trafficinc
Last active December 21, 2020 16:03
Show Gist options
  • Save trafficinc/1229e9ef2916f4e9616dd463673d663f to your computer and use it in GitHub Desktop.
Save trafficinc/1229e9ef2916f4e9616dd463673d663f to your computer and use it in GitHub Desktop.
JS Tree data structure
var Node = function (name) {
this.children = [];
this.name = name;
}
Node.prototype = {
add: function (child) {
this.children.push(child);
},
remove: function (child) {
var length = this.children.length;
for (var i = 0; i < length; i++) {
if (this.children[i] === child) {
this.children.splice(i, 1);
return;
}
}
},
getChild: function (i) {
return this.children[i];
},
hasChildren: function () {
return this.children.length > 0;
}
}
// recursively traverse a (sub)tree
function traverse(indent, node) {
log.add(Array(indent++).join("--") + node.name);
for (var i = 0, len = node.children.length; i < len; i++) {
traverse(indent, node.getChild(i));
}
}
var log = (function () {
var log = "";
return {
add: function (msg) { log += msg + "\n"; },
show: function () { console.log(log); log = ""; }
}
})();
// execute... run
function run() {
var executive = new Node("CEO");
var vpOne = new Node("VP of Happiness");
var vpTwo = new Node("VP of Finance");
var dirPromo = new Node("Director of Promo");
var dirGive = new Node("Director of Giveaways");
var dirRec = new Node("Director of Recievables");
var dirSales = new Node("Director of Sales");
var mSalesOne = new Node("Manager of Sales 1");
var mSalesTwo = new Node("Manager of Sales 2");
executive.add(vpOne);
executive.add(vpTwo);
vpOne.add(dirPromo);
vpOne.add(dirGive);
vpTwo.add(dirRec);
vpTwo.add(dirSales);
dirRec.add(mSalesOne);
dirSales.add(mSalesTwo);
dirSales.remove(mSalesTwo); // remove ex.
dirSales.add(mSalesTwo);
traverse(1, executive);
log.show();
}
run();
/* OUTPUTS:
CEO
--VP of Happiness
----Director of Promo
----Director of Giveaways
--VP of Finance
----Director of Recievables
------Manager of Sales 1
----Director of Sales
------Manager of Sales 2
*/
@EgoPingvina
Copy link

line 51: there is declaration of currentTree ?

@trafficinc
Copy link
Author

Updated, check now

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment