import crypto from "crypto"; export async function sleep(ms: number): Promise { await new Promise((resolve) => setTimeout(resolve, ms)); } export async function waitImmediate(): Promise { await new Promise((resolve) => setImmediate(resolve)); } export function getRandomItem(array: T[]): T { return array[Math.floor(Math.random() * array.length)]; } export function toUuid(identifier: string | null | undefined): string { if (!identifier) { return "unknown"; } const uuid = crypto.createHash("md5").update(identifier).digest("hex").split(""); uuid.splice(20, 0, "-"); uuid.splice(16, 0, "-"); uuid.splice(12, 0, "-"); uuid.splice(8, 0, "-"); return uuid.join(""); } /** * Return the index where to insert x in array, assuming array is sorted. * The return value i is such that all e in array[:i] have e <= x, and all e in * array[i:] have e > x. So if x already appears in the list, array.insert(i, x) will * insert just after the rightmost x already there. * Ported from Python: https://github.com/python/cpython/blob/07cf10bafc8f6e1fcc82c10d97d3452325fc7c04/Lib/bisect.py#L19 * @param array * @param x */ export function bisectRight(array: Array, x: number): number { let lowIndex = 0; let highIndex = array.length; while (lowIndex < highIndex) { const midIndex = Math.floor((lowIndex + highIndex) / 2); if (x < array[midIndex]) { highIndex = midIndex; } else { lowIndex = midIndex + 1; } } return lowIndex; }