File tree 1 file changed +53
-0
lines changed
1 file changed +53
-0
lines changed Original file line number Diff line number Diff line change
1
+ ( function ( win ) {
2
+
3
+ win . Trie = function ( ) {
4
+ this . holder = { } ;
5
+ } ;
6
+ // Caching the prototype as its used multiple times.
7
+ var trieProto = win . Trie . prototype ;
8
+ /*
9
+ * Prints the word to the console.
10
+ */
11
+ trieProto . print = function ( ) {
12
+ console . log ( this . holder ) ;
13
+ }
14
+
15
+ /*
16
+ * Adds the word to the trie.
17
+ * @param : word (word to be added to the trie)
18
+ */
19
+ trieProto . addWord = function ( word ) {
20
+ var l = word . length ; obj = this . holder ; var ch ;
21
+ for ( var i = 0 ; i < l ; i ++ ) {
22
+ ch = word . charAt ( i ) ;
23
+ if ( ! obj [ ch ] ) {
24
+ obj [ ch ] = { } ;
25
+ }
26
+ obj = obj [ ch ] ;
27
+ if ( i == l - 1 ) {
28
+ obj . count = ( obj . count ) ? obj . count + 1 : 1 ;
29
+ }
30
+ }
31
+ } ;
32
+
33
+ /*
34
+ * Searchs for the word in the trie.
35
+ * @params : word (word to be searched)
36
+ * return : Returns 0 if word not found
37
+ * Returns number of occurances of the word.
38
+ */
39
+ trieProto . search = function ( word ) {
40
+ var l = word . length ; obj = this . holder ; var ch ;
41
+ var found = true ;
42
+ for ( var i = 0 ; i < l ; i ++ ) {
43
+ ch = word . charAt ( i ) ;
44
+ if ( obj [ ch ] ) {
45
+ obj = obj [ ch ] ;
46
+ } else {
47
+ found = false ;
48
+ break ;
49
+ }
50
+ }
51
+ return ( found ) ? obj . count : 0 ;
52
+ }
53
+ } ) ( window ) ;
You can’t perform that action at this time.
0 commit comments