remeda
Version:
A utility library for JavaScript and Typescript.
1 lines • 1.68 kB
Source Map (JSON)
{"version":3,"file":"binarySearchCutoffIndex-Cgz2eJ3b.cjs","names":[],"sources":["../src/internal/binarySearchCutoffIndex.ts"],"sourcesContent":["/**\n * A binary search implementation that finds the index at which `predicate`\n * stops returning `true` and starts returning `false` (consistently) when run\n * on the items of the array. It **assumes** that mapping the array via the\n * predicate results in the shape `[...true[], ...false[]]`. *For any other case\n * the result is unpredictable*.\n *\n * This is the base implementation of the `sortedIndex` functions which define\n * the predicate for the user, for common use-cases.\n *\n * It is similar to `findIndex`, but runs at O(logN), whereas the latter is\n * general purpose function which runs on any array and predicate, but runs at\n * O(N) time.\n */\nexport function binarySearchCutoffIndex<T>(\n array: ReadonlyArray<T>,\n predicate: (value: T, index: number, data: ReadonlyArray<T>) => boolean,\n): number {\n let lowIndex = 0;\n let highIndex = array.length;\n\n while (lowIndex < highIndex) {\n // eslint-disable-next-line no-bitwise -- We use bitwise operator here as a way to find the mid-point and round it down using the same operation.\n const pivotIndex = (lowIndex + highIndex) >>> 1;\n const pivot = array[pivotIndex]!;\n\n if (predicate(pivot, pivotIndex, array)) {\n lowIndex = pivotIndex + 1;\n } else {\n highIndex = pivotIndex;\n }\n }\n\n return highIndex;\n}\n"],"mappings":"AAcA,SAAgB,EACd,EACA,EACQ,CACR,IAAI,EAAW,EACX,EAAY,EAAM,OAEtB,KAAO,EAAW,GAAW,CAE3B,IAAM,EAAc,EAAW,IAAe,EACxC,EAAQ,EAAM,GAEhB,EAAU,EAAO,EAAY,EAAM,CACrC,EAAW,EAAa,EAExB,EAAY,EAIhB,OAAO"}