What are the steps for applying logic based on the types of keys and values in a Map<K,V>?

When it comes to serialization, one must analyze and handle different Map types by determining logic based on the key and value types. But how can this be achieved in Typescript?

For example:

const stringAndNumberPairs: Map<string, number> = new Map<string, number>([['text', 1]]);
const stringAndStringPairs: Map<string, string> = new Map<string, string>([['text', 'more text']]);

The function to accomplish this would resemble:

function serialize(input: any): string {
  let output: string = "";
  if (type of K is number) {
    output += "Key is number"; 
  }

  if (type of V is string) {
    output += "Value is string";
  }
  else if (type of V is number) {
    output += "Value is number";
  }

  return output;
}

Answer №1

typeof (used for base types) or instanceof (used for class instances) are the keywords that would be appropriate in this situation.

class Foo { }


function serialize<K, V extends any>(map: Map<K, V>): string {
    let output: string = "";

    Array.from(map.entries()).forEach(([k, v]) => {
        if (typeof k === 'number') {
            output += "Key is number";
        }

        if (typeof v === 'string') {
            output += "value if string";
        }

        if (v instanceof Foo) {
            output += "value if string";
        }
    });
    return output;
}

Alternatively, a cleaner implementation:

function serialize<K, V extends any>(map: Map<K, V>): string[][] {

  const output = Array.from(map.entries()).map(([k, v]) => {
    return [
      { condition: typeof k === 'number', label: 'Key is number' },
      { condition: typeof v === 'string', label: "value is string" },
      { condition: v instanceof Foo, label: 'value is class Foo' }

    ].filter((c) => c.condition).map((c) => c.label);  // you could join() here

  });
  return output;  // also join() here
}

https://www.typescriptlang.org/play?ssl=16&ssc=2&pln=1&pc=1#code/MYGwhgzhAEBiD29oG9oF8CwAob2BmArgHbAAuAlvEdBAKYBO5YI5AXrQDwDSANNAGrRaAD1K0iAExhgiATwB8ACgC2YAA4AuaAFl13Pv3kBKLRFKMiAcwDaAXTspcWaNGBUz0eAVJrv0ALzQAIL09GCyAHR49PDKKuoR4ubktBCKRkYRqmqKitYA1nwAbrZGAfKOzi7Q9LSkBPTU1tjV1ahukuQUVFqksmq08HjQ+QH+gQDkRATKAEYME3zg8yBaE1y0stDkMNNzC+g8La0orlQSXZREvf2Dw0Vjk2YWlovQy7Sr0ABERcwEtG2MGe5Cs30Ox1a7XOlx60AeoLMMmAdzgiCWYBWaz+IABQNc4CgaPgE3QTlatii5BAYnouWAZX8FWAEQ6F26REy2XpjOZEQ+IDK0AA9MLoLIvK4ZNAAFbwUHpaAACwYtHJ6CMAG5jrV6o1PN5fKQXKLoMwIEg5Qqyiratg0EA

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

