Skip to content

Commit 0a60058

Browse files
feat: add harmonic mean algorithm
1 parent 5c39e87 commit 0a60058

2 files changed

Lines changed: 73 additions & 0 deletions

File tree

‎Maths/HarmonicMean.js‎

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
/**
2+
* @function harmonicMean
3+
* @description Calculates the harmonic mean of an array of positive numbers.
4+
* The harmonic mean is the reciprocal of the arithmetic mean of reciprocals.
5+
* Formula: n / (1/x1 + 1/x2 + ... + 1/xn)
6+
* @param {number[]} arr - An array of positive numbers
7+
* @returns {number} - The harmonic mean
8+
* @see https://en.wikipedia.org/wiki/Harmonic_mean
9+
* @example harmonicMean([1, 2, 4]) => 1.714
10+
* @example harmonicMean([2, 2, 2]) => 2
11+
* @example harmonicMean([1, 4]) => 1.6
12+
*/
13+
const harmonicMean = (arr) => {
14+
if (!Array.isArray(arr) || arr.length === 0) {
15+
throw new TypeError('Input must be a non-empty array')
16+
}
17+
if (!arr.every((n) => typeof n === 'number' && !isNaN(n) && n > 0)) {
18+
throw new TypeError('All elements must be positive numbers')
19+
}
20+
const sumOfReciprocals = arr.reduce((sum, n) => sum + 1 / n, 0)
21+
return arr.length / sumOfReciprocals
22+
}
23+
24+
export { harmonicMean }

‎Maths/test/HarmonicMean.test.js‎

Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
1+
import { harmonicMean } from '../HarmonicMean.js'
2+
3+
describe('harmonicMean', () => {
4+
test('harmonicMean([2, 2, 2]) returns 2', () => {
5+
expect(harmonicMean([2, 2, 2])).toBeCloseTo(2)
6+
})
7+
8+
test('harmonicMean([1, 4]) returns 1.6', () => {
9+
expect(harmonicMean([1, 4])).toBeCloseTo(1.6)
10+
})
11+
12+
test('harmonicMean([1, 2, 4]) returns ~1.714', () => {
13+
expect(harmonicMean([1, 2, 4])).toBeCloseTo(1.714, 2)
14+
})
15+
16+
test('harmonicMean single element returns that element', () => {
17+
expect(harmonicMean([5])).toBeCloseTo(5)
18+
})
19+
20+
test('harmonicMean([1, 1, 1]) returns 1', () => {
21+
expect(harmonicMean([1, 1, 1])).toBeCloseTo(1)
22+
})
23+
24+
test('harmonicMean([2, 4, 8]) returns ~3.428', () => {
25+
expect(harmonicMean([2, 4, 8])).toBeCloseTo(3.428, 2)
26+
})
27+
28+
test('harmonicMean does not mutate original array', () => {
29+
const arr = [1, 2, 4]
30+
harmonicMean(arr)
31+
expect(arr).toEqual([1, 2, 4])
32+
})
33+
34+
test('throws TypeError for empty array', () => {
35+
expect(() => harmonicMean([])).toThrow(TypeError)
36+
})
37+
38+
test('throws TypeError for non-array input', () => {
39+
expect(() => harmonicMean('123')).toThrow(TypeError)
40+
})
41+
42+
test('throws TypeError for zero values', () => {
43+
expect(() => harmonicMean([1, 0, 3])).toThrow(TypeError)
44+
})
45+
46+
test('throws TypeError for negative values', () => {
47+
expect(() => harmonicMean([1, -2, 3])).toThrow(TypeError)
48+
})
49+
})

0 commit comments

Comments
 (0)