| | |
| | | /* cspell:disable-next-line */ |
| | | // Refactor: Peter Somogyvari @petermetz |
| | | |
| | | /** @typedef {">=" | "<=" | "<" | ">" | "-" } BinarySearchPredicate */ |
| | | /** @typedef {"GE" | "GT" | "LT" | "LE" | "EQ" } SearchPredicateSuffix */ |
| | | /** @typedef {">=" | "<=" | "<" | ">" | "-"} BinarySearchPredicate */ |
| | | /** @typedef {"GE" | "GT" | "LT" | "LE" | "EQ"} SearchPredicateSuffix */ |
| | | |
| | | /** |
| | | * Helper function for compiling binary search functions. |
| | |
| | | }; |
| | | |
| | | /** |
| | | * Defines the search type used by this module. |
| | | * @template T |
| | | * @typedef {(items: T[], start: number, compareFn?: number | ((item: T, needle: number) => number), l?: number, h?: number) => number} Search |
| | | */ |
| | | |
| | | /** |
| | | * This helper functions generate code for two binary search functions: |
| | | * A(): Performs a binary search on an array using the comparison operator specified. |
| | | * P(): Performs a binary search on an array using a _custom comparison function_ |
| | |
| | | * @param {boolean} reversed Whether the search should be reversed. |
| | | * @param {SearchPredicateSuffix} suffix The suffix to be used in the function name. |
| | | * @param {boolean=} earlyOut Whether the search should return as soon as a match is found. |
| | | * @returns {(items: T[], start: number, compareFn?: number | ((item: T, needle: number) => number), l?: number, h?: number) => number} The compiled binary search function. |
| | | * @returns {Search<T>} The compiled binary search function. |
| | | */ |
| | | const compileBoundsSearch = (predicate, reversed, suffix, earlyOut) => { |
| | | const arg1 = compileSearch("A", `x${predicate}y`, reversed, ["y"], earlyOut); |
| | |
| | | return result(); |
| | | }; |
| | | |
| | | const fns = { |
| | | ge: compileBoundsSearch(">=", false, "GE"), |
| | | gt: compileBoundsSearch(">", false, "GT"), |
| | | lt: compileBoundsSearch("<", true, "LT"), |
| | | le: compileBoundsSearch("<=", true, "LE"), |
| | | eq: compileBoundsSearch("-", true, "EQ", true) |
| | | }; |
| | | |
| | | /** |
| | | * These functions are used to perform binary searches on arrays. |
| | | * @example |
| | |
| | | * const index2 = le(arr, 5); // index2 === 4 |
| | | * ``` |
| | | */ |
| | | module.exports = { |
| | | ge: compileBoundsSearch(">=", false, "GE"), |
| | | gt: compileBoundsSearch(">", false, "GT"), |
| | | lt: compileBoundsSearch("<", true, "LT"), |
| | | le: compileBoundsSearch("<=", true, "LE"), |
| | | eq: compileBoundsSearch("-", true, "EQ", true) |
| | | }; |
| | | module.exports = fns; |