UNPKG

@picosearch/radix-tree

Version:

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

38 lines (37 loc) 973 B
/** * 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. */ export 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); }; export const getNewEmptyNode = () => [ Object.create(null), ]; export 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; }; export const assert = (condition, message) => { if (!condition) throw new Error(message); };