Adjusting ES2015 Map to accommodate the expected functionality

Exploring the capabilities of ES2015 Maps has been quite exciting, as I'm starting to see its potential. However, I've encountered a use case that has me stumped on whether Maps can handle it.

Let's take a look at my class:

class A {
     constructor(public a:number) {}
     public equals(obj: A): boolean {
         return this.a === obj.a;
     }
 }

From what I understand, ES2015 Maps utilize the === equality operator (with some exceptions). This raises the question - is it possible to customize the equality comparison and make Maps use the A object's equals(...) method if applicable?

My end goal is simple:

var map = new Map();
map.set(new A(8), 7)
map.get(new A(8))      // should return 7 instead of undefined

Do you believe that creating a custom Map class is necessary to achieve this behavior, where it checks if both objects are instances of A and then calls the equals(...) method?

Answer №1

To customize the behavior of the get method, you can create a subclass like this:

class MapByEquals extends Map {
  get(key) {
    for(var k of this.keys()) {
      if(key.equals(k)) {
        return super.get(k);
      }
    }
    return super.get(key);
  }
}

"use strict";
class A {
  constructor(a) {
    this.a = a;
  }
  equals(b) {
    return this.a === b.a;
  }
}

class MapByEquals extends Map {
  get(key) {
    for(var k of this.keys()) {
      if(key.equals(k)) {
        return super.get(k);
      }
    }
    return super.get(key);
  }
}

var map = new MapByEquals();
map.set(new A(8), 7)
console.log(map.get(new A(8)))

Note that Babel does not support native classes extension. However, most modern browsers (Chrome 42+, Firefox 45+) do support classes natively, so this code should work fine.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the best way to modify the color of a table cell in Typescript with *ngFor loop?

I have an image located at the following link: https://i.sstatic.net/rxDQT.png My goal is to have cells with different colors, where main action=1 results in a green cell and action=0 results in a red cell. Below is the HTML code I am working with: & ...

Exploring the power of AngularJS in manipulating Google Maps polygons with the help of ng-repeat

I recently started using a Google Maps plugin specifically designed for AngularJS, which can be found at . My goal is to display polygons on the map, so my HTML code looks something like this: <google-map center="map.center" zoom="map.zoom" draggab ...

How to trigger a force reload on a VueJS route with a different query parameter?

Is there a method to refresh the page component when two pages utilize the same Component? I have encountered an issue where the router does not reload and the previous edit values persist. { path: "/products/new", component: ProductPage, meta: { ...

Ways to retrieve the date of the chosen <td> cell in a calendar

Looking for a way to extract dates from the <td> elements selected by mouse? Here is my code snippet that highlights the TD upon selection: $(function () { var isMouseDown = false, isHighlighted; $("#schichtplan td") .moused ...

Avoiding cross-site scripting vulnerabilities, an AJAX response will return an HTML response

function accessAccount() { var errorMessage = ""; var checkedResult = true; $(".errorDisplay").hide(); var accountNumber = document.getElementById('customerAccountNumber').value; var accountType = document.getElementById(&apos ...

Module not found: vueform.config

For my current project, I decided to integrate Vueforms into the codebase. However, when I pasted their installation code into both my .ts and .js files, I encountered errors during the import of vueformconfig and builderconfig. This is a snippet of my ma ...

The magic of jQuery when chaining AJAX callback functions

I have a centralized ajaxSuccess callback function that needs to initialize components from various AJAX calls across the project. Here is an example: $(document).ajaxSuccess(function (response, status, xhr) { initComponents(); }); For module-level a ...

What is the best way to activate a JQ function with my submit button?

Is there a way to trigger a JQ function when clicking the submit button in a form? I managed to make Dreamweaver initiate an entire JS file, but not a particular function. ...

Is there a way in jQuery Validation to apply a rule to the entire form rather than just individual elements within the form?

I am facing an issue with a form where each element has its own custom rules that work perfectly. However, the form cannot be submitted unless values are provided for at least one of its elements. It seems like this is a rule for the entire form rather th ...

Implementing bi-directional data binding between sibling components in Vue.js

Is it possible to create a dual binding scenario with the typeahead plugin https://github.com/pespantelis/vue-typeahead, where the search terms of two typeaheads are linked? This means that regardless of which search box the user types into, both should ...

Revisiting the Issue: Jquery Hover Effect Fails to Function in Internet Explorer

Can anyone provide assistance with this issue? The code snippet works perfectly in all browsers except for IE, where the menu does not fade in and looks unattractive. html <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.o ...

Stripping the prefix from a string using the .split function leads to an error message stating "Unexpected

When dealing with a string containing a unique prefix, I attempted to separate it into an array after the backslash character "\" by using the split function. Here is the string: i:0#.w|itun\allepage_fg This was my approach: function claimOrder ...

Tips for streamlining code using switch statements in vue.js

Is there a more efficient way to simplify this switch statement for handling 5 different cases? Can I streamline the process of updating the completion status based on each step? data() { return { stepOneIsCompleted: false, ...

Oops! We encountered an issue in locating the Entry Module. The error message is indicating that it cannot find the specified source file

https://i.sstatic.net/m6kKr.png Currently enrolled in a Udemy course focusing on Wordpress development, I encountered an issue while attempting to integrate Google Maps into a custom post type. This required updating a JavaScript file, however, running &a ...

Spinning image on button click with seamless animation in Javascript

I'm trying to make an image rotate every second using the code below, but it's not working. Can you help me figure out why? <html> <head> <style> .rotated-image { -webkit-transform: rotate(2deg); transform: rotate(2deg); } & ...

Guidelines for transmitting form information to a web API using Angular

I am currently working on an Angular 6 project where I have a form and a table that retrieves data from a web API. I want to know if it's possible to send the form data to that web API. Here is the code snippet that I have so far: HTML Form: &l ...

Show and hide menu items without automatically scrolling the user back to the top of the page

I am currently working on a project where I have an image button that toggles between expanding and collapsing a menu using JavaScript. The issue I am facing is that every time the button is clicked, it takes the user back to the top of the page. My goal ...

The Textfield component in Material UI now automatically sets the default date to the current date when using the "date" type

I am using Material UI's textfield with the type set to "date" and I'm experiencing an issue where the date defaults to the current date instead of mm/dd/yyyy. Is there a way to prevent this behavior and display mm/dd/yyyy when the user loads the ...

define a variable within a v-for loop

Example of Code <div v-for="item in dataItems"> <div v-if="enableEdit"> <input type="text" v-model="name"> </div> <div v-else> {{name}} </div> <button @click="enableEdit = true">click</button> This ...

Leveraging the AngularJS promise/defer feature alongside the Quickblox framework, learn how to efficiently upload images and subsequently upload public URLs to a custom

I am currently developing an application that requires users to upload 5 images of themselves. Using a backend-as-a-service platform like Quickblox, I have to create and upload blob files individually. Once each image is uploaded, I receive a success call ...