Home Reference Source

src/utils/binary-search.ts

  1. type BinarySearchComparison<T> = (candidate: T) => -1 | 0 | 1;
  2.  
  3. const BinarySearch = {
  4. /**
  5. * Searches for an item in an array which matches a certain condition.
  6. * This requires the condition to only match one item in the array,
  7. * and for the array to be ordered.
  8. *
  9. * @param {Array<T>} list The array to search.
  10. * @param {BinarySearchComparison<T>} comparisonFn
  11. * Called and provided a candidate item as the first argument.
  12. * Should return:
  13. * > -1 if the item should be located at a lower index than the provided item.
  14. * > 1 if the item should be located at a higher index than the provided item.
  15. * > 0 if the item is the item you're looking for.
  16. *
  17. * @return {T | null} The object if it is found or null otherwise.
  18. */
  19. search: function <T>(
  20. list: T[],
  21. comparisonFn: BinarySearchComparison<T>
  22. ): T | null {
  23. let minIndex: number = 0;
  24. let maxIndex: number = list.length - 1;
  25. let currentIndex: number | null = null;
  26. let currentElement: T | null = null;
  27.  
  28. while (minIndex <= maxIndex) {
  29. currentIndex = ((minIndex + maxIndex) / 2) | 0;
  30. currentElement = list[currentIndex];
  31.  
  32. const comparisonResult = comparisonFn(currentElement);
  33. if (comparisonResult > 0) {
  34. minIndex = currentIndex + 1;
  35. } else if (comparisonResult < 0) {
  36. maxIndex = currentIndex - 1;
  37. } else {
  38. return currentElement;
  39. }
  40. }
  41.  
  42. return null;
  43. },
  44. };
  45.  
  46. export default BinarySearch;