From c0d5d12ec03fc27875a054ecfe2251bdaeca8073 Mon Sep 17 00:00:00 2001 From: Jackson Harper Date: Mon, 21 Nov 2022 16:11:52 +0800 Subject: [PATCH] Add missing file --- packages/api/src/utils/interpolationSearch.ts | 32 +++++++++++++++++++ 1 file changed, 32 insertions(+) create mode 100644 packages/api/src/utils/interpolationSearch.ts diff --git a/packages/api/src/utils/interpolationSearch.ts b/packages/api/src/utils/interpolationSearch.ts new file mode 100644 index 000000000..a834e16ca --- /dev/null +++ b/packages/api/src/utils/interpolationSearch.ts @@ -0,0 +1,32 @@ +/** + * Finds the index of the element which value is the closest to the target + * @param arr - An array of numbers to search from + * @param target - The target number to find + * @returns The index of the closest to the target value array element + */ + +export function interpolationSearch(arr: number[], target: number): number { + let left = 0 + let right = arr.length - 1 + while (left < right) { + const rangeDelta = arr[right] - arr[left] + const indexDelta = right - left + const valueDelta = target - arr[left] + if (valueDelta < 0) { + throw new Error('Unable to find text node') + } + if (!rangeDelta) { + return left + } + const middleIndex = + left + Math.floor((valueDelta * indexDelta) / rangeDelta) + if (target < arr[middleIndex]) { + right = middleIndex + } else if (target >= arr[middleIndex + 1]) { + left = middleIndex + 1 + } else { + return middleIndex + } + } + throw new Error('Unable to find text node') +}