From 39e5c3736135f9a49daceee1fe4da9fbdbb96eab Mon Sep 17 00:00:00 2001 From: Karsten Schmidt Date: Thu, 21 Jan 2021 11:26:23 +0000 Subject: [PATCH] fix(arrays): fixed-length binarySearch2/4/8/16/32 - add binarySearch2() - fix results for not-found values, make compatible w/ binarySearch() --- packages/arrays/src/binary-search.ts | 13 +++++++++---- 1 file changed, 9 insertions(+), 4 deletions(-) diff --git a/packages/arrays/src/binary-search.ts b/packages/arrays/src/binary-search.ts index 5ee840af47..bda59bb75d 100644 --- a/packages/arrays/src/binary-search.ts +++ b/packages/arrays/src/binary-search.ts @@ -86,6 +86,11 @@ export const binarySearchNumeric = ( return -low - 1; }; +export const binarySearch2 = (buf: ArrayLike, x: number) => { + let idx = buf[1] <= x ? 1 : 0; + return buf[idx] === x ? idx : buf[0] < x ? -idx - 2 : -1; +}; + /** * Non-recursive, optimized binary search for fixed size numeric arrays of 4 * values. Returns index of `x` or `-index-1` if not found. @@ -96,7 +101,7 @@ export const binarySearchNumeric = ( export const binarySearch4 = (buf: ArrayLike, x: number) => { let idx = buf[2] <= x ? 2 : 0; idx |= buf[idx + 1] <= x ? 1 : 0; - return buf[idx] === x ? idx : -idx - 1; + return buf[idx] === x ? idx : buf[0] < x ? -idx - 2 : -1; }; /** @@ -110,7 +115,7 @@ export const binarySearch8 = (buf: ArrayLike, x: number) => { let idx = buf[4] <= x ? 4 : 0; idx |= buf[idx + 2] <= x ? 2 : 0; idx |= buf[idx + 1] <= x ? 1 : 0; - return buf[idx] === x ? idx : -idx - 1; + return buf[idx] === x ? idx : buf[0] < x ? -idx - 2 : -1; }; /** @@ -125,7 +130,7 @@ export const binarySearch16 = (buf: ArrayLike, x: number) => { idx |= buf[idx + 4] <= x ? 4 : 0; idx |= buf[idx + 2] <= x ? 2 : 0; idx |= buf[idx + 1] <= x ? 1 : 0; - return buf[idx] === x ? idx : -idx - 1; + return buf[idx] === x ? idx : buf[0] < x ? -idx - 2 : -1; }; /** @@ -141,7 +146,7 @@ export const binarySearch32 = (buf: ArrayLike, x: number) => { idx |= buf[idx + 4] <= x ? 4 : 0; idx |= buf[idx + 2] <= x ? 2 : 0; idx |= buf[idx + 1] <= x ? 1 : 0; - return buf[idx] === x ? idx : -idx - 1; + return buf[idx] === x ? idx : buf[0] < x ? -idx - 2 : -1; }; /**