Assignment 13

TRIE Spellchecker

by ClarenceDowns

HTML

<h1>
  Assignment 13: "TRIE Spellchecker"
</h1>
<input type="textbox" id="uInput" value="" />
<input type="button" value="Add To Dictionary" id="add" />
<input type="button" value="Spell Check" id="spellCheck" />
<p id="output1"></p>
<p id="output2"></p>

JavaScript

//Node Constructor
let Node = function() {
  this.keys = new Map(); //each node will have a key, which is a new Map(); 
  //which is an es6 map structure. This will be used to keep a list of all the other
  //letters in the node
  this.end = false;
  //setter functions to set end of words to true or false
  this.setEnd = function() {
    this.end = true;
  };
  this.isEnd = function() {
    return this.end;
  };
};
//TRIE Constructor: 2 methods; Add (adds nodes to TRIE, and/or letters in Map() of nodes);
//and isWord (checks is word exists in the TRIE. Word exists if this.end == true)
let Trie = function() {

  this.root = new Node();

  this.add = function(input, node = this.root) {
    if (input.length == 0) {
      node.setEnd();
      return;
    } else if (!node.keys.has(input[0])) {
      node.keys.set(input[0], new Node());
      return this.add(input.substr(1), node.keys.get(input[0]));
    } else {
      return this.add(input.substr(1), node.keys.get(input[0]));
    }
  };

  this.isWord = function(word) {
    let node = this.root;
    while (word.length > 1) {
      if (!node.keys.has(word[0])) {
        return false;
      } else {
        node = node.keys.get(word[0]);
        word = word.substr(1);
      }
    }
    return (node.keys.has(word) && node.keys.get(word).isEnd()) ?
      true : false;
  };

};
var myDictionary = new Trie()
myDictionary.add('I');
myDictionary.add('in');
myDictionary.add('into');
myDictionary.add('inlet');
myDictionary.add('inn');
myDictionary.add('inner');
myDictionary.add('innate')
myDictionary.add('ink');
//Function called when add button is clicked.
//Informs user that the word entered has been added
document.getElementById("add").onclick = function() {
  var wordAdded = document.getElementById("uInput").value;
  myDictionary.add(wordAdded);
  document.getElementById("output1").innerHTML = "Word added: " + wordAdded;

};
//Function called when the Spell Check button is...