@@ -5,6 +5,12 @@ class Trie {
5
5
this . root = new Node ( '' ) ;
6
6
}
7
7
8
+ // helper to get the index of a character
9
+ // eslint-disable-next-line class-methods-use-this
10
+ getIndexOfChar ( char ) {
11
+ return char . charCodeAt ( 0 ) - 'a' . charCodeAt ( 0 ) ;
12
+ }
13
+
8
14
insert ( key ) {
9
15
if ( ! key ) {
10
16
return false ;
@@ -29,11 +35,39 @@ class Trie {
29
35
return true ;
30
36
}
31
37
32
- // helper to get the index of a character
33
- // eslint-disable-next-line class-methods-use-this
34
- getIndexOfChar ( char ) {
35
- return char . charCodeAt ( 0 ) - 'a' . charCodeAt ( 0 ) ;
38
+ search ( key ) {
39
+ if ( ! key ) {
40
+ return false ;
41
+ }
42
+
43
+ // convert word to lower case
44
+ const word = key . toLowerCase ( ) ;
45
+ let currentNode = this . root ;
46
+
47
+ for ( let level = 0 ; level < word . length ; level += 1 ) {
48
+ const index = this . getIndexOfChar ( word [ level ] ) ;
49
+ if ( ! currentNode . children [ index ] ) {
50
+ return false ;
51
+ }
52
+ currentNode = currentNode . children [ index ] ;
53
+ }
54
+ if ( currentNode !== null && currentNode . isEndOfWord ) {
55
+ return true ;
56
+ }
57
+ return false ;
36
58
}
37
59
}
38
60
61
+ const words = [ 'bed' , 'ball' , 'apple' , 'java' , 'javascript' ] ;
62
+ const trie = new Trie ( ) ;
63
+
64
+ words . forEach ( word => trie . insert ( word ) ) ;
65
+
66
+ console . log ( trie . root ) ;
67
+
68
+ console . log ( trie . search ( words [ 3 ] ) ) ;
69
+ console . log ( trie . search ( 'word' ) ) ;
70
+ console . log ( trie . search ( words [ 4 ] ) ) ;
71
+ console . log ( trie . search ( 'random' ) ) ;
72
+
39
73
module . exports = Trie ;
0 commit comments