TRIE
by arosado417
HTML
<h1>
Assignment 13 – TRIE Spellchecker
</h1>
<h2>
Enter a string to see all words beginning with the string</br>
</h2>
<input type="text" placeholder="user input" id="input" />
<input type="button" value="Add to Dictionary" id="add" />
<input type="submit" value="Spell Check" id="check" />
<p id="output1">
</p>
<p id="output2">
</p>
<p id="output3">
</p>
JavaScript
var Trie = function(letter){
this.letter = letter || '';
this.isWord = false;
this.children = {};
// Adds a new word into the prefix tree
this.insert = function(word) {
var currentNode = this;
var newNode;
var ch;
// Loop through all the letters of the word to be inserted.
for (var i = 0; i < word.length; i++) {
this.children = word.charAt(i);
// Check if the current node already has a property corresponding to the next letter
if (currentNode[this.children]) {
// If it does have that letter already
// Move current node on to the next child node corresponding to next letter
currentNode = currentNode[this.children];
// If Next letter node DOESN'T exists
} else {
// create a new child node for the next letter
// move current node on to the new node
newNode = new Trie(this.children);
currentNode[this.children] = newNode;
currentNode = newNode;
}
// When the last letter is reached, set the current node's
// isWord property to true to represent the end of a complete
// word.
if (i === word.length - 1) {
currentNode.isWord = true;
}
}
}
this.contains = function(str) {
var currentNode = this;
var ch;
// Loop through each letter in the string
for (var i = 0; i < str.length; i++) {
this.children = str.charAt(i);
// Check if the current node has a link to that letter
if (!currentNode[this.children]) {
// If it doesn't, str isn't a valid word so return false
return false;
} else {
// If it is a valid letter, move on to the next node.
currentNode = currentNode[this.children];
}
// If we reach the end of the string and the current node
// represents a complete word, return true.
if (i === str.length - 1 && currentNode.isWord) {
return true;
}
}
// If we reach the end of the string, but it's not a complete
// word, return false.
return false;
};
this.getWords= function(str,...