Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Base62 encoder/decoder
var Base62 = (function() {
var chars = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
var base = chars.length;
var decoder = chars.split('').reduce(function(memo, c, i) {
memo[c] = i;
return memo;
}, {});
var encode = function(value) {
if (typeof(value) !== 'number') {
value = parseInt(value);
}
if (Math.floor(value) !== value) {
throw new Error('Base62.encode called with value=' + value
+ ', should only be called with integers');
}
var encoded = '';
do {
var m = value % base;
encoded = chars[m] + encoded;
value = (value - m) / base;
} while (value > 0);
return encoded;
};
var decode = function(encoded) {
var len = encoded.length;
var value = 0;
for(var i = 0; i < len; i++) {
value += decoder[encoded[i]] * Math.pow(base, len - i - 1);
}
return value;
};
return {
encode: encode,
decode: decode
};
}());
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.