File tree 1 file changed +93
-0
lines changed
1 file changed +93
-0
lines changed Original file line number Diff line number Diff line change
1
+ class Node {
2
+ constructor ( key , value ) {
3
+ this . key = key ;
4
+ this . value = value ;
5
+ this . next = null ;
6
+ }
7
+ }
8
+
9
+ class Table {
10
+ constructor ( size ) {
11
+ this . cells = new Array ( size ) ;
12
+ }
13
+
14
+ hash ( key ) {
15
+ let total = 0 ;
16
+
17
+ for ( let i = 0 ; i < key . length ; i ++ ) {
18
+ total += key . charCodeAt ( i ) ;
19
+ }
20
+
21
+ return total % this . cells . length ;
22
+ }
23
+
24
+ insert ( key , value ) {
25
+ const hash = this . hash ( key ) ;
26
+
27
+ if ( ! this . cells [ hash ] ) {
28
+ this . cells [ hash ] = new Node ( key , value ) ;
29
+ } else if ( this . cells [ hash ] . key === key ) {
30
+ this . cells [ hash ] . value = value ;
31
+ } else {
32
+ let node = this . cells [ hash ] ;
33
+
34
+ while ( node . next ) {
35
+ if ( node . next . key === key ) {
36
+ node . next . value = value ;
37
+ return ;
38
+ }
39
+
40
+ node = node . next ;
41
+ }
42
+
43
+ node . next = new Node ( key , value ) ;
44
+ }
45
+ }
46
+
47
+ get ( key ) {
48
+ const hash = this . hash ( key ) ;
49
+ if ( ! this . cells [ hash ] ) {
50
+ return null ;
51
+ }
52
+
53
+ let node = this . cells [ hash ] ;
54
+
55
+ while ( node ) {
56
+ if ( node . key === key ) {
57
+ return node . value ;
58
+ }
59
+
60
+ node = node . next ;
61
+ }
62
+
63
+ return null ;
64
+ }
65
+
66
+ getAll ( ) {
67
+ const table = [ ] ;
68
+
69
+ for ( let i = 0 ; i < this . cells . length ; i ++ ) {
70
+ const cell = [ ] ;
71
+ let node = this . cells [ i ] ;
72
+
73
+ while ( node ) {
74
+ cell . push ( node . value ) ;
75
+ node = node . next ;
76
+ }
77
+
78
+ table . push ( cell ) ;
79
+ }
80
+
81
+ return table ;
82
+ }
83
+ }
84
+
85
+ const table = new Table ( 5 ) ;
86
+ table . insert ( "baa" , 1 ) ;
87
+ table . insert ( "aba" , 2 ) ;
88
+ table . insert ( "aba" , 3 ) ;
89
+ table . insert ( "aac" , 4 ) ;
90
+ table . insert ( "aac" , 5 ) ;
91
+
92
+ console . log ( table . get ( 'aac' ) ) ;
93
+ console . log ( table . get ( 'baa' ) ) ;
You can’t perform that action at this time.
0 commit comments