|
| 1 | +import { describe, it, expect } from 'vitest' |
| 2 | +import { binarySearch } from '../../../src/algorithms/searching/binarySearch' |
| 3 | + |
| 4 | +describe('binarySearch', () => { |
| 5 | + describe('when array is empty', () => { |
| 6 | + it('should return null', () => { |
| 7 | + expect(binarySearch([], 1)).toBeNull() |
| 8 | + }) |
| 9 | + }) |
| 10 | + |
| 11 | + describe('when the array has even number of elements', () => { |
| 12 | + describe('and target is in the list', () => { |
| 13 | + const vectors = Array.from({ length: 10 }, (_, index) => ({ |
| 14 | + array: Array.from({ length: 10 }, (_, index) => index + 1), |
| 15 | + target: index + 1, |
| 16 | + expected: { index, element: index + 1 } |
| 17 | + })) |
| 18 | + |
| 19 | + it('should return the target with its index', () => { |
| 20 | + vectors.forEach(({ array, target, expected }) => { |
| 21 | + expect(binarySearch(array, target)).toStrictEqual(expected) |
| 22 | + }) |
| 23 | + }) |
| 24 | + }) |
| 25 | + |
| 26 | + describe('and target is not in the list', () => { |
| 27 | + const vectors = Array.from({ length: 10 }, (_, index) => ({ |
| 28 | + array: Array.from({ length: 10 }, (_, index) => index + 1), |
| 29 | + target: 100 |
| 30 | + })) |
| 31 | + |
| 32 | + it('should return null', () => { |
| 33 | + vectors.forEach(({ array, target }) => { |
| 34 | + expect(binarySearch(array, target)).toBeNull() |
| 35 | + }) |
| 36 | + }) |
| 37 | + }) |
| 38 | + }) |
| 39 | + |
| 40 | + describe('when the array has odd number of elements', () => { |
| 41 | + describe('and target is in the list', () => { |
| 42 | + const vectors = Array.from({ length: 11 }, (_, index) => ({ |
| 43 | + array: Array.from({ length: 11 }, (_, index) => index + 1), |
| 44 | + target: index + 1, |
| 45 | + expected: { index, element: index + 1 } |
| 46 | + })) |
| 47 | + |
| 48 | + it('should return the target with its index', () => { |
| 49 | + vectors.forEach(({ array, target, expected }) => { |
| 50 | + expect(binarySearch(array, target)).toStrictEqual(expected) |
| 51 | + }) |
| 52 | + }) |
| 53 | + }) |
| 54 | + |
| 55 | + describe('and target is not in the list', () => { |
| 56 | + const vectors = Array.from({ length: 11 }, (_, index) => ({ |
| 57 | + array: Array.from({ length: 11 }, (_, index) => index + 1), |
| 58 | + target: 100 |
| 59 | + })) |
| 60 | + |
| 61 | + it('should return null', () => { |
| 62 | + vectors.forEach(({ array, target }) => { |
| 63 | + expect(binarySearch(array, target)).toBeNull() |
| 64 | + }) |
| 65 | + }) |
| 66 | + }) |
| 67 | + }) |
| 68 | +}) |
0 commit comments