Assignment 13
TRIE Spellchecker
by F Fornos
HTML
<input id="text">
<button id="add">
Add To Dictionary
</button>
<button id="search">
Spell Check
</button>
<div id="content">
</div>
JavaScript
var node = {
key: null,
value: null,
children: []
}
function Trie() {
this.head = {
key: '',
children: {}
}
}
Trie.prototype.add = function(key) {
var curNode = this.head,
newNode = null,
curChar = key.slice(0, 1);
key = key.slice(1);
while (typeof curNode.children[curChar] !== "undefined" && curChar.length > 0) {
curNode = curNode.children[curChar];
curChar = key.slice(0, 1);
key = key.slice(1);
}
while (curChar.length > 0) {
newNode = {
key: curChar,
value: key.length === 0 ? null : undefined,
children: {}
};
curNode.children[curChar] = newNode;
curNode = newNode;
curChar = key.slice(0, 1);
key = key.slice(1);
}
};
Trie.prototype.search = function(key) {
var curNode = this.head,
curChar = key.slice(0, 1),
d = 0;
key = key.slice(1);
while (typeof curNode.children[curChar] !== "undefined" && curChar.length > 0) {
curNode = curNode.children[curChar];
curChar = key.slice(0, 1);
key = key.slice(1);
d += 1;
}
if (curNode.value === null && key.length === 0) {
return d;
} else {
return -1;
}
}
Trie.prototype.print = function() {
var curNode = this.head;
var div = document.getElementById("content");
var searchUtil = function(curNode, str) {
var found = false;
for (var key in curNode.children) {
searchUtil(curNode.children[key], str + curNode.key);
found = true;
}
if (!found) {
div.innerHTML = div.innerHTML + "</br>" + str + curNode.key;
}
}
div.innerHTML = "";
searchUtil(this.head, "");
}
ourTrie = new Trie();
document.getElementById("add").addEventListener("click", function() {
var text = document.getElementById("text").value;
ourTrie.add(text);
alert(text + " was added in dictionary.")
ourTrie.print()
});
document.getElementById("search").addEventListener("click", function() {
var text = document.getElementById("text").value;
if (ourTrie.search(text)...