There was an error parsing the data from the specified URL (http://localhost:8000/src/client/assets/data.json

Hey there, I'm a newcomer to Angular and I'm having trouble reading a JSON array from a file. Every time I try, it gives me a "failed to parse" error. Can someone please provide some guidance? Here is my folder structure: src --assets ---a ...

Using TypeScript - Implementing a generic constraint to allow passing a Zod schema result as an argument to a function

I'm in the process of creating a custom controller function to streamline my application. The repetitive task of wrapping try-catch, parsing a zod schema, and merging the request zod schema into a single object is present in all handler functions. The ...

Is it recommended to include modules in the Imports section of SharedModule in Angular?

Welcome to my SharedModule! import { CommonModule } from "@angular/common"; import { NgModule } from "@angular/core"; import { FormsModule, ReactiveFormsModule } from "@angular/forms"; import { IconModule } from "@my-app/components/icon/icon.module"; impo ...

I am interested in adding a personalized icon to the progress bar in Material-UI

I am currently using the MUI linerProgressBar design. I would like to incorporate a custom UI Icon that moves along with the progress. Are there any examples of this available? I have searched for one in MUI but haven't found anything. If you know of ...

Missing value: Attempted to access properties of an undefined variable

I've been encountering an issue while trying to transfer data from one component to another using a service. The error message that I keep running into is: ERROR TypeError: Cannot read properties of undefined (reading 'statistics') at St ...

Taking out the modal element from the document object model, causing the animation

I am currently working on a project using Next.js, Typescript, and Tailwind CSS. Within this project, I have implemented a modal component with some animations. However, I encountered an issue where the modal does not get removed from the DOM when closed, ...

Undefined Perception

Trying to obtain values from an observable, my subscription code within the component looks like this: this.checkoutService.getDisabledDate().subscribe (dates=>{this.formattedDate=dates}, (error:any)=>{console.log(error)}); When logging this.forma ...

Tips for sending a variable to control a particular panel within an accordion in Angular 2

I have a collection of ngbpanels that are dynamically created using ngFor. I need to expand or collapse a specific panel based on certain conditions, but the ID I provide for the panel is stored in a variable. The code does not recognize the panel ID when ...

Maintain synchrony of the state with swiftly unfolding occurrences

I developed a custom hook to keep track of a state variable that increments based on the number of socket events received. However, when I tested by sending 10 simultaneous events, the total value of the state variable ended up being 6, 7, or 8 instead of ...

How to locate and remove an object in Angular 6

What is the method to remove an object from a list of objects using an id number in Angular 6 with TypeScript? EntityService.ts import { Injectable } from '@angular/core'; import { Entity } from '../../models/entity'; @Injectable({ ...

Removing redundant names from an array using Typescript

My task involves retrieving a list of names from an API, but there are many duplicates that need to be filtered out. However, when I attempt to execute the removeDuplicateNames function, it simply returns an empty array. const axios = require('axios&a ...

Is there a problem with the transition table in my negamax algorithm implementation?

I'm currently developing a Chess AI in TypeScript that utilizes negamax with alpha-beta pruning to explore potential moves. The AI incorporates two heuristics: 1) the main heuristic, which assesses leaf nodes during the negamax tree traversal, and 2) ...

Best practice in TypeScript for handling an Enum with a switch-case to assign a variable

Here's an issue I'm facing: I have a variable called Difficulty that is an Enum. Within a function, I need to set the configuration DifficultyConfig based on the value of Difficulty. The current solution I have in mind seems overly complicated: ...

Encountering an issue with the tieredMenu component in PrimeNG version 9

Currently utilizing Angular along with primeng version 9. I am aiming to incorporate hover functionality on tiredMenu. Within the primeNg library, I find that initially, I need to click in order to then hover over the menu to view the submenu. How can th ...

Updating select options list dynamically in Angular

In a modal, I have two selects that are populated with data from two different object arrays: <select class="browser-default" id="gebied" [(ngModel)]="filteredGebied" (ngModelChange)="onChange($event)"> <option *ngFor="let gebied of lis ...

I'm curious about the type I can set for the first parameter of setState in TypeScript. Is there a way to pass a dynamically generated state object to setState?

When trying to pass a newState object to setState and add some additional properties under certain conditions, I encountered a type error: I attempted to define the new State as Pick<ItemListState, keyof ItemListState> but received a type error ...

Steps to ensure that the autocomplete is reset to its default settings every time the page is

I am experiencing an issue with the accountInfo property where the targetValue does not reset to default as expected. I have tried using useEffect to solve this problem, but it's not working. Any suggestions on how I can achieve this? Whenever the ac ...

What is the best way to declare this massive entity in typescript?

In the process of parsing a file, a large object is returned by the main function. function parse(file){ /* dostuff.. */ return myObject } The order of determining properties is crucial (e.g., "a" must be determined before "b" or the value will be differe ...

typescript - instantiate an object using values stored in an array

Assume we have a model defined as follows. export interface Basicdata { materialnumber: number; type: string; materialclass: string; } We also have an array containing values that correspond directly to the Basicdata model in order, like this: ...

Executing the setDeleted loop causes changes to the entities which are then reflected in the saveChanges

My goal is to delete a hierarchy of objects: Customer->Orders->OrderItems->OrderItemOptions I attempted to set up a nested loop to perform the operations in the correct order - deleting child records before deleting parent records as required by ...