Next we'll use a while
loop to iterate through each letter of the word, and create nodes for each of the children and attach them to the appropriate key. Depending on the language, there may be a more efficient implementation where the lookup and initialization happen simultaneously.
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
18 // Break each character into levels respectively
19 // 'val' is the character, and 'value' lets us know if it terminates
20 while (currentChar.length) {
21 newNode = {
22 val: currentChar,
23 value: val.length === 0 ? null : undefined,
24 children: {},
25 };
26
27 currentNode.children[currentChar] = newNode;
28
29 currentNode = newNode;
30
31 currentChar = val.slice(0, 1);
32 val = val.slice(1);
33 }
34}