Last active
September 11, 2023 13:53
-
-
Save felixbuenemann/9a30be873ce7dc11dbdd to your computer and use it in GitHub Desktop.
Generate random 10 byte base58 identifiers
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
var min = 7427658739644928; // min int value that is 10 bytes long in base58 | |
var max = 9007199254740992; // max safe integer (exclusive), also 10 bytes | |
var alphabet = '123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ'; // base58 | |
var base = alphabet.length; | |
function encode(num) { | |
var mod, str = ''; | |
while (num >= base) { | |
mod = num % base; | |
str = alphabet[mod] + str; | |
num = (num - mod) / base; | |
} | |
return alphabet[num] + str; | |
}; | |
// returns random int between min (inclusive) and max (exclusive) | |
function randomInt(min, max) { | |
return Math.floor(Math.random() * (max - min)) + min; | |
} | |
// generate 10 byte random base58 id with ~50 bits of entropy | |
function generateShortUid() { | |
return encode(randomInt(min, max)); | |
} | |
module.exports = { | |
generateShortUid: generateShortUid | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I've converted this code to Kotlin, in case anyone ever needs it: