find the largest key in a map in typescript

index.ts
// TypeScript function to find the largest key in a Map
function mapMaxKey<K, V>(map: Map<K, V>): K | undefined {
    let maxKey: K | undefined = undefined;
    
    map.forEach((value, key) => {
        if(!maxKey || key > maxKey) {
            maxKey = key;
        }
    });
    
    return maxKey;
}
304 chars
13 lines

Explanation:

  1. We define a generic function mapMaxKey that takes a Map with keys of type K and values of type V, and returns either the largest key or undefined if the map is empty.

  2. We initialize the maxKey variable to undefined.

  3. We use the forEach() method on the map to iterate over its entries.

  4. For each entry, we check if maxKey is undefined or if the current key is greater than maxKey. If either of these conditions is true, we update maxKey to the current key.

  5. After iterating over all the entries, we return maxKey.

gistlibby LogSnag