No special treatment is needed for primitives in this scenario. Simply pass the identity function for getProperty
: i => i
.
I am sufficiently interested in your goal to devise a universal solution on my own, complete with examples using 1) an array of numbers and 2) an array of objects with a date property:
const binarySearch = <T, U>(
arr: T[],
getProperty:(item:T) => U,
searchedValue: U,
subArrayHeadIndex = 0, //for internal use w/recursion
): number | undefined => {
const midPoint = Math.floor(arr.length / 2);
const item = arr[midPoint];
const propVal: U = getProperty(item);
if(propVal === searchedValue){
return subArrayHeadIndex + arr.indexOf(item);
}
const newStart = propVal > searchedValue ? 0 : midPoint + 1;
const newEnd = propVal > searchedValue ? midPoint : arr.length;
if (newStart === newEnd){
console.log("couldn't find it")
return -1
}
const newSubArrayHeadIndex = subArrayHeadIndex + (propVal > searchedValue ? 0: midPoint + 1);
return binarySearch(arr.slice(newStart, newEnd), getProperty, searchedValue, newSubArrayHeadIndex);
}
- Primitives case -- Determine the position of 29 in the following array:
const numbers = [2, 3, 6, 11, 13, 29, 35, 65, 89, 143, 144, 190, 2001];
console.log(binarySearch(numbers, i => i, 29));
// outputs "5"
- Object case -- Discover the location of the item dated August 21, 1995 from the array:
const things = [
{ id: 1, date: 'January 17, 1995 03:24:00'},
{ id: 2, date: 'December 25, 1995 11:24:00'},
{ id: 3, date: 'January 27, 1995 05:43:00'},
{ id: 4, date: 'March 1, 1995 09:44:00'},
{ id: 5, date: 'April 10, 1995 13:20:00'},
{ id: 6, date: 'May 2, 1995 07:16:00'},
{ id: 7, date: 'May 24, 1995 15:55:00'},
{ id: 8, date: 'August 17, 1995 21:33:00'},
{ id: 9, date: 'August 21, 1995 21:49:00'},
{ id: 10, date: 'December 17, 1995 19:57:00'},
];
const getDayString = (dateStr: string) => {
const date = new Date(dateStr)
//using Korean here for convenient comparison -- the KR format is "yyyy. mm. dd."
const d= date.toLocaleDateString("ko-KR", {
year: "numeric",
month: "2-digit",
day: "2-digit"
});
return d;
}
console.log(binarySearch(things, i => getDayString(i.date), "1995. 08. 21."))
// outputs "8"