export enum SearchResult { Equal, Greater, Less } export function binarySearch(arr: O[], test: (o: O) => SearchResult): O | undefined { let start = 0; let end = arr.length - 1; // Iterate while start not meets end while (start <= end) { // Find the mid index let mid = Math.floor((start + end)/2); const result = test(arr[mid]); // If element is present at mid, return True if (result === SearchResult.Equal) return arr[mid]; // Else look in left or right half accordingly else if (result === SearchResult.Less) start = mid + 1; else end = mid - 1; } throw new Error("Expected element ") } export function compareFn(...fns: ((a: O, b: O) => number)[]): (a: O, b: O) => number { return (a: O, b: O) => { for (let fn of fns) { const res = fn(a, b); if (res > 0) return 1; if (res < 0) return -1; } return 0; }; } export function compareFnProps>(...props: (keyof O)[]): (a: O, b: O) => number { return compareFn(...props.map((prop) => (a: O, b: O) => b[prop] - a[prop])); }