Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: implement new median function #3

Merged
merged 2 commits into from
Jun 17, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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
12 changes: 11 additions & 1 deletion test/index.test.js
Original file line number Diff line number Diff line change
@@ -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', () => {
Expand All @@ -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]);
Expand Down