Created
January 20, 2017 20:27
-
-
Save anbnyc/68039dbd2deb8aa1caae6261fe6768c7 to your computer and use it in GitHub Desktop.
Tree data structure implementation
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
/*** | |
* Tree Data Structure Implementation | |
*/ | |
/** | |
* Generates a tree | |
* @param {String} data | |
* @return {Object} Tree | |
*/ | |
function Tree(data) { | |
this._root = new Node(data); | |
} | |
/** | |
* Generates a node | |
* @param {String} data | |
* @return {Object} Node | |
*/ | |
function Node(data) { | |
this.data = data; | |
this.parent = null; | |
this.children = []; | |
} | |
/** | |
* Traverses the tree depth-first | |
* @param {Function} callback | |
*/ | |
Tree.prototype.traverseDF = function(callback){ | |
function traverse(currentNode){ | |
for(let i = 0; i < currentNode.children.length; i++){ | |
traverse(currentNode.children[i]); | |
} | |
callback(currentNode); | |
} | |
traverse(this._root); | |
} | |
/** | |
* Adds a new node to the tree | |
* @param {String} newData | |
* @param {String} parentData | |
*/ | |
Tree.prototype.add = function(newData, parentData){ | |
let nodeParent = null; | |
this.traverseDF(node=>{ | |
if(node.data === parentData){ | |
nodeParent = node; | |
} | |
}); | |
let newNode = new Node(newData); | |
nodeParent.children[nodeParent.children.length] = newNode; | |
newNode.parent = nodeParent; | |
} | |
/** | |
* Removes a node from the tree | |
* @param {String} data | |
* @param {String} parentData | |
*/ | |
Tree.prototype.remove = function(data, parentData){ | |
let nodeParent = null; | |
this.traverseDF(node=>{ | |
if(node.data === parentData){ | |
nodeParent = node; | |
} | |
}); | |
let removeNode = nodeParent.children.filter(node=>node.data === data)[0]; | |
nodeParent.children.splice(nodeParent.children.indexOf(removeNode),1); | |
} | |
/** | |
* Runs all tests | |
*/ | |
function tests(){ | |
var tree = new Tree("one"); | |
if(!tree._root){ | |
console.warn("Test failed: _root does not exist"); | |
} | |
tree.add("two","one"); | |
tree.add("three","one"); | |
if(tree._root.children.length !== 2){ | |
console.warn("Test failed: children were not added to root") | |
} | |
tree.add("four","two"); | |
tree.add("five","two"); | |
tree.add("six","four"); | |
let allNodes = []; | |
tree.traverseDF(node=>{ | |
allNodes.push(node); | |
}); | |
if(allNodes.length !== 6){ | |
console.warn("Test failed: all nodes not counted"); | |
} | |
tree.remove("two","one"); | |
if(tree._root.children.length !== 1){ | |
console.warn("Test failed: child node was not removed from root"); | |
} | |
} | |
tests(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment