What are some methods for replacing the iterator or values in JavaScript / Typescript Set?

Looking to create a custom ArraySet in Typescript that handles arrays as values:

export class ArraySet extends Set<any> {
  override add(arr: any): any {
    super.add(arr.toString());
  }
  override has(arr): boolean {
    return super.has(arr.toString());
  }
}

Is there a way to modify this class to store and return array values?

Current behavior:

const set = new ArraySet()
set.add([1,1])
set.add([2,1])
set.forEach(e => console.log(typeof(e)))
# string 
# string

Expected behavior:

const set = new ArraySet()
set.add([1,1])
set.add([2,1])
set.forEach(e => console.log(typeof(e)))
# object       # expecting the element to be an array
# object

Answer №1

By incorporating a few recommendations, you may be able to avoid the need to override the iterator part and instead control what is included in the set like this:

class ArrayNumberSet extends Set<number[]> {
  private readonly keyMap: Map<string, number[]> = new Map();

  private key(value: number[]): string {
    return JSON.stringify(value);// or value.toString()
  }

  override add(value: number[]): this {
    const key = this.key(value);
    const old = this.keyMap.get(key);
    if (old) {
      this.delete(old);
    }
    this.keyMap.set(key, value);
    super.add(value);
    return this;
  }

  override clear(): void {
    this.keyMap.clear();
    super.clear();
  }

  override delete(value: number[]): boolean {
    const key = this.key(value);
    const old = this.keyMap.get(key);
    if (old) {
      this.keyMap.delete(key);
      return super.delete(old);
    }
    return false
  }

  override has(value: number[]): boolean {
      return this.keyMap.has(this.key(value))
  }
}

This implementation would distinguish [1, 2], [2, 1], [2, 1, 1] as distinct objects. If you prefer them to be treated as equivalent, consider using a set of sets or generating keys from sorted arrays.

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

I'm curious if someone can provide an explanation for `<->` in TypeScript

Just getting started with TypeScript. Can someone explain the meaning of this symbol <->? And, is ProductList actually a function in the code below? export const ProductList: React.FC<-> = ({ displayLoader, hasNextPage, notFound, on ...

Is it possible to create a click event for a mat-icon within a mat form field (either in the matprefix or matsuffix)?

I am working with a mat-form-field and have incorporated a custom mat-icon within it as a matprefix. However, I am now looking to create a click method for that matprefix icon. Despite my attempts to write a click method, it does not seem to be functioning ...

What is the best way to save an array in a session and retrieve it in Laravel?

There are certain fields in the form that need to be filled out. <form action="users/registration/new_user" method="post" class="new_user" enctype="multipart/form-data" novalidate="novalidate"> <div class="col-md-12 col-sm-12 col-xs-12 no-pa ...

Exploring the combination of Jasmine context and Typescript

Recently, while working with Jasmine and Typescript, our team has begun utilizing the this context in both the beforeEach and it functions. For example: beforeEach(() => { this.fixture = TestBed.createComponent(blablabla); }); it('should do so ...

Lazy loading images in a grid using React's react-lazy-load component

In my React application, I have a grid of images. To show these images in the div grid, I am utilizing sprites where each set of 10 divs uses a single URL to display the thumbnail. With approximately 16000 thumbnails to showcase, I decided to implement rea ...

Encountering an issue with react-dom that needs to be resolved

After updating my node and npm installations, I encountered an error when trying to run my project. Specifically, I am using "react": "^0.13.3" and "react-dom": "0.14.0-beta3" npm WARN unmet dependency /Users/hilarl/Desktop/client/node_modules/react-do ...

Enable automatic full-screen mode on Google Chrome upon page load

I would greatly appreciate it if you could provide an answer to this question, even if it is marked as a duplicate. I have tried various solutions and sought help, but unfortunately, nothing seems to be working for me... What I really need is for the brow ...

Ways to retrieve a JSON value with JavaScript

Take a look at this JSON document: [ { "title":"Potato and Cheese Frittata", "href":"http://allrecipes.com/Recipe/Potato-and-Cheese-Frittata/Detail.aspx", "ingredients":"cheddar cheese, eggs, olive oil, onions, ...

Following the recent update of Google Chrome, Sencha Touch experiences spinning issues

Since updating my Google Chrome to the latest version (v29.0.1547.57 m), I've noticed some issues with parts of my Sencha Touch app spinning. The Sencha Touch version I am using is v2.2.1. For example, when using Ext.Msg.alert, I can see the title bu ...

In strict mode, duplicate data properties are not allowed in object literals when using grunt-connect-proxy

I recently started following a tutorial on AngularJS titled "Hands on Angularjs" by Tutsplus. In the tutorial, the instructor uses the grunt-connect-proxy package to redirect ajax requests to a Rails server running on localhost:3000. However, I believe the ...

Skipping the Typescript function for now

I'm facing an issue where the below function is getting skipped during debugging, regardless of the scenario. I'm at a loss as to why this is happening as nothing is being thrown out of the catch block. Upon debugging, I find myself immediately r ...

Override children component class names with Material UI Tooltip Component

Check out this example In this scenario, there are three visible buttons. The first button lacks a tooltip and changes color based on state and hover. The second button includes a tooltip but encounters issues with the className being overwritten, result ...

styled-components: expand designs and alter type of element

Imagine I have these specific styles: color: black; border: 1px solid white; and now I want to apply them to two different elements: const SomeImg = styled.img` margin: 2em; `; const SomeDiv = styled.div` margin: 3em; `; How can I make sure that b ...

Retrieve a list of items using the GET method when the button is clicked, then display them in an HTML table on

Accessing the GET method to retrieve a list of cars: const express = require('express') const app = express() app.use(express.static('public')) app.get('/cars', (req, res) => { res.status(200).json([{ name : ...

Angular 4: Issue with Radiobutton values vanishing when another Radiobutton is selected

I have 3 radio buttons that are used to sort different data from an API. However, when I press one radio button, the value of the selected button disappears if another radio button is clicked. This issue can be seen in the screenshots here: https://i.sstat ...

The gap separating an array of arrays

Consider the following situation: public class Universe{ public Planet[,] planets { get; set; } } public class Planet { public int planet_number { get; set; } public int x_coordinate { get; set; } public int y_coordinate { get; set ...

What is the best way to display items stored in MongoDB?

I'm encountering an issue while trying to display data from my MongoDB database in a dropdown menu. The error message "listName is not defined" keeps popping up, even though I have already declared it in the app.js file. How can I resolve this problem ...

Node Pagination and Filtering feature malfunctioning

I am currently working on incorporating Pagination and Filtering in the backend functionality. This controller receives input such as Page number and Filtering conditions. Controller:- const getPosts = asyncHandler(async (req, res) => { const { ...

Converting a JSON array into a singular object using Node.js

I am struggling to convert a JSON array into a single object. Here are the details: Array: [{ "item-A": "value-1" }, { "item-B": "value-2" }] Expected Result: { "item-A": "value-1", "item-B": "value-2" } I have attempted various methods but none have yi ...

The parameter cannot be assigned a value of type 'string' as it requires a value that matches the format '`${string}` | `${string}.${string}` | `${string}.${number}`'

I recently updated my react-hook-forms from version 6 to version 7. Following the instructions in the migration guide, I made changes to the register method. However, after making these changes, I encountered the following error: The argument being pass ...