find the median of all values in a map in typescript

To find the median of all values in a Map in TypeScript, we can follow these steps:

  1. Extract all the values from the Map using the Map.prototype.values() method.
  2. Convert the values into an array using the Array.from() method.
  3. Sort the array in ascending order using the Array.prototype.sort() method.
  4. Calculate the median of the array using the following steps:
    1. Get the length of the array using the Array.prototype.length property.
    2. If the length is even, calculate the average of the middle two values in the array.
    3. If the length is odd, return the middle value from the array.

Here's the TypeScript code to find the median of all values in a Map:

index.ts
function findMapValuesMedian(map: Map<any, any>): number | undefined {
  const valuesArray = Array.from(map.values());
  valuesArray.sort((a, b) => a - b);

  const middleIndex = Math.floor(valuesArray.length / 2);

  if (valuesArray.length % 2 === 0) {
    return (valuesArray[middleIndex - 1] + valuesArray[middleIndex]) / 2;
  } else {
    return valuesArray[middleIndex];
  }
}
382 chars
13 lines

This function takes a Map as an argument and returns the median of all its values. If the Map is empty or contains non-numeric values, the function returns undefined.

gistlibby LogSnag