Skip to content

Instantly share code, notes, and snippets.

@ariesmcrae
Last active August 29, 2023 13:24
Show Gist options
  • Save ariesmcrae/96ef9b6fe52f1db28b4950c807a008f9 to your computer and use it in GitHub Desktop.
Save ariesmcrae/96ef9b6fe52f1db28b4950c807a008f9 to your computer and use it in GitHub Desktop.
Typescript: How to use Map(k, v) collection to store unique key/value pairs and perform fast key lookup

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

interface Person {
  name: string;
  age: number;
}

const myMap = new Map<string, Person>();

function insertUniqueKey(key: string, value: Person): void {
  // Check if the key already exists
  if (!myMap.has(key)) {
    // Insert the key-value pair
    myMap.set(key, value);
    console.log(`Inserted: ${key} -> ${JSON.stringify(value)}`);
  } else {
    console.log(`Key ${key} already exists.`);
  }
}

const person1: Person = { name: "Alice", age: 30 };
const person2: 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

function lookupKey(key: string): Person | undefined {
  const value = myMap.get(key);
  if (value !== undefined) {
    console.log(`Found: ${key} -> ${JSON.stringify(value)}`);
    return value;
  } else {
    console.log(`Key ${key} not found.`);
    return undefined;
  }
}

// Look up keys
const value1 = lookupKey("key1"); // Should return the value associated with "key1"
const value2 = lookupKey("key3"); // Should return undefined as "key3" does not exist
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment