Skip to content

Instantly share code, notes, and snippets.

@stalingino
Last active April 13, 2023 18:59
Show Gist options
  • Save stalingino/809d1f46d6843541f123c5190cfa0b57 to your computer and use it in GitHub Desktop.
Save stalingino/809d1f46d6843541f123c5190cfa0b57 to your computer and use it in GitHub Desktop.
Base64 UUID generator using UUID version 4 and variant 2. URL friendly. Faster direct generation from random.
function generateBase64UUID() {
const byteArray = new Uint8Array(16);
window.crypto.getRandomValues(byteArray);
// Set the UUID version (4) and variant (2)
byteArray[6] = (byteArray[6] & 0x0f) | 0x40;
byteArray[8] = (byteArray[8] & 0x3f) | 0x80;
let base64String = '';
const characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_';
for (let i = 0; i < 15;) {
const byte1 = byteArray[i++];
const byte2 = byteArray[i++];
const byte3 = byteArray[i++];
const base64Index1 = byte1 >> 2;
const base64Index2 = ((byte1 & 0x03) << 4) | (byte2 >> 4);
const base64Index3 = ((byte2 & 0x0F) << 2) | (byte3 >> 6);
const base64Index4 = byte3 & 0x3F;
base64String += characters[base64Index1] + characters[base64Index2] +
characters[base64Index3] + characters[base64Index4];
}
return base64String;
}
// const base64Uuid = generateBase64UUID();
// console.log('Base64 UUID:', base64Uuid);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment