Spellchecker

Assignment 13

by Jake Jernigan

HTML

<input type="textbox" id="word" str="" />
<input type="button" id="button1" value="Add to Dictionary" onClick="Spellchecker.addToDictionary()" />
<input type="button" id="button2" value="Spell Check" onClick="Spellchecker.checkSpelling()" />
<br/>
<br/>
<p id="output1"></p>
<br/> Current dictionary:
<p id="output2"></p>
Test Test

JavaScript

function TRIE() {
  this.words = 0;
  this.prefixes = 0;
  this.children = [];
}

TRIE.prototype.addToTRIE = function(word, pos) {
  var k;
  var child;

  if (word.length == 0) {
    return;
  }
  if (pos === undefined) {
    pos = 0;
  }
  if (pos === word.length) {
    this.words++;
    return;
  }

  this.prefixes++;
  k = word[pos];
  if (this.children[k] === undefined) {
    this.children[k] = new TRIE();
  }
  child = this.children[k];
  child.addToTRIE(word, pos + 1);
}

TRIE.prototype.countWord = function(word, pos) {
  var k;
  var child;
  var count = 0;

  if (word.length == 0) {
    count = 0;
  }

  if (pos === undefined) {
    pos = 0;
  }
  if (pos === word.length) {
    count = this.words;
  }

  k = word[pos];
  child = this.children[k];
  if (child !== undefined) {
    count = child.countWord(word, pos + 1);
  }

  return count;
}

TRIE.prototype.createDictionary = function() {
  this.addToTRIE("apple");
  this.addToTRIE("orange");
  this.addToTRIE("lemon");
  this.addToTRIE("grape");
  this.addToTRIE("Jake");
  this.addToTRIE("Joe");
  this.addToTRIE("Shannon");
  this.addToTRIE("Vickie");
}

TRIE.prototype.printDictionary = function(word) {
  var k;
  var child;
  var ret = [];
  var s = "";

  if (word === undefined) {
    word = "";
  }
  if (this === undefined) {
    return [];
  }
  if (this.words > 0) {
    ret.push(word);
  }
  for (k in this.children) {
    child = this.children[k];
    ret = ret.concat(child.printDictionary(word + k));
  }
  for (var i = 0; i < ret.length; i++) {
    s += ret[i] + " ";
  }

  return s;
}

TRIE.prototype.addToDictionary = function(word, pos) {
  clearDisplay();
  var word = document.getElementById("word").value;
  if (word.length == 0) {
    document.getElementById("output1").innerHTML += "Error: An empty string cannot be added to the dictionary. Please enter a word.";
  } else if (!isNaN(word)) {
    document.getElementById("output1").innerHTML += "Error: A number cannot be added to the dictionary....