diff --git a/src/index.js b/src/index.js index d2f047e..b65c30f 100644 --- a/src/index.js +++ b/src/index.js @@ -15,6 +15,18 @@ export function sum(values) { export function average(values) { return sum(values) / values.length; } +/** + * Calculated median average of all numbers in array. + * @param {number[]} values Numbers to average. + * @returns {number} Median of all numbers. + */ +export function median(values) { + const sorted = sort(values, 'asc'); + if (sorted.length % 2 === 0) { + return average([sorted[sorted.length / 2 - 1], sorted[sorted.length / 2]]); + } + return sorted[Math.floor(sorted.length / 2)]; +} /** * Sort array by numeric values. diff --git a/test/index.test.js b/test/index.test.js index 3eea261..33cc280 100644 --- a/test/index.test.js +++ b/test/index.test.js @@ -1,6 +1,6 @@ import assert from 'node:assert'; import { describe, it } from 'node:test'; -import { average, sort, sum } from '../src/index.js'; +import { average, median, sort, sum } from '../src/index.js'; describe('sum', () => { it('should sum all numbers', () => { @@ -18,6 +18,16 @@ describe('average', () => { }); }); +describe('median', () => { + it('should calculate median for odd-length array', () => { + assert.strictEqual(median([3, 1, 2]), 2); + }); + + it('should calculate median for even-length array', () => { + assert.strictEqual(median([3, 4, 1, 2]), 2.5); + }); +}); + describe('sort', () => { it('should sort numbers in ascending order by default', () => { assert.deepEqual(sort([4, 2, 1, 3]), [1, 2, 3, 4]);