Assignment #13 - TRIE Spellchecker

by Mike Kerney

HTML

<input type=text box id=input value="Enter Word:"/> 
<input type=button onclick = "AddToTRIE()" value="Add word to dictionary"/>
<input type=button onclick = "CheckSpelling()" value="Check Dictionary"/>
<br/>
<br/>

<div id="output">

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

</div>

JavaScript

function Node(content) {
  this.content= content;
  this.inDict = false;
  this.children = [];
}

function TRIE() {
  this.root = new Node();
}

TRIE.prototype.add = function(input) {
 if ( this.root == null) {
    return;
  }
  this._addNode(this.root, input);
}

TRIE.prototype.has = function(input) {
  if (this.root == null) {
    return;
  }
  return this._has(this.root, input);
}
TRIE.prototype._addNode = function(node, input) {
  if (node == false || input == false) {
    return null;
  }
  var char = input.charAt(0);
  var child = node.children[char];
  if (child == null) {
    child = new Node(char);
    node.children[char] = child;
  }
  var remainder = input.substring(1);
  if (remainder == 0) {
    child.inDict = true;
  }
  this._addNode(child, remainder);


TRIE.prototype._has = function(node, input) {
  if (node == null || input == null) {
    return false;
  }
  var char = input.charAt(0);
  var child = node.children[char];
  if (child) {
    var remainder = input.substring(1);
    if (remainder == false && child.inDict) {
      return true;
    } else {
      return this._has(child, remainder);
    }
  } else {
    return false;
  }
 }
}

var newTRIE = new TRIE();

newTRIE.add("I");
newTRIE.add("in");
newTRIE.add("into");
newTRIE.add("inlet");
newTRIE.add("inn");
newTRIE.add("inner");
newTRIE.add("innate");
newTRIE.add("ink");

function AddToTRIE() {
	var newWord = document.getElementById("input").value;
  newTRIE.add(newWord);
  document.getElementById("output").innerHTML = "The word * " + newWord +" * was added to the dictionary";
 }

function CheckSpelling() {
 var wordCheck = document.getElementById("input").value;
 	if (newTRIE.has(wordCheck)) {
  	document.getElementById("output2").innerHTML = "The word * "+ wordCheck + " * is in the dictionary";    
  }
  else {
  	document.getElementById("output2").innerHTML = "The word * "+ wordCheck + " * is not in the dictionary";   
  }
}