Assignment 13 - TRIE Spellchecker

by aren_anderson

HTML

<h1>
  TRIE Spellchecker
</h1>



<h4>
  Enter a word to add to dictionary: <input type="textbox" id="tbWord" onkeyup="change(value)"/>
</h4>


<input type="button" id="btnAdd" value="Add Word" onclick="addWord();" />
<input type="button" id="btnSpellcheck" value="Check Spelling" onclick="check();" />

<br/><br/>
<div id="output">
</div>
<div id="output2">
</div>
<div id="output3">
</div>

JavaScript

debugger;
//trie function
function Trie(key) {
  this.key = key;
}

Trie.prototype.addToTrie = function(word) {
  var node = this;
  var len = word.length;
  var current;

  for (var i = 0; i < len; i++) {
    current = word[i];
    node = node[current] || (node[current] = new Trie(current));
  }
  node.value = word;
  node.word = word;
}

Trie.prototype.checkSpelling = function(word) {
  var node = this;
  var len = word.length;

  for (var i = 0; i < len; i++) {
    if (!(node = node[word[i]])) break;
  }
  return (i == len) ? "Word exists" : "Word does not exist or is misspelled";
}

var dictionary = new Trie();
dictionary.addToTrie("I");
dictionary.addToTrie("in");
dictionary.addToTrie("into");
dictionary.addToTrie("inlet");
dictionary.addToTrie("inn");
dictionary.addToTrie("inner");
dictionary.addToTrie("innate");
dictionary.addToTrie("ink");

function addWord() {
  document.getElementById("output3").innerHTML = "";
  var newWord = document.getElementById("tbWord").value;
  dictionary.addToTrie(newWord);
  document.getElementById("output2").innerHTML = "Added the word " + newWord + " to the dictionary.";
}

function check() {
  var newWord = document.getElementById("tbWord").value;
  document.getElementById("output2").innerHTML = "";
  document.getElementById("output3").innerHTML = "Checked the following word for spelling: " + newWord;
  document.getElementById("output2").innerHTML = dictionary.checkSpelling(newWord);
}

var w = ["I", "in", "into", "inlet", "inn", "inner", "innate", "ink"];

function matchWords(input) {
  var reg = new RegExp(input.split('').join('\\w*').replace(/\W/, ""), 'i');
  return w.filter(function(input) {
    if (input.match(reg)) {
      return input;
    }
  });
}

function change(input) {
  var complete = matchWords(input);
  document.getElementById("output").innerHTML = complete;
}