Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 | 1x 1x 1x 1x 2x 2x 2x 1x 1x 2x 2x 2x 2x 2x 2x 2x | const LAST_RUNTIME_ID = Symbol('LastRuntimeId');
const GLOBAL_CONTEXT = {};
const DEFAULT_MAX = 0xffffffff; // Max 32-bit integer
const DEFAULT_SEPARATOR = '-';
/**
* Generate a unique numeric ID string valid during a single runtime session;
*
* @param context - An optional object to be used as context.
* Defaults to a global context;
* @param separator - The component separator. Defaults to "-";
* @param max - The maximum component value. Defaults to 4294967295;
* @returns The string representation of the the unique ID;
*/
export default function getRuntimeId(
context?: unknown,
separator?: string,
max?: number
): string {
return getNextRuntimeId(
// @ts-ignore
context !== null && typeof context === 'object' ? context : GLOBAL_CONTEXT,
LAST_RUNTIME_ID,
(typeof max === 'number' && max > 0 ? max : DEFAULT_MAX) >>> 0
).join(typeof separator === 'string' ? separator : DEFAULT_SEPARATOR);
}
/*
* Helpers
*/
function getNextRuntimeId(
context: Record<symbol, Array<number>>,
symbol: symbol,
max: number
): Array<number> {
let idComponents = context[symbol];
if (!(idComponents instanceof Array)) {
idComponents = [0];
Object.defineProperty(context, symbol, { value: idComponents });
}
for (let carry = true, i = 0; carry && i < idComponents.length; ++i) {
let n = idComponents[i] | 0;
Eif (n < max) {
carry = false;
n = n + 1;
} else {
n = 0;
if (i + 1 === idComponents.length) idComponents.push(0);
}
idComponents[i] = n;
}
return idComponents;
}
|