Skip to content

Instantly share code, notes, and snippets.

@FlameWolf
Last active November 7, 2024 16:51
Show Gist options
  • Save FlameWolf/f422dc4dc69ec0b82513639845ffc85f to your computer and use it in GitHub Desktop.
Save FlameWolf/f422dc4dc69ec0b82513639845ffc85f to your computer and use it in GitHub Desktop.
const toBase62String = function (value) {
const base = 62n;
const digits = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
const sign = value < 0n ? "-" : "";
let [result, quotient] = ["", sign ? 0n - value : value];
do {
result = `${digits[Number(quotient % base)]}${result}`;
} while ((quotient /= base));
return `${sign}${result}`;
};
const getRandomIdString = function (steps = 4) {
let value = 0n;
for (let i = 0; i < steps; i++) {
value = (value << 53n) + BigInt(Math.floor(Math.random() * Number.MAX_SAFE_INTEGER));
}
return toBase62String(value).substring(0, steps * 8);
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment