Skip to content

Instantly share code, notes, and snippets.

@davidcrawford
Created August 30, 2011 07:05
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save davidcrawford/1180363 to your computer and use it in GitHub Desktop.
Save davidcrawford/1180363 to your computer and use it in GitHub Desktop.
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