-
-
Save karadza3a/73cb954ce79ac1936935d68a5e666f05 to your computer and use it in GitHub Desktop.
Base62 encode & decode (alphanumeric only) in JavaScript
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 ALPHA = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'; | |
var Base62 = function () {}; | |
var _encode = function (value) { | |
if (typeof(value) !== 'number') { | |
throw 'Value is not number!'; | |
} | |
var result = '', mod; | |
do { | |
mod = value % 62; | |
result = ALPHA.charAt(mod) + result; | |
value = Math.floor(value / 62); | |
} while(value > 0); | |
return result; | |
}; | |
var _decode = function (value) { | |
var result = 0; | |
for (var i = 0, len = value.length; i < len; i++) { | |
result *= 62; | |
result += ALPHA.indexOf(value[i]); | |
} | |
return result; | |
}; | |
Base62.prototype = { | |
constructor: Base62, | |
encode: _encode, | |
decode: _decode | |
}; | |
return Base62; | |
})(); |
Author
karadza3a
commented
Feb 24, 2019
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment