Trie in Typescript
by Preetha Srinivasan
HTML
<link rel="stylesheet" href="https://cdn.jsdelivr.net/jasmine/1.3.1/jasmine.css">
<script src="https://cdn.jsdelivr.net/jasmine/1.3.1/jasmine.js"></script>
<script src="https://cdn.jsdelivr.net/jasmine/1.3.1/jasmine-html.js"></script>
TypeScript
class TrieNode {
map: Map;
isWord: boolean;
constructor() {
this.map = new Map();
}
setIsWord(isWord) {
this.isWord = isWord;
}
getIsWord() {
return this.isWord;
}
}
class Trie {
root: TrieNode;
constructor() {
this.root = new TrieNode();
}
add(word: string) {
this.addRec(word, this.root);
}
addRec(word: string, node: TrieNode) {
if (word.length == 0) {
node.setIsWord(true);
return;
} else if (!node.map.has(word[0])) {
node.map.set(word[0], new TrieNode());
this.addRec(word.substr(1), node.map.get(word[0]));
} else {
this.addRec(word.substr(1), node.map.get(word[0]));
}
}
getWords() {
var words = [];
this.getWordsRec(this.root, "", words);
return words;
}
getWordsRec(node: TrieNode, word: string, words: []) {
if (node) {
for (let letter of node.map.keys()) {
this.getWordsRec(node.map.get(letter), word.concat(letter), words);
};
if (node.getIsWord()) {
words.push(word);
};
}
}
search(word:string){
var curr = this.root;
var cnt = 0;
var ch = word[cnt];
var isFound = true;
while(curr != null && cnt < word.length && isFound) {
if (!curr.map.has(ch)) {
isFound = false;
break;
} else {
curr = curr.map.get(ch);
ch = word[++cnt];
}
}
return isFound;
}
deleteWord(word:string) {
this.deleteWordRec(this.root,word);
}
deleteWordRec(curr:TrieNode,word:string){
if (curr) {
if (word.length > 1) {
curr = curr.map.get(word[0]);
this.deleteWordRec(curr,word.substr(1));
}
if (curr){
curr.map.delete(word[0]);
}
}
}
hasChildren(node:TrieNode){
return node.map.size > 0 ? true : false;
}
}
describe("Trie tests",function(){
it("Should be able to add items to the trie",function(){
var trie = new Trie();
trie.add("on");
trie.add("ox");
var...