Created
April 12, 2024 04:24
-
-
Save rheinardkorf/a5bf6168d4e6d723626716da04398e98 to your computer and use it in GitHub Desktop.
KSUID implemented in Google Apps Script
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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