Skip to content
This repository has been archived by the owner on Dec 15, 2021. It is now read-only.

Commit

Permalink
feat(median): Add module median
Browse files Browse the repository at this point in the history
Get the median from a list of numbers
  • Loading branch information
adambrgmn committed Jan 16, 2018
1 parent dc02100 commit 4718073
Show file tree
Hide file tree
Showing 3 changed files with 54 additions and 0 deletions.
26 changes: 26 additions & 0 deletions src/__tests__/median.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
import median from '../median';

describe('Core.median', () => {
test('returns middle value of an odd-length list', () => {
expect(median([2, 9, 7])).toBe(7);
expect(median([3, 2, 11, 7, 9])).toBe(7);
expect(median([2])).toBe(2);
});

test('returns mean of two middle values of a nonempty even-length list', () => {
expect(median([7, 2])).toBe(4.5);
expect(median([7, 2, 10, 9])).toBe(8);
});

test('returns NaN for an empty list', () => {
expect(median([])).toBe(NaN);
});

test('handles array-like object', () => {
function getArgs() {
return arguments; // eslint-disable-line prefer-rest-params
}

expect(median(getArgs(1, 2, 3))).toBe(2);
});
});
4 changes: 4 additions & 0 deletions src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,8 @@ import keys from './keys';
import last from './last';
import length from './length';
import map from './map';
import mean from './mean';
import median from './median';
import modulo from './modulo';
import multiply from './multiply';
import negate from './negate';
Expand Down Expand Up @@ -84,6 +86,8 @@ export {
last,
length,
map,
mean,
median,
modulo,
multiply,
negate,
Expand Down
24 changes: 24 additions & 0 deletions src/median.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
import length from './length';
import divide from './divide';
import modulo from './modulo';
import nth from './nth';
import slice from './slice';
import mean from './mean';

const median = list => {
const sorted = Array.prototype.sort.call(list, (a, b) => {
if (a > b) return 1;
if (a < b) return -1;
return 0;
});

const l = length(sorted);
const half = divide(l, 2);

if (modulo(l, 2) > 0) return nth(Math.floor(half), sorted);

const sub = slice(half - 1, half + 1, sorted);
return mean(sub);
};

export { median as default };

0 comments on commit 4718073

Please sign in to comment.