find the standard deviation of all keys in a map in typescript

Assuming you have a map with numeric values, you can find the standard deviation of all keys in the map with the following code:

index.ts
let map = new Map<number, number>(); // initialize your map

let sum = 0;
let sumSquared = 0;
let count = 0;

map.forEach((value, key) => {
  sum += key;
  sumSquared += key * key;
  count += 1;
});

const mean = sum / count;
const variance = (sumSquared / count) - (mean * mean);
const stdDev = Math.sqrt(variance);

console.log(stdDev);
339 chars
18 lines

This code iterates through all the keys in the map, keeping track of the sum of the keys, the sum of the squared keys, and the count of keys. It then calculates the mean, variance, and standard deviation using the formulas:

index.ts
mean = sum / count
variance = (sumSquared / count) - (mean * mean)
stdDev = Math.sqrt(variance)
96 chars
4 lines

Finally, the standard deviation is logged to the console.

gistlibby LogSnag