Skip to content

Instantly share code, notes, and snippets.

@jrasanen
Last active March 7, 2018 06:15
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jrasanen/80a2945fd4ae79d60c0b34448662dd2a to your computer and use it in GitHub Desktop.
Save jrasanen/80a2945fd4ae79d60c0b34448662dd2a to your computer and use it in GitHub Desktop.
// Random quick uuidv4 implementation
// https://gist.github.com/jed/982883
const b = (
a // placeholder
) => {
return a // if the placeholder was passed, return
? ( // a random number from 0 to 15
a ^ // unless b is 8,
Math.random() // in which case
* 16 // a random number from
>> a/4 // 8 to 11
).toString(16) // in hexadecimal
: ( // or otherwise a concatenated string:
[1e7] + // 10000000 +
-1e3 + // -1000 +
-4e3 + // -4000 +
-8e3 + // -80000000 +
-1e11 // -100000000000,
).replace( // replacing
/[018]/g, // zeroes, ones, and eights with
b // random hex digits
)
}
// Main logic
const uuid = b();
const suuid = uuid.replace(/-/g, '')
var result = ''
// JS version of PHP's "pack(h*)"
for (i = 0; i < suuid.length; i += 2) {
let word = suuid[i]
if (((i + 1) >= suuid.length) || typeof suuid[i + 1] === 'undefined') {
word += '0'
} else {
word += suuid[i + 1]
}
// low nibble first
word = word[1] + word[0]
const char = String.fromCharCode(parseInt(word, 16))
result += char
}
// URL-safe base64 representation
const compressed = Buffer.from(result, 'binary')
.toString('base64')
.replace(/[=\/\-\+]+/g, '')
console.log('original uuidv4', uuid, uuid.length, 'characters')
console.log('compressed uuidv4', compressed, compressed.length, 'characters')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment