Skip to content

Instantly share code, notes, and snippets.

@droduit
Created May 29, 2019 20:16
Show Gist options
  • Save droduit/af37dd833facae28353af3d999b96ebb to your computer and use it in GitHub Desktop.
Save droduit/af37dd833facae28353af3d999b96ebb to your computer and use it in GitHub Desktop.
JS encode / decode base62
// Source : https://lowrey.me/encoding-decoding-base-62-in-es6-javascript/
const base62 = {
charset: '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'.split(''),
encode: integer => {
if (integer === 0) {
return 0;
}
let s = [];
while (integer > 0) {
s = [base62.charset[integer % 62], ...s];
integer = Math.floor(integer / 62);
}
return s.join('');
},
decode: chars => chars.split('').reverse()
.reduce((prev, curr, i) => prev + (base62.charset.indexOf(curr) * (62 ** i)), 0)
};
// Usage
let sha512 = "1fe3e26d11b5984d794563d66e9c98862f499753c9edaea49bfcbd0bc27138b2c78b8375561d24ea591cac6da535094779eaa9d30c8df6298f73fc493139cc2f";
console.log(base62.encode(parseInt("0x"+sha512)));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment