File tree Expand file tree Collapse file tree 1 file changed +51
-0
lines changed Expand file tree Collapse file tree 1 file changed +51
-0
lines changed Original file line number Diff line number Diff line change
1
+ class HashTable {
2
+ constructor ( size = 50 ) {
3
+ this . size = size ;
4
+ this . buckets = new Array ( size ) ;
5
+ }
6
+
7
+ // Hash function
8
+ _hash ( key ) {
9
+ let hash = 0 ;
10
+ for ( const char of key ) {
11
+ hash = ( hash + char . charCodeAt ( 0 ) ) % this . size ;
12
+ }
13
+ return hash ;
14
+ }
15
+
16
+ // Set a key-value pair in the hash table
17
+ set ( key , value ) {
18
+ const index = this . _hash ( key ) ;
19
+ if ( ! this . buckets [ index ] ) {
20
+ this . buckets [ index ] = [ ] ;
21
+ }
22
+ this . buckets [ index ] . push ( [ key , value ] ) ;
23
+ }
24
+
25
+ // Get the value associated with a key
26
+ get ( key ) {
27
+ const index = this . _hash ( key ) ;
28
+ if ( ! this . buckets [ index ] ) {
29
+ return null ;
30
+ }
31
+
32
+ for ( const [ storedKey , value ] of this . buckets [ index ] ) {
33
+ if ( storedKey === key ) {
34
+ return value ;
35
+ }
36
+ }
37
+ return null ;
38
+ }
39
+
40
+ // Other hash table operations (remove, update, etc.) can be added here
41
+ }
42
+
43
+ // Example usage:
44
+ const hashTable = new HashTable ( ) ;
45
+
46
+ hashTable . set ( 'firstName' , 'John' ) ;
47
+ hashTable . set ( 'lastName' , 'Doe' ) ;
48
+ hashTable . set ( 'age' , 30 ) ;
49
+
50
+ console . log ( hashTable . get ( 'firstName' ) ) ; // Output: 'John'
51
+
You can’t perform that action at this time.
0 commit comments