Last active
June 27, 2017 07:15
-
-
Save codyromano/f60f844b018d2a1aad0627152aebdb1c to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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