|
| 1 | +// median.test.js |
| 2 | + |
| 3 | +// Someone has implemented calculateMedian but it isn't |
| 4 | +// passing all the tests... |
| 5 | +// Fix the implementation of calculateMedian so it passes all tests |
| 6 | + |
| 7 | +const calculateMedian = require("./median.js"); |
| 8 | + |
| 9 | +describe("calculateMedian", () => { |
| 10 | + [ |
| 11 | + { input: [1, 2, 3], expected: 2 }, |
| 12 | + { input: [1, 2, 3, 4, 5], expected: 3 }, |
| 13 | + { input: [1, 2, 3, 4], expected: 2.5 }, |
| 14 | + { input: [1, 2, 3, 4, 5, 6], expected: 3.5 }, |
| 15 | + ].forEach(({ input, expected }) => |
| 16 | + it(`returns the median for [${input}]`, () => |
| 17 | + expect(calculateMedian(input)).toEqual(expected)) |
| 18 | + ); |
| 19 | + |
| 20 | + [ |
| 21 | + { input: [3, 1, 2], expected: 2 }, |
| 22 | + { input: [5, 1, 3, 4, 2], expected: 3 }, |
| 23 | + { input: [4, 2, 1, 3], expected: 2.5 }, |
| 24 | + { input: [6, 1, 5, 3, 2, 4], expected: 3.5 }, |
| 25 | + { input: [110, 20, 0], expected: 20 }, |
| 26 | + { input: [6, -2, 2, 12, 14], expected: 6 }, |
| 27 | + ].forEach(({ input, expected }) => |
| 28 | + it(`returns the correct median for unsorted array [${input}]`, () => |
| 29 | + expect(calculateMedian(input)).toEqual(expected)) |
| 30 | + ); |
| 31 | + |
| 32 | + it("doesn't modify the input array [3, 1, 2]", () => { |
| 33 | + const list = [3, 1, 2]; |
| 34 | + calculateMedian(list); |
| 35 | + expect(list).toEqual([3, 1, 2]); |
| 36 | + }); |
| 37 | + |
| 38 | + [ |
| 39 | + "not an array", |
| 40 | + 123, |
| 41 | + null, |
| 42 | + undefined, |
| 43 | + {}, |
| 44 | + [], |
| 45 | + ["apple", null, undefined], |
| 46 | + ].forEach((val) => |
| 47 | + it(`returns null for non-numeric array (${val})`, () => |
| 48 | + expect(calculateMedian(val)).toBe(null)) |
| 49 | + ); |
| 50 | + |
| 51 | + [ |
| 52 | + { input: [1, 2, "3", null, undefined, 4], expected: 2 }, |
| 53 | + { input: ["apple", 1, 2, 3, "banana", 4], expected: 2.5 }, |
| 54 | + { input: [1, "2", 3, "4", 5], expected: 3 }, |
| 55 | + { input: [1, "apple", 2, null, 3, undefined, 4], expected: 2.5 }, |
| 56 | + { input: [3, "apple", 1, null, 2, undefined, 4], expected: 2.5 }, |
| 57 | + { input: ["banana", 5, 3, "apple", 1, 4, 2], expected: 3 }, |
| 58 | + ].forEach(({ input, expected }) => |
| 59 | + it(`filters out non-numeric values and calculates the median for [${input}]`, () => |
| 60 | + expect(calculateMedian(input)).toEqual(expected)) |
| 61 | + ); |
| 62 | +}); |
0 commit comments