@techmely/utils
Version:
Collection of helpful JavaScript / TypeScript utils
55 lines (50 loc) • 1.51 kB
JavaScript
var crypto = require('crypto');
var POOL_SIZE_MULTIPLIER = 128;
var pool;
var poolOffset;
function fillPool(bytes) {
if (!pool || pool.length < bytes) {
pool = Buffer.allocUnsafe(bytes * POOL_SIZE_MULTIPLIER);
crypto.webcrypto.getRandomValues(pool);
poolOffset = 0;
} else if (poolOffset + bytes > pool.length) {
crypto.webcrypto.getRandomValues(pool);
poolOffset = 0;
}
poolOffset += bytes;
}
function random(bytes) {
fillPool(bytes -= 0);
return pool.subarray(poolOffset - bytes, poolOffset);
}
function customRandom(alphabet, defaultSize, getRandom) {
let mask = (2 << 31 - Math.clz32(alphabet.length - 1 | 1)) - 1;
let step = Math.ceil(1.6 * mask * defaultSize / alphabet.length);
return (size = defaultSize) => {
let id = "";
while (true) {
let bytes = getRandom(step);
let i = step;
while (i--) {
id += alphabet[bytes[i] & mask] || "";
if (id.length === size)
return id;
}
}
};
}
function customAlphabet(alphabet, size = 21) {
return customRandom(alphabet, size, random);
}
// src/id.ts
var generateId = customAlphabet(
"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"
);
var DEFAULT_PREFIX_ID_LENGTH = 22;
function generatePrefixId(prefix = "key", length = DEFAULT_PREFIX_ID_LENGTH) {
return `${prefix}_${generateId(length)}`;
}
exports.DEFAULT_PREFIX_ID_LENGTH = DEFAULT_PREFIX_ID_LENGTH;
exports.generateId = generateId;
exports.generatePrefixId = generatePrefixId;
;