Skip to content

Commit

Permalink
Create median.ts
Browse files Browse the repository at this point in the history
  • Loading branch information
Mqxx committed Nov 6, 2023
1 parent fad4835 commit 10d8234
Showing 1 changed file with 32 additions and 0 deletions.
32 changes: 32 additions & 0 deletions src/math/median.ts
Original file line number Diff line number Diff line change
@@ -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
}

0 comments on commit 10d8234

Please sign in to comment.