Last active
December 21, 2020 16:03
-
-
Save trafficinc/1229e9ef2916f4e9616dd463673d663f to your computer and use it in GitHub Desktop.
JS Tree data structure
This file contains hidden or 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
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 | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
line 51: there is declaration of
currentTree
?