Tips for defining a distinct series of key-value pairs in typescript

Having experience with a different language where this was simple, I am finding it challenging to articulate a sequence of pairs:

  • Each pair is made up of two basic elements (such as strings or numbers)
  • Each element may appear multiple times within the list, but the combination must be unique:
a, k
a, m
b, m
b, n

The 2 key features I require are:

  • The ability to add a pair and ensure that if it already exists, it will not be duplicated (for example, attempting to add a, k to the current list would not result in a duplicate entry)
  • I should also be able to verify whether a specific pair exists in the list. For instance, checking for b, n should return true, while checking for b, p should return false.

What would be the most appropriate implementation in typescript?

Initially, my thought was to use Set<[string, string]>:

const a = new Set<[string, string]>();
a.add(['a', 'k']);
a.add(['a', 'm']);
a.add(['b', 'm']);
a.add(['b', 'n']);
...

However, the challenge arises when comparing objects, causing a.has(['a', 'b']) to return false. Are there any other alternatives worth considering?

Answer №1

When using JS Set, element equality is checked using Object.is. This means that for arrays, the comparison is based on whether it is the same instance or the array itself.

To learn more about Set, visit MDN's page on Set

For information on equality comparisons and sameness in JavaScript, check out this link

If you're considering a different approach, you could create a class to store your arrays in stringified form:

class ArraySet<T extends any[]>  {
    values = new Set<string>();
    add: (arr: T) => this = (arr) => {
        this.values.add(JSON.stringify(arr));
        return this;
    }

    has: (arr: T) => boolean = (arr) => {
        return this.values.has(JSON.stringify(arr));
    }
}

const a = new ArraySet<[string, string]>();
a.add(['a', 'k']);
a.add(['a', 'm']);
a.add(['b', 'm']);
a.add(['b', 'n']);

console.log(a.has(['a', 'k']))

Further reading: Learn about storing arrays in ES6 Set and accessing them by value on Stack Overflow

Answer №2

Have you considered developing your own custom solution for this task?

type Element = string | number
type ElementPair<T extends Element> = [T, T]

class ElementPairHolder<T extends Element> {
  private data: Map<Element, Set<Element>>;

  public constructor() {
    this.data = new Map();
  }

  public add(pair: ElementPair<T>): void {
    const [key, value] = pair;
    const set = this.data.get(key) ?? new Set();

    set.add(value);
    this.data.set(key, set);
  }

  public has(pair: ElementPair<T>): boolean {
    const [key, value] = pair;
    return this.data.get(key)?.has(value) ?? false;
  }
}

Here's an example of how you can use it:

const holder = new ElementPairHolder<string>();
holder.add(['a', 'k']);
holder.add(['a', 'm']);
holder.add(['b', 'm']);
holder.add(['b', 'n']);

console.log(holder.has(['b', 'n'])); // true
console.log(holder.has(['b', 'p'])); // false

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

Unable to update due to outdated response call causing issues

I am currently in the process of updating outdated response calls and have encountered a peculiar issue where the response is not being properly ended. Typically, I would use : res.send(200, {message: 'Location Updated'}); However, this method ...

No input value provided

I can't figure out what's going wrong. In other js files, this code works fine. Here is my HTML code: <table class='table'> <tr> <th>Event</th><td><input class='for ...

Is the button failing to direct you to the intended destination?

I'm facing an issue with a button tied to a JavaScript function using onClick(); My interface allows me to ban players on a game server, but when I select anyone here: https://i.stack.imgur.com/kcE1t.png, it always selects wartog for some reason. In ...

React-Bootstrap Popup encounters overlay failure

While using the Tooltip without an OverlayTrigger, I encountered the following error: webpack-internal:///133:33 Warning: Failed prop type: The prop overlay is marked as required in Tooltip, but its value is undefined. The code snippet causing the issu ...

How to store angular 2 table information generated using ngFor

I am currently working on a project where I need to create an editable table using data retrieved from the back end. My goal now is to save any updated data. I attempted to use formControl, but it seems to only save the data in the last column. Below is a ...

I have an HTML table with multiple cells containing inner HTML tables. I have implemented a function along with buttons to filter the main table, excluding the inner tables

