Trie Check Test
by dhizzybusy
HTML
<p id ="Instructions">
Words already in the dictionary: I, in, into, inlet, inn, inner, innate, ink.
</p><br/> Word to add:
<input type="textbox" id="X" value="" />
<input type="button" value="Add To Dictionary" onclick="AddTo();" />
<input type="button" value="Spell Check" onclick="Check();" />
<p id="output"></p>
<p id="output2"> </p>
JavaScript
function Trie(key) {
this.key = key;
this.value;
}
Trie.prototype.AddToTrie = function (name) {
var node = this,
nameLength = name.length,
i = 0,
currentLetter;
for (i = 0; i < nameLength; i++) {
currentLetter = name[i];
node = node[currentLetter] || (node[currentLetter] = new Trie(currentLetter));
}
node.value = name;
node.name = name;
};
Trie.prototype.SpellCheck = function (name) {
var node = this,
nameLength = name.length,
i, node;
for (i = 0; i < nameLength; i++) {
if (!(node = node[name[i]])) break;
}
return (i === nameLength) ? 'Value Exists' : 'Value not found or spelled incorrectly';
};
// --------
// Each branch (key) contains a single letter
// If the letter already exists, a new branch, or child, is made
// At the end of each branch there is a "leaf" that holds a value (the word each path spells)
// I originaly had a second paramter to store any value at the end, but decided to make the value the same as the name for simplicity.
var dict = new Trie();
dict.AddToTrie("I");
dict.AddToTrie("in");
dict.AddToTrie("into");
dict.AddToTrie("inlet");
dict.AddToTrie("inn");
dict.AddToTrie("inner");
dict.AddToTrie("innate");
dict.AddToTrie("ink");
//console.log(JSON.stringify(dict));
function AddTo() {
document.getElementById("output2").innerHTML = "";
var Value = document.getElementById("X").value;
if (Value == 0){var A ="Please Enter A Value";
return A;}
dict.AddToTrie(Value);
document.getElementById("output").innerHTML= "Word Added = " + Value;
}
function Check() {
document.getElementById("output").innerHTML = "";
document.getElementById("output2").innerHTML = "Word Checked: ";
var Value = document.getElementById("X").value;
if (Value == 0) { var A = "Please Enter A Value";
return A;}
document.getElementById("output").innerHTML = dict.SpellCheck(Value);
document.getElementById("output2").innerHTML += Value;
}