Challenge: Create a Map Data Structure
Create the following methods and operations on the Map object:
-
add
accepts akey, value
pair to add to the map. -
remove
accepts a key and removes the associatedkey, value
pair -
get
accepts akey
and returns the storedvalue
-
has
accepts akey
and returns true if the key exists or false if it doesn’t. -
values
returns an array of all the values in the map -
size
returns the number of items in the map -
clear
empties the map
Solution:
Solution
var Map = function() {
this.collection = {};
this.add = (key,value)=>{
this.collection[key] = value;
};
this.remove = (key)=>{
this.has(key) ? delete this.collection[key] : false;
};
this.has = (key)=>{
return this.collection.hasOwnProperty(key);
};
this.get = (key)=> {
if(this.has(key)){
return this.collection[key];
}
};
this.values = ()=>{
return Object.values(this.collection);
};
this.size = () => {
return this.values().length;
};
this.clear = () =>{
for(let el in this.collection){
delete this.collection[el];
}
};
};
Link to the challenge:
Map Data Structure