Created
December 21, 2017 00:01
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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