We can use a while
loop to determine the appropriate place to assign our word as a child key in a children
hash. It does this by trying to look for each of our word's characters in the current node's children
hash, and if there's a match, we try to place it in the next child's children
hash. This handles the case where lineages like c -> a -> t
in "category"
may have already been previously added with a word like "cater"
.
1add(val) {
2 let currentNode = this.head,
3 newNode = null,
4 currentChar = val.slice(0, 1);
5
6 val = val.slice(1);
7
8 // See how deep we can get in any existing branches
9 while (
10 typeof currentNode.children[currentChar] !== 'undefined' &&
11 currentChar.length > 0
12 ) {
13 currentNode = currentNode.children[currentChar];
14 currentChar = val.slice(0, 1);
15 val = val.slice(1);
16 }
17}