Created
October 25, 2017 20:13
-
-
Save trevorhreed/efff3714c1cea0241dba15b300e24301 to your computer and use it in GitHub Desktop.
Shorter UUIDs
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
const bigInt = require("big-integer") | |
const symbols = `0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ`; | |
const v2r = (n, b) => { | |
if(!bigInt.isInstance(n)) n = bigInt(n); | |
let digits = ''; | |
while(n > 0){ | |
let r = n.divmod(b); | |
digits = symbols[r.remainder] + digits; | |
n = r.quotient; | |
} | |
return digits; | |
} | |
const r2v = (digits, b) => { | |
let n = bigInt(); | |
for(let d of digits){ | |
if(symbols.substr(0, b).indexOf(d) === -1){ | |
throw new Error(`Digit '${d}' not found in digits ${base_symbols.substr(0, b)}`); | |
} | |
n = n.times(b).add(symbols.indexOf(d)); | |
} | |
return n; | |
} | |
const b2b = (digits, b1, b2) => { | |
return v2r(r2v(digits, b1), b2); | |
} | |
const toShort = (value) => { | |
value = value.replace(/-/g, '').toLowerCase(); | |
let base = symbols.length; | |
return b2b(value, 16, base); | |
} | |
const fromShort = (value) => { | |
let base = symbols.length; | |
let result = b2b(value, base, 16); | |
return result.replace(/^([a-f0-9]{8})([a-f0-9]{4})([a-f0-9]{4})([a-f0-9]{4})([a-f0-9]{12})$/, '$1-$2-$3-$4-$5'); | |
} | |
// Example | |
const arr = [ | |
'3763672ba658491f9ad267aa1ff337cd', | |
'f891380f-9db7-4c03-a13e-2063a83272c3', | |
'FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF' | |
].forEach((uuid)=>{ | |
let short = toShort(uuid); | |
let long = fromShort(short); | |
console.log(`${uuid} >> ${short} >> ${long}`); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment