Skip to content

Instantly share code, notes, and snippets.

@mo7amd
Created December 21, 2017 00:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mo7amd/f79dd027860d7c7fbc2130865e3364a2 to your computer and use it in GitHub Desktop.
Save mo7amd/f79dd027860d7c7fbc2130865e3364a2 to your computer and use it in GitHub Desktop.
implement add method to Map Object to handle collision when add different value to the same key.
// add method to Map object
Map.prototype.add = function (key, value){
// check first if the key has value if not just set the value to the key
if ( map.has(key)) {
let oldValue = map.get(key); // get old value
let tempArr = []; // create temp array to collect new and values together
/* check if old value is array or not to make the values on one array which make
iteration over it when get the value command excute easier
**/
oldValue.constructor === Array ? tempArr = oldValue : tempArr.push(oldValue);
tempArr.push(value); // push new value to temp array
map.set(key,tempArr); // set temp array as new value to the key
return; // return from the function
}
map.set(key,value);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment