UNPKG

@tanstack/db

Version:

A reactive client store for building super fast apps on sync

1 lines 2.83 kB
{"version":3,"file":"array-utils.cjs","sources":["../../../src/utils/array-utils.ts"],"sourcesContent":["/**\n * Finds the correct insert position for a value in a sorted array using binary search\n * @param sortedArray The sorted array to search in\n * @param value The value to find the position for\n * @param compareFn Comparison function to use for ordering\n * @returns The index where the value should be inserted to maintain order\n */\nexport function findInsertPositionInArray<T>(\n sortedArray: Array<T>,\n value: T,\n compareFn: (a: T, b: T) => number,\n): number {\n let left = 0\n let right = sortedArray.length\n\n while (left < right) {\n const mid = Math.floor((left + right) / 2)\n const comparison = compareFn(sortedArray[mid]!, value)\n\n if (comparison < 0) {\n left = mid + 1\n } else {\n right = mid\n }\n }\n\n return left\n}\n\n/**\n * Finds the correct insert position for a value in a sorted tuple array using binary search\n * @param sortedArray The sorted tuple array to search in\n * @param value The value to find the position for\n * @param compareFn Comparison function to use for ordering\n * @returns The index where the value should be inserted to maintain order\n */\nexport function findInsertPosition<T>(\n sortedArray: Array<[T, any]>,\n value: T,\n compareFn: (a: T, b: T) => number,\n): number {\n let left = 0\n let right = sortedArray.length\n\n while (left < right) {\n const mid = Math.floor((left + right) / 2)\n const comparison = compareFn(sortedArray[mid]![0], value)\n\n if (comparison < 0) {\n left = mid + 1\n } else {\n right = mid\n }\n }\n\n return left\n}\n\n/**\n * Deletes a value from a sorted array while maintaining sort order\n * @param sortedArray The sorted array to delete from\n * @param value The value to delete\n * @param compareFn Comparison function to use for ordering\n * @returns True if the value was found and deleted, false otherwise\n */\nexport function deleteInSortedArray<T>(\n sortedArray: Array<T>,\n value: T,\n compareFn: (a: T, b: T) => number,\n): boolean {\n const idx = findInsertPositionInArray(sortedArray, value, compareFn)\n if (idx < sortedArray.length && compareFn(sortedArray[idx]!, value) === 0) {\n sortedArray.splice(idx, 1)\n return true\n }\n return false\n}\n"],"names":[],"mappings":";;AAOO,SAAS,0BACd,aACA,OACA,WACQ;AACR,MAAI,OAAO;AACX,MAAI,QAAQ,YAAY;AAExB,SAAO,OAAO,OAAO;AACnB,UAAM,MAAM,KAAK,OAAO,OAAO,SAAS,CAAC;AACzC,UAAM,aAAa,UAAU,YAAY,GAAG,GAAI,KAAK;AAErD,QAAI,aAAa,GAAG;AAClB,aAAO,MAAM;AAAA,IACf,OAAO;AACL,cAAQ;AAAA,IACV;AAAA,EACF;AAEA,SAAO;AACT;AAsCO,SAAS,oBACd,aACA,OACA,WACS;AACT,QAAM,MAAM,0BAA0B,aAAa,OAAO,SAAS;AACnE,MAAI,MAAM,YAAY,UAAU,UAAU,YAAY,GAAG,GAAI,KAAK,MAAM,GAAG;AACzE,gBAAY,OAAO,KAAK,CAAC;AACzB,WAAO;AAAA,EACT;AACA,SAAO;AACT;;;"}