11/**
22 * Hash Map data structure implementation
3+ *
4+ * Features:
5+ * - HashMap offers 0(1) lookup and insertion.
6+ * - Keys are ordered by their insertion order (like LinkedHashMap)
7+ * - It contains only unique elements.
8+ * - It may have one null key and multiple null values.
9+ *
310 * @author Adrian Mejia <me AT adrianmejia.com>
411 */
512class HashMap {
@@ -20,7 +27,7 @@ class HashMap {
2027 * Decent hash function where each char ascii code is added with an offset depending on the possition
2128 * @param {any } key
2229 */
23- hash ( key ) {
30+ static hashCode ( key ) {
2431 let hashValue = 0 ;
2532 const stringTypeKey = `${ key } ${ typeof key } ` ;
2633
@@ -33,11 +40,12 @@ class HashMap {
3340 }
3441
3542 /**
36- * Get the array index after applying the hash funtion to the given key
43+ * A hash function converts keys into array indices
3744 * @param {any } key
45+ * @returns {Number } array index given the bucket size
3846 */
39- _getBucketIndex ( key ) {
40- const hashValue = this . hash ( key ) ;
47+ hashFunction ( key ) {
48+ const hashValue = HashMap . hashCode ( key ) ;
4149 const bucketIndex = hashValue % this . buckets . length ;
4250 return bucketIndex ;
4351 }
@@ -101,7 +109,7 @@ class HashMap {
101109 * @param {any } key
102110 */
103111 _getIndexes ( key ) {
104- const bucketIndex = this . _getBucketIndex ( key ) ;
112+ const bucketIndex = this . hashFunction ( key ) ;
105113 const values = this . buckets [ bucketIndex ] || [ ] ;
106114
107115 for ( let entryIndex = 0 ; entryIndex < values . length ; entryIndex ++ ) {
@@ -191,4 +199,7 @@ class HashMap {
191199 }
192200}
193201
202+ // Aliases
203+ HashMap . prototype . containsKey = HashMap . prototype . has ;
204+
194205module . exports = HashMap ;
0 commit comments