Skip to content

Instantly share code, notes, and snippets.

@rheinardkorf
Created April 12, 2024 04:24
Show Gist options
  • Save rheinardkorf/a5bf6168d4e6d723626716da04398e98 to your computer and use it in GitHub Desktop.
Save rheinardkorf/a5bf6168d4e6d723626716da04398e98 to your computer and use it in GitHub Desktop.
KSUID implemented in Google Apps Script
// Pseudorandom number generator function
function getRandomBytes(length) {
var result = [];
for (var i = 0; i < length; i++) {
result.push(Math.floor(Math.random() * 256));
}
return result;
}
// Convert bytes to base62 string
function bytesToBase62(bytes) {
var base62Chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz';
var result = '';
var num = 0;
for (var i = 0; i < bytes.length; i++) {
num = num * 256 + bytes[i];
}
while (num > 0) {
result = base62Chars.charAt(num % 62) + result;
num = Math.floor(num / 62);
}
return result;
}
// KSUID generation function
function generateKSUID() {
// Generate timestamp
var timestamp = Math.floor((new Date().getTime() / 1000) - 1400000000); // Adjust epoch to May 13th, 2014
// Generate random payload (128 bits)
var payload = getRandomBytes(16);
// Concatenate timestamp and payload
var bytes = [];
bytes.push(timestamp >>> 24 & 0xFF);
bytes.push(timestamp >>> 16 & 0xFF);
bytes.push(timestamp >>> 8 & 0xFF);
bytes.push(timestamp & 0xFF);
bytes.push.apply(bytes, payload);
// Encode concatenated value using base62
var base62Str = bytesToBase62(bytes);
// Pad result to ensure it always has a fixed length of 27 characters
var result = base62Str.padEnd(27, '0');
return result;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment