This repository has been archived by the owner on Dec 15, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Get the median from a list of numbers
- Loading branch information
Showing
3 changed files
with
54 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); | ||
}); | ||
}); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 }; |