|
| 1 | +import { describe, it, type TestContext } from 'node:test'; |
| 2 | +import { binarySearch } from '../src/binary-search/binary-search'; |
| 3 | + |
| 4 | +describe('binarysearch', () => { |
| 5 | + const arr = [1, 2, 2, 2, 3, 5, 9]; |
| 6 | + const cmp = (a: number, b: number) => a - b; |
| 7 | + |
| 8 | + it('should bail if not passed an array', (t: TestContext) => { |
| 9 | + // @ts-expect-error |
| 10 | + t.assert.throws(() => { binarySearch(undefined, 3, cmp); }, TypeError); |
| 11 | + }); |
| 12 | + |
| 13 | + it('should bail if not passed a comparator', (t: TestContext) => { |
| 14 | + // @ts-expect-error |
| 15 | + t.assert.throws(() => { binarySearch(arr, 3, undefined); }, TypeError); |
| 16 | + }); |
| 17 | + |
| 18 | + it('should return the index of an item in a sorted array', (t: TestContext) => { |
| 19 | + t.assert.strictEqual(binarySearch(arr, 3, cmp), 4); |
| 20 | + }); |
| 21 | + |
| 22 | + it('should return the index of where the item would go plus one, negated, if the item is not found', |
| 23 | + (t: TestContext) => { |
| 24 | + t.assert.strictEqual(binarySearch(arr, 4, cmp), -6); |
| 25 | + }); |
| 26 | + |
| 27 | + it('should return any valid index if an item exists multiple times in the array', |
| 28 | + (t: TestContext) => { |
| 29 | + t.assert.strictEqual(binarySearch(arr, 2, cmp), 3); |
| 30 | + }); |
| 31 | + |
| 32 | + it('should work even on empty arrays', (t: TestContext) => { |
| 33 | + t.assert.strictEqual(binarySearch([], 42, cmp), -1); |
| 34 | + }); |
| 35 | + |
| 36 | + it('should work even on arrays of doubles', (t: TestContext) => { |
| 37 | + t.assert.strictEqual(binarySearch([0.0, 0.1, 0.2, 0.3, 0.4], 0.25, cmp), -4); |
| 38 | + }); |
| 39 | + |
| 40 | + it('should pass the index and array parameters to the comparator', (t: TestContext) => { |
| 41 | + const indexes: number[] = []; |
| 42 | + const indexCmp = (a: number, b: number, i?: number, array?: ArrayLike<number>) => { |
| 43 | + t.assert.strictEqual(array, arr); |
| 44 | + indexes.push(i!); |
| 45 | + return cmp(a, b); |
| 46 | + }; |
| 47 | + binarySearch(arr, 3, indexCmp); |
| 48 | + t.assert.deepStrictEqual(indexes, [3, 5, 4]); |
| 49 | + }); |
| 50 | +}); |
0 commit comments