From e3a712b79e0bbad4f903825c3f012b33b03c1934 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mat=C4=9Bj=20Chalk?= Date: Mon, 17 Jun 2024 14:29:09 +0200 Subject: [PATCH 1/2] feat: implement new median function --- src/index.js | 12 ++++++++++++ 1 file changed, 12 insertions(+) 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. From 3d79a7f9917e01ee230d8f8956b4bcd8c0e4bf2a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mat=C4=9Bj=20Chalk?= Date: Mon, 17 Jun 2024 14:29:29 +0200 Subject: [PATCH 2/2] test: unit test new median function --- test/index.test.js | 12 +++++++++++- 1 file changed, 11 insertions(+), 1 deletion(-) 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]);