Home Reference Source

src/utils/binary-search.ts

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