-
-
Notifications
You must be signed in to change notification settings - Fork 283
Expand file tree
/
Copy pathmedian.test.js
More file actions
71 lines (64 loc) · 2.33 KB
/
median.test.js
File metadata and controls
71 lines (64 loc) · 2.33 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
// median.test.js
// Someone has implemented calculateMedian but it isn't
// passing all the tests...
// Fix the implementation of calculateMedian so it passes all tests
const calculateMedian = require("./median.js");
describe("calculateMedian", () => {
[
{ input: [1.5, 2.5, 3.5], expected: 2.5 },
{ input: [-2, -4, -6, -10], expected: -5 },
{ input: [3, 3, 3, 3, 3], expected: 3 },
{ input: [1, 3], expected: 2 },
{ input: [1], expected: 1 },
{ input: [1, 2, 3], expected: 2 },
{ input: [1, 2, 3, 4, 5], expected: 3 },
{ input: [1, 2, 3, 4], expected: 2.5 },
{ input: [1, 2, 3, 4, 5, 6], expected: 3.5 },
].forEach(({ input, expected }) =>
it(`returns the median for [${input}]`, () =>
expect(calculateMedian(input)).toEqual(expected))
);
[
{ input: [-5, -1, -3], expected: -3 },
{ input: [2, 2, 2, 2], expected: 2 },
{ input: [8, 4], expected: 6 },
{ input: [3, 1, 2], expected: 2 },
{ input: [5, 1, 3, 4, 2], expected: 3 },
{ input: [4, 2, 1, 3], expected: 2.5 },
{ input: [6, 1, 5, 3, 2, 4], expected: 3.5 },
{ input: [110, 20, 0], expected: 20 },
{ input: [6, -2, 2, 12, 14], expected: 6 },
].forEach(({ input, expected }) =>
it(`returns the correct median for unsorted array [${input}]`, () =>
expect(calculateMedian(input)).toEqual(expected))
);
it("doesn't modify the input array [3, 1, 2]", () => {
const list = [3, 1, 2];
calculateMedian(list);
expect(list).toEqual([3, 1, 2]);
});
[
"not an array",
123,
null,
undefined,
{},
[],
["apple", null, undefined],
].forEach((val) =>
it(`returns null for non-numeric array (${val})`, () =>
expect(calculateMedian(val)).toBe(null))
);
[
{ input: ["a", null, 5, undefined], expected: 5 },
{ input: [1, 2, "3", null, undefined, 4], expected: 2 },
{ input: ["apple", 1, 2, 3, "banana", 4], expected: 2.5 },
{ input: [1, "2", 3, "4", 5], expected: 3 },
{ input: [1, "apple", 2, null, 3, undefined, 4], expected: 2.5 },
{ input: [3, "apple", 1, null, 2, undefined, 4], expected: 2.5 },
{ input: ["banana", 5, 3, "apple", 1, 4, 2], expected: 3 },
].forEach(({ input, expected }) =>
it(`filters out non-numeric values and calculates the median for [${input}]`, () =>
expect(calculateMedian(input)).toEqual(expected))
);
});