Created
August 30, 2011 07:05
-
-
Save davidcrawford/1180363 to your computer and use it in GitHub Desktop.
Base62 encoder/decoder
This file contains 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
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