Assignment 13

TRIE Spellcheck

by Daniel Eberhart

HTML

<!-- Assignment 13, TRIE Spell Check -->
<!--Daniel Eberhart, COP 3530 -->
<h2>
Assignment 13, TRIE Spell checker
</h2>
<h3>
Programmed by Daniel Eberhart
</h3>

<h5>
Insert a word in the box below, and click "Add to Dictionary" <br>
Repeat as many times as you'd like, and then Check Spelling to see if added to the dictionary correctly
</h5>
<input id="text">
<button id="add">
  Add To Dictionary 
</button>
<button id="search">
Spell Check
</button>

<div id="content">
</div>

JavaScript

var node = {
  key: null,
  value: null,
  children: []
}
function Trie() {
  this.head = {
    key: '',
    children: {}
  }
}
Trie.prototype.add = function(key) {
  var curNode = this.head,
    newNode = null,
    curChar = key.slice(0, 1);

  key = key.slice(1);

  while (typeof curNode.children[curChar] !== "undefined" && curChar.length > 0) {
    curNode = curNode.children[curChar];
    curChar = key.slice(0, 1);
    key = key.slice(1);
  }

  while (curChar.length > 0) {
    newNode = {
      key: curChar,
      value: key.length === 0 ? null : undefined,
      children: {}
    };

    curNode.children[curChar] = newNode;

    curNode = newNode;

    curChar = key.slice(0, 1);
    key = key.slice(1);
  }

};

Trie.prototype.search = function(key) {

  var curNode = this.head,
    curChar = key.slice(0, 1),
    d = 0;

  key = key.slice(1);

  while (typeof curNode.children[curChar] !== "undefined" && curChar.length > 0) {
    curNode = curNode.children[curChar];
    curChar = key.slice(0, 1);
    key = key.slice(1);
    d += 1;
  }

  if (curNode.value === null && key.length === 0) {
    return d;
  } else {
    return -1;
  }

}

Trie.prototype.print = function() {
  var curNode = this.head;

  var div = document.getElementById("content");
  var searchUtil = function(curNode, str) {
    var found = false;
    for (var key in curNode.children) {
      searchUtil(curNode.children[key], str + curNode.key);
      found = true;
    }
    if (!found) {
      div.innerHTML = div.innerHTML + "</br>" + str + curNode.key;
    }
  }
  div.innerHTML = "";
  searchUtil(this.head, "");
}

ourTrie = new Trie();
document.getElementById("add").addEventListener("click", function() {
  var text = document.getElementById("text").value;
  ourTrie.add(text);
  alert(text + " was added in dictionary.")
  ourTrie.print()
});
document.getElementById("search").addEventListener("click", function() {
  var text = document.getElementById("text").value;
  if (ourTrie.search(text) !=...