11/**
22 * Hash Map data structure implementation
3+ * @author Adrian Mejia <me AT adrianmejia.com>
34 */
45class HashMap {
56
@@ -39,7 +40,8 @@ class HashMap {
3940 }
4041
4142 /**
42- * insert a key/value pair into the hash map
43+ * Insert a key/value pair into the hash map.
44+ * If the key is already there replaces its content. Return the Map object to allow chaining
4345 * @param {any } key
4446 * @param {any } value
4547 */
@@ -60,15 +62,13 @@ class HashMap {
6062 * @param {any } key
6163 */
6264 get ( key ) {
63- const hashIndex = this . getIndex ( key ) ;
64- const values = this . array [ hashIndex ] || [ ] ;
65+ const { hashIndex, arrayIndex} = this . _getIndexes ( key ) ;
6566
66- for ( let index = 0 ; index < values . length ; index ++ ) {
67- const entry = values [ index ] ;
68- if ( entry . key === key ) {
69- return entry . value
70- }
67+ if ( arrayIndex === undefined ) {
68+ return ;
7169 }
70+
71+ return this . array [ hashIndex ] [ arrayIndex ] . value ;
7272 }
7373
7474 /**
@@ -81,6 +81,7 @@ class HashMap {
8181
8282 /**
8383 * Search for a key in the map. It returns it's internal array indexes.
84+ * Returns hashIndex and the internal array index
8485 * @param {any } key
8586 */
8687 _getIndexes ( key ) {
@@ -94,7 +95,7 @@ class HashMap {
9495 }
9596 }
9697
97- return { } ;
98+ return { hashIndex } ;
9899 }
99100
100101 /**
@@ -104,7 +105,7 @@ class HashMap {
104105 delete ( key ) {
105106 const { hashIndex, arrayIndex} = this . _getIndexes ( key ) ;
106107
107- if ( ! hashIndex || arrayIndex ) {
108+ if ( arrayIndex === undefined ) {
108109 return false ;
109110 }
110111
@@ -142,3 +143,7 @@ assert.equal(hashMap.delete('rat'), true);
142143assert . equal ( hashMap . has ( 'rat' ) , false ) ;
143144assert . equal ( hashMap . size , 3 ) ;
144145
146+ // set override
147+ // assert.equal(hashMap.get('art'), 0);
148+ // hashMap.set('art', 2);
149+ // assert.equal(hashMap.get('art'), 2);
0 commit comments