find the variance of all values in a map in typescript

To find the variance of all values in a map in TypeScript or JavaScript, you can use the following code snippet:

index.ts
function variance(map: Map<any, number>): number {
  const values = Array.from(map.values());
  const mean = values.reduce((acc, val) => acc + val, 0) / values.length;
  const squareDiffs = values.map(val => Math.pow(val - mean, 2));
  return squareDiffs.reduce((acc, val) => acc + val, 0) / values.length;
}
309 chars
7 lines

This function takes a Map object as its parameter, extracts all the values from the map, and calculates the variance using the formula:

index.ts
variance = sum((x - mean)^2) / n
33 chars
2 lines

where x is each value in the map, mean is the mean of all values, and n is the total number of values.

The function returns the variance as a number. You can call this function by passing in your map object as shown in the example below:

index.ts
const myMap = new Map<string, number>();
myMap.set("a", 10);
myMap.set("b", 20);
myMap.set("c", 30);

const myVariance = variance(myMap);
console.log(myVariance); // Output: 66.66666666666667
192 chars
8 lines

In this example, the variance of the three values in the myMap object is calculated and stored in myVariance. The output of console.log(myVariance); statement is 66.66666666666667.

gistlibby LogSnag