Skip to content

Commit

Permalink
feat: implement new median function
Browse files Browse the repository at this point in the history
  • Loading branch information
matejchalk committed Jun 17, 2024
1 parent 52a0f31 commit e3a712b
Showing 1 changed file with 12 additions and 0 deletions.
12 changes: 12 additions & 0 deletions src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down

0 comments on commit e3a712b

Please sign in to comment.