My HTML Table is generated from my database, containing information about machines and their status pulled from emails with HTML Tables. Each row has a click option to open/hide the <td> tag showing the original table for more details and better trac ...

Tips for using a JavaScript variable in a PHP file on WordPress

As a newcomer to Wordpress, I am trying to navigate the Theme Editor. Within it, I found a javascript file that looks like this: const isMenuOpen = false; function toggleMenu() { alert("toggle"); isMobileMenuOpen = !isMobileMenuOpen; } ...

The type definition file for '@wdio/globals/types' is nowhere to be found

I'm currently utilizing the webdriverio mocha framework with typescript. @wdio/cli": "^7.25.0" NodeJs v16.13.2 NPM V8.1.2 Encountering the following error in tsconfig.json JSON schema for the TypeScript compiler's configuration fi ...

Retrieve the data of elements that have been clicked using jQuery

I am struggling with a particular issue and would appreciate some assistance. Recently, I've been working on developing buttons that, when clicked, add data to a form for submission. An example of the code structure is as follows: <div> < ...

Design a custom Bootstrap dropdown using an input[type="text"] element

After exploring the Bootstrap dropdown example here, I realized that for my particular scenario, it would be more beneficial to have an input field (type="text") instead of a button. This way, I can display the selected option from the dropdown. Is there ...

Utilizing a Web Interface for Remote Monitoring of Windows Servers

I am in need of creating a webpage that will indicate whether a server is currently operational or not. These servers are all Windows based, with some running on 2008 and others on 2003. They are spread across different networks within various client locat ...

Addressing the issue of prolonged Electron initialization

Scenario After spending considerable time experimenting with Electron, I have noticed a consistent delay of over 2.5 seconds when rendering a simple html file on the screen. The timeline of events unfolds like this: 60 ms: app ready event is triggered; a ...

What is the best way to set a JSON string as a variable?

I am attempting to send form input data to a REST service. Currently, the format is as follows: { "locationname":"test", "locationtype":"test", "address":"test" } However, the service is only accepting the following format: { "value": "{ loca ...

The Jquery code encountered an issue where it was unable to access the property 'length' of an undefined

My goal is to submit a form using jQuery and AJAX, which includes file upload functionality. The challenge I'm facing is that the forms are dynamically created, so I need to identify which form was clicked and retrieve its input values. $(document).r ...

The JavaScript date picker is malfunctioning in the HTML editor, but it functions properly in Fiddle

I have a working format available in a JS fiddle. Here is the code I have used on my demo site: I created a new folder named "js" and placed datepicker.js inside it, then linked it in my HTML like this: <script type="text/javascript" src="js/datepicke ...

NPM encountered difficulties in resolving the dependency tree

I seem to be encountering a persistent issue that I cannot resolve on my own. My attempt to update webpack and webpack-cli in a project has been met with repeated errors of this nature: npm install webpack@latest --save-dev npm ERR! code ERESOLVE npm E ...

The mongoose.populate() method is failing to display the populated content

// defining user schema const mongoose = require('mongoose'); const {ChatRoom} = require('./chatRoom'); const userSchema = new mongoose.Schema({ _id: mongoose.Schema.Types.ObjectId, username:{ type: 'String', unique ...

Error message: Unable to access .exe file through HTML link

We have a need to include an HTML link on our intranet site that, when clicked, will open an .exe file that is already installed on all user machines. I attempted the following code: <a href = "C:\Program Files\Cisco Systems\VPN&bsol ...

The functionality of getAttribute has changed in Firefox 3.5 and IE8, no longer behaving as it did before

Creating a JavaScript function to locate an anchor in a page (specifically with, not an id) and then going through its parent elements until finding one that contains a specified class. The code below works perfectly in Firefox 3.0 but encounters issues wi ...

Automatically Assigning a Default Value to a Column Using SEQUELIZE ORM

When fetching data from a database using Sequelize ORM, I need to set a default value. Here is an example of the SQL query: SELECT a.affiliate_id, a.active AS current_state, IF(MAX(cn.contract_id) IS NULL ,0, IF(DATEDIFF(NOW(),MAX(cn.contract_date) ...