find the mode of all values in a map in typescript

To find the mode of all values in a Map in TypeScript, you can use the following algorithm:

  1. Create a new Map to keep track of the frequency of each value
  2. Loop through all the values in the input Map
  3. For each value, check if it exists in the frequency Map
  4. If it exists, increment its frequency by 1
  5. If it doesn't exist, add it to the frequency Map with a frequency of 1
  6. Loop through the frequency Map to find the value with the highest frequency
  7. Return the value with the highest frequency as the mode

Here's the TypeScript code to implement this algorithm:

index.ts
function findMode(inputMap: Map<any, any>): any {
  let frequencyMap = new Map();
  let maxFrequency = 0;
  let mode;

  for (let val of inputMap.values()) {
    let frequency = frequencyMap.get(val) || 0;
    frequencyMap.set(val, frequency + 1);
  }

  for (let [key, value] of frequencyMap) {
    if (value > maxFrequency) {
      maxFrequency = value;
      mode = key;
    }
  }

  return mode;
}
402 chars
20 lines

You can use this function like this:

index.ts
let myMap = new Map<string, number>();
myMap.set("a", 1);
myMap.set("b", 2);
myMap.set("c", 2);
myMap.set("d", 3);

let mode = findMode(myMap); // Returns 2
157 chars
8 lines

gistlibby LogSnag