1
+ class Trie {
2
+ rootNode = new Node ( ) ;
3
+ constructor ( ) {
4
+ this . rootNode = new Node ( ) ;
5
+ }
6
+
7
+ insert ( str ) {
8
+ const characters = [ ...str ] ;
9
+ // we start with the rootNode, which has no character value
10
+ let currentNode = this . rootNode ;
11
+ for ( let ii = 0 ; ii < charactres . length ; ii ++ ) {
12
+ // in the "dog" example, this would be the character "d"
13
+ const currentChar = characters [ ii ] ;
14
+
15
+ /* this is checking if currentNode contains a child node with currentChar.
16
+ ** this is not chekcing if currentNode's char value is currentChar
17
+ ** in fact, each node does NOT know its own character value, only keeps track of
18
+ ** children nodes. In this case, rootNode does not have "d" yet, so we add a new node under
19
+ ** root for "d". */
20
+ if ( ! currentNode . contains ( currentChar ) ) {
21
+ currentNode . addNode ( currentChar ) ;
22
+ // now rootNode's hashMap has {d: Node}
23
+ }
24
+
25
+ currentNode = currentNode . getNode ( currentChar ) ; // then we traverse to the newly created "d" node
26
+ }
27
+
28
+ currentNode . isWord = true ;
29
+ }
30
+
31
+ hasWord ( str ) {
32
+ const wordCharacters = [ ...str ] ;
33
+ let currentNode = this . rootNode ;
34
+ for ( let ii = 0 ; ii < wordCharacters . length ; ii ++ ) {
35
+ const currentChar = wordCharacters [ ii ] ;
36
+ if ( ! currentNode . contains ( currentChar ) ) {
37
+ return false ;
38
+ }
39
+
40
+ currentNode = currentNode . getNode ( currentChar ) ;
41
+ }
42
+
43
+ return currentNode . isWord ;
44
+ }
45
+ }
46
+
47
+ class Node {
48
+ map ;
49
+ isWord ;
50
+ constructor ( ) {
51
+ this . map = new Map ( ) ;
52
+ this . isWord = false ;
53
+ }
54
+
55
+ contains ( char ) {
56
+ return ! ! this . map . get ( char ) ;
57
+ }
58
+
59
+ addNode ( char ) {
60
+ if ( ! this . contains ( char ) ) {
61
+ this . map . set ( char , new Node ( ) )
62
+ }
63
+ }
64
+
65
+ getNode ( char ) {
66
+ return this . map . get ( char ) ;
67
+ }
68
+ }
0 commit comments