Code coverage report for lib/dataStructures/trie.js

Statements: 90.2% (46 / 51)      Branches: 80.77% (21 / 26)      Functions: 100% (9 / 9)      Lines: 100% (45 / 45)      Ignored: none     

All files » lib/dataStructures/ » trie.js
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 921 31     1 115 115     1 81   80   80 503 358     503     80     1 26   26   26 147 6     141     20     1 10   9   1 74 74 74   74     9         65     35     30     1 44       1 2 2   2   1 33 39   31         2     1
var trie = function() {
	this.head = {};
};
 
trie.prototype.validate = function(word) {
	Iif((word === undefined) || (word === null)) throw "The given word is invalid.";
	Iif (typeof word !== "string") throw "The given word is not a string";
}
 
trie.prototype.add = function(word) {
	this.validate(word);
 
	var current = this.head;
 
	for (var i = 0; i < word.length; i++) {
		if(!(word[i] in current)) {
			current[word[i]] = {};
		}
 
		current = current[word[i]]
	};
 
	current.$ = 1;	//word end marker
};
 
trie.prototype.hasWord = function(word) {
	this.validate(word);
 
	var current = this.head;
 
	for (var i = 0; i < word.length; i++) {
		if(!(word[i] in current)) {
			return false;
		}
 
		current = current[word[i]]
	};
 
	return current.$ === 1;	//word end marker
};
 
trie.prototype.remove = function(word) {
	this.validate(word);
 
	canDelete(word, -1, this.head);
 
	function canDelete(word, index, node){
		Iif(word === undefined ) throw "Bad Word";
		Iif(index >= word.length) throw "Bad index to check for deletion.";
		Iif(node === undefined ) throw "Bad Node at " + index + " for " + word;
 
		if(index === word.length - 1) {
			//last letter
			//always delete word marker (as we are deleting word)
			return (delete node.$) && noKids(node); //if last letter of word, should be empty.
		}
		else {
			//any other letter in word
			//check child, and after child check, I am now empty
			if(canDelete(word, index + 1, node[word[index + 1]]) )
			{
				//delete me
				return (delete node[word[index + 1]]) && noKids(node);
			}
		}
		return false;
	};
 
	function noKids(node) {
		return Object.keys(node).length === 0;
	};
};
 
trie.prototype.sort = function() {
	var word = "";
	var sorted = [];
 
	sortTrie(this.head, word, sorted);
 
	function sortTrie(node, word, sorted) {
		for(var letter in node) {
			if (letter == '$') { sorted.push(word); }
			else {
				sortTrie(node[letter], word + letter, sorted);
			}
		}
	}
 
	return sorted;
};
 
module.exports = trie;