Assignment 13

by Taylor Zimmerman

HTML

<html>
	<body>
		<fieldset>
		<legend>Enter or Check for Word in Dictionary</legend>
		<input type="textbox" id="txtInput"/>
		<br>
		<input type="button" id="AddWord" value="Add word to Dictionary" onClick="addToWord();" />
		<input type="button" id="CheckSpell" value="Check for word in DIctionary" onClick="checkSpell();" />
		<br>
		</fieldset>
		<fieldset>
		<legend>
		Dictionary Display</legend>
		<div id="btnOutput"/>
		</fieldset>
	</body>
</html>

JavaScript

var txtIn = document.getElementById("txtInput");
var d = document.getElementById("output");
var message = document.getElementById("btnOutput");

function TrieNode(key) {
  this.key = key;
  this.parent = null;
  this.children = {};
  this.end = false;
}

TrieNode.prototype.getWord = function() {
  var diction = [];
  var node = this;

  while (node !== null) {
    diction.unshift(node.key);
    node = node.parent;
  }
	return diction.join('');
}

function Trie() {
  this.root = new TrieNode(null);
}

Trie.prototype.insert = function(word) {
  var node = this.root; 
	
  for (var i = 0; i < word.length; i++) {
    if (!node.children[word[i]]) {
      node.children[word[i]] = new TrieNode(word[i]);
      node.children[word[i]].parent = node;
    }
    node = node.children[word[i]];
		
    if (i == word.length - 1) {
      node.end = true;
    }
  }
}

Trie.prototype.contains = function(word) {
  var node = this.root;
  for (var i = 0; i < word.length; i++) {
    if (node.children[word[i]]) {
      node = node.children[word[i]];
    } 
		else {
    	return false;
    }
  }
  return node.end;
}

var myTrie = new Trie();

myTrie.insert("i");
myTrie.insert("in");
myTrie.insert("into");
myTrie.insert("inlet");
myTrie.insert("inn");
myTrie.insert("inner");
myTrie.insert("innate");
myTrie.insert("ink");

function addToWord() {
  var word = txtIn.value;

  if (word == "") {
    message.innerHTML = "Please enter a word.";
  } 
	else {
    if (myTrie.contains(word.toLowerCase()) == true) {
    	message.innerHTML = "'" + word + "' already in dictionary.";
    } 
		else {
      myTrie.insert(word.toLowerCase())  
      message.innerHTML = "'" + word + "' added to dictionary!";
    }
  }
}

function checkSpell() {
  var word = txtIn.value;

  if (word == "") {
    message.innerHTML = "Please enter a word."
  } 
	else {
    if (myTrie.contains(word.toLowerCase()) == true) {
      message.innerHTML = "'" + word + "' found in dictionary.";
    } 
		else {
     message.innerHTML =...