Assignment 13

Dictionary

by Nickolas Smiley

HTML

<input id="text"> <button id="add"> Add Word to Dictionary</button>
<button id="search"> Search the Dictionary </button>
<div id="content"> </div>

JavaScript

// Initialize the node
var node = {
  key: null,
  value: null,
  children: []
}

// The Trie Function
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 Search
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, "");
}

//Alert add
ourTrie = new Trie();

document.getElementById("add").addEventListener("click", function() {
  var text = document.getElementById("text").value;
  ourTrie.add(text);
  alert(text + " was added to the dictionary.")
  ourTrie.print()
});

// Alert Results from...