TRIE spell checker
Assignment 13
by Alan Harris
HTML
Insert a word: <br>
<input id="text"> <br> <button id="add"> Add Word to Dictionary</button><br>
<button id="search"> Search the Dictionary </button>
<div id="content"> </div>
CSS
button:focus {
border: 1px solid black;
padding: 4px 4px;
}
button {
background-color: grey;
border: 1px solid black;
color: white;
padding: 4px 8px;
text-decoration: none;
margin: 4px 2px;
}
button:hover {
background-color:black;
}
JavaScript
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 Search
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, "");
}
//Alert add
ourTrie = new Trie();
document.getElementById("add").addEventListener("click", function() {
var text = document.getElementById("text").value;
ourTrie.add(text);
alert(text + " was added to the dictionary.")
ourTrie.print()
});
// Alert Results from Search
document.getElementById("search").addEventListener("click", function() {
var text = document.getElementById("text").value;
if (ourTrie.search(text) != -1) {
alert(text + " was found in the dictionary");
} else {
...