You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Typescript: How to use Map(k, v) collection to store unique key/value pairs and perform fast key lookup
Insert a unique key/value pair
interfacePerson{name: string;age: number;}constmyMap=newMap<string,Person>();functioninsertUniqueKey(key: string,value: Person): void{// Check if the key already existsif(!myMap.has(key)){// Insert the key-value pairmyMap.set(key,value);console.log(`Inserted: ${key} -> ${JSON.stringify(value)}`);}else{console.log(`Key ${key} already exists.`);}}constperson1: Person={name: "Alice",age: 30};constperson2: Person={name: "Bob",age: 40};insertUniqueKey("key1",person1);insertUniqueKey("key2",person2);insertUniqueKey("key1",person1);// This will not insert because key1 already exists
Look up a key
functionlookupKey(key: string): Person|undefined{constvalue=myMap.get(key);if(value!==undefined){console.log(`Found: ${key} -> ${JSON.stringify(value)}`);returnvalue;}else{console.log(`Key ${key} not found.`);returnundefined;}}// Look up keysconstvalue1=lookupKey("key1");// Should return the value associated with "key1"constvalue2=lookupKey("key3");// Should return undefined as "key3" does not exist