Solution to Data Structures: Create a Map Data Structure?

What is your hint or solution suggestion?

Solution
var Map = function() {
  this.collection = {};
  // change code below this line
  this.add = function(key, value) {
    this.collection[key] = value;
  };
  this.remove = function(key) {
    if (this.hasOwnProperty(key)) {
      delete this.collection[key]
    }
  };
  this.get = function(key) {
    return this.collection[key]
  };
  this.has = function(key) {
    if (this.collection[key] == undefined) return false;
    else return true
  };
  this.values = function() {
    return Object.values(this.collection)
  };
  this.size = function() {
    return (Object.keys(this.collection).length)
  };
  this.clear = function () {
    for (const key in this.collection) {
      delete this.collection[key]
    }
  }
  // change code above this line
};

Challenge: Create an ES6 JavaScript Map

Link to the challenge:

ES6 Map accepts keys of any type, including undefined:

const map = new Map();
map.set(undefined, 42);
map.get(); // 42
map.has(); // true

Do you want to challenge yourself and fix your solution? :slight_smile:

1 Like

thank you so much for pointing that out! may not have realized that until later. used obj.hasOwnProperty method instead! would that work?

I’m somewhat new here, would the challenges without solutions have solutions in the future?

once a solution is submitted for the guide (in the way you did) if it’s correct and complete it is added to the guide after evaluation

1 Like

Welcome, masonisblue.

Thank you, for your contribution. For future contributions, please wrap your solution within :

[details]
```
code goes here...
```
[/details]

Also, when you enter a code block into a forum post, please precede it with a separate line of three backticks and follow it with a separate line of three backticks to make it easier to read.

You can also use the “preformatted text” tool in the editor ( </> ) to add backticks around text.

See this post to find the backtick on your keyboard.
Note: Backticks (`) are not single quotes (’).

1 Like