From 10d823433db344d252cbd78127f75376c72553ac Mon Sep 17 00:00:00 2001 From: Mqxx <62719703+Mqxx@users.noreply.github.com> Date: Mon, 6 Nov 2023 15:50:02 +0100 Subject: [PATCH] Create median.ts --- src/math/median.ts | 32 ++++++++++++++++++++++++++++++++ 1 file changed, 32 insertions(+) create mode 100644 src/math/median.ts diff --git a/src/math/median.ts b/src/math/median.ts new file mode 100644 index 0000000..3a839b5 --- /dev/null +++ b/src/math/median.ts @@ -0,0 +1,32 @@ +/** + * This function calculates the median value of a number array. + * + * @function + * @param array List of numbers + * @returns The median value + */ +export function median(array : number[]) : number { + const sumOfArray = array.reduce( + ( + previousValue, + currentValue + ) => { + return previousValue + currentValue + }, + 0 + ); + + if (sumOfArray === 0) { + return 0; + } + + const isOdd = ((array.length % 2) === 1); + + array.sort((a, b) => a - b); + + if (isOdd) { + return array[(array.length + 1) / 2]; + } + + return (array[(array.length / 2) - 1] + array[array.length / 2]) / 2 +}