UNPKG

@picosearch/radix-tree

Version:

Simple, zero dependency, type-safe implementation of a radix tree data structure.

45 lines (44 loc) 1.27 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.assert = exports.getCommonPrefix = exports.getNewEmptyNode = exports.sortedInsert = void 0; /** * Insert a value into a sorted array efficiently. * * Reference: https://stackoverflow.com/a/21822316 * * @param array - The array to insert into. Must be sorted. * @param value - The value to insert. * @param compare - The comparison function. */ const sortedInsert = (array, value, compare) => { let low = 0; let high = array.length; while (low < high) { const mid = (low + high) >>> 1; if (compare(array[mid], value) < 0) low = mid + 1; else high = mid; } array.splice(low, 0, value); }; exports.sortedInsert = sortedInsert; const getNewEmptyNode = () => [ Object.create(null), ]; exports.getNewEmptyNode = getNewEmptyNode; const getCommonPrefix = (a, b) => { let result = ''; for (let i = 0; i < Math.min(a.length, b.length); i++) { if (a[i] !== b[i]) break; result += a[i]; } return result; }; exports.getCommonPrefix = getCommonPrefix; const assert = (condition, message) => { if (!condition) throw new Error(message); }; exports.assert = assert;