From 39a8f571cafc60cefa55b42ad0877312db42156a Mon Sep 17 00:00:00 2001 From: Wadah Esam Date: Tue, 29 Aug 2023 01:00:11 +0300 Subject: [PATCH] perf: improve (nearestPoint) calculation by 50%+ --- src/utils.ts | 21 ++++++++++++--------- 1 file changed, 12 insertions(+), 9 deletions(-) diff --git a/src/utils.ts b/src/utils.ts index c2f8f34..79e59c0 100644 --- a/src/utils.ts +++ b/src/utils.ts @@ -116,20 +116,23 @@ export const getIndexOfTheNearestXPoint = ( ) => { 'worklet'; - let closest = array[0]; + if (!array || array.length === 0) return -1; + let closestIndex = 0; - for (let i = 0; i < array.length; i++) { - while ( - closest && - array[i] && - // @ts-ignore - Math.abs(array[i].x - value) < Math.abs(closest.x - value) - ) { - closest = array[i]; + // @ts-ignore + let closestDistance = Math.abs(array[0].x - value); + + for (let i = 1; i < array.length; i++) { + // @ts-ignore + const currentDistance = Math.abs(array[i].x - value); + + if (currentDistance < closestDistance) { + closestDistance = currentDistance; closestIndex = i; } } + return closestIndex; };