diff --git a/src/main/statistics.ts b/src/main/statistics.ts index 662b314..e6562dc 100644 --- a/src/main/statistics.ts +++ b/src/main/statistics.ts @@ -13,6 +13,20 @@ export const getArithmeticMean = (data: number[], decimalPlaces = Infinity) : nu return setDecimalPlaces(sum / data.length, decimalPlaces); }; +/** + * Frequency map: number ---> it's frequency + */ +export const getArithmeticMeanFromFrequency = (frequencyMap: Map, decimalPlaces = Infinity) => { + + let mean = 0; + + for(const [val, frequency] of frequencyMap) { + mean += val * frequency; + } + + return setDecimalPlaces(mean, decimalPlaces); +}; + /** * Central tendency: What is the central number in the sorted array? * Good for lists like [3, 3, 3, 3, 3, 3, 100] - 100 here is called "Outlier" diff --git a/test/statistics.test.ts b/test/statistics.test.ts index 6f11c86..89c94ae 100644 --- a/test/statistics.test.ts +++ b/test/statistics.test.ts @@ -4,7 +4,8 @@ import { getMode, getVariance, getVariance1, - getStandardDeviation + getStandardDeviation, + getArithmeticMeanFromFrequency, } from '../src/main/statistics'; describe('Statistics', () => { @@ -34,6 +35,18 @@ describe('Statistics', () => { }); }); + describe('getArithmeticMeanFromFrequency()', () => { + + test('map 1', () => { + const map = new Map(); + map.set(3, 0.6); // 60% of number 3 + map.set(4, 0.2); // 20% of number 4 + map.set(5, 0.2); // 20% of number 5 + + expect(getArithmeticMeanFromFrequency(map, 2)).toStrictEqual(3.6); + }); + }); + describe('getMedian()', () => { test('[]', () => {