1+ /**
2+ * Hash Map data structure implementation
3+ */
4+ class HashMap {
5+
6+ /**
7+ * Initialize array that holds the values. Default is size 1,000
8+ * @param {number } size
9+ */
10+ constructor ( size = 1000 ) {
11+ this . array = new Array ( size ) ;
12+ }
13+
14+ /**
15+ * insert a key/value pair into the hash map
16+ * @param {any } key
17+ * @param {any } value
18+ */
19+ set ( key , value ) {
20+ const index = this . getIndex ( key ) ;
21+ if ( this . array [ index ] ) {
22+ this . array [ index ] . push ( { key, value} ) ;
23+ } else {
24+ this . array [ index ] = [ { key, value} ] ;
25+ }
26+ return this ;
27+ }
28+
29+ /**
30+ * Gets the value out of the hash map
31+ * @param {any } key
32+ */
33+ get ( key ) {
34+ const hashIndex = this . getIndex ( key ) ;
35+ const values = this . array [ hashIndex ] ;
36+ for ( let index = 0 ; index < values . length ; index ++ ) {
37+ const entry = values [ index ] ;
38+ if ( entry . key === key ) {
39+ return entry . value
40+ }
41+ }
42+ }
43+
44+ /**
45+ * Decent hash function where each char code is added with an offset depending on the possition
46+ * @param {any } key
47+ */
48+ hash ( key ) {
49+ let hashValue = 0 ;
50+ const stringKey = key . toString ( ) ;
51+
52+ for ( let index = 0 ; index < stringKey . length ; index ++ ) {
53+ const charCode = stringKey . charCodeAt ( index ) ;
54+ hashValue += charCode << ( index * 8 ) ;
55+ }
56+
57+ return hashValue ;
58+ }
59+
60+ /**
61+ * Get the array index after applying the hash funtion to the given key
62+ * @param {any } key
63+ */
64+ getIndex ( key ) {
65+ const indexHash = this . hash ( key ) ;
66+ const index = indexHash % this . array . length ;
67+ return index ;
68+ }
69+ }
70+
71+ const assert = require ( 'assert' ) ;
72+ const hashMap = new HashMap ( ) ;
73+
74+ hashMap . set ( 'cat' , 2 ) ;
75+ hashMap . set ( 'rat' , 7 ) ;
76+ hashMap . set ( 'dog' , 1 ) ;
77+ hashMap . set ( 'art' , 0 ) ; // <-- NO more collision with rat
78+
79+ console . log ( hashMap . array ) ;
80+
81+ assert . equal ( hashMap . get ( 'cat' ) , 2 ) ;
82+ assert . equal ( hashMap . get ( 'rat' ) , 7 ) ;
83+ assert . equal ( hashMap . get ( 'dog' ) , 1 ) ;
0 commit comments