Skip to content

Instantly share code, notes, and snippets.

@codyromano
Last active June 27, 2017 07:15
Show Gist options
  • Select an option

  • Save codyromano/f60f844b018d2a1aad0627152aebdb1c to your computer and use it in GitHub Desktop.

Select an option

Save codyromano/f60f844b018d2a1aad0627152aebdb1c to your computer and use it in GitHub Desktop.
class Trie {
constructor() {
// The tree containing letters as nodes
this.contents = {};
}
addString(string) {
let pointer = this.contents;
/* The position of each letter in the string dicates
its depth in the tree. For instance, in "bacon",
"a" has a depth of 2, "c" a depth of 3, and so on. */
for (const char of string.split('')) {
pointer[char] = pointer[char] || {};
pointer = pointer[char];
}
}
exists(string) {
let pointer = this.contents;
if (!string.length) {
return false;
}
/* If a letter exists in the tree, we advance
the pointer to see if the following letter exists.
Otherwise, if a letter doesn't exist, we know
there isn't a match. */
for (const char of string.split('')) {
if (pointer[char]) {
pointer = pointer[char];
} else {
return false;
}
}
return true;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment