base62.js 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. module.exports = (function (Base62) {
  2. "use strict";
  3. var DEFAULT_CHARACTER_SET = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
  4. Base62.encode = function(integer){
  5. if (integer === 0) {return '0';}
  6. var s = '';
  7. while (integer > 0) {
  8. s = Base62.characterSet[integer % 62] + s;
  9. integer = Math.floor(integer/62);
  10. }
  11. return s;
  12. };
  13. var defaultCharsetDecode = function defaultCharsetDecode (base62String) {
  14. var value = 0,
  15. i = 0,
  16. length = base62String.length,
  17. charValue;
  18. for (; i < length; i++) {
  19. charValue = base62String.charCodeAt(i);
  20. if (charValue < 58) {
  21. charValue = charValue - 48;
  22. } else if (charValue < 91) {
  23. charValue = charValue - 29;
  24. } else {
  25. charValue = charValue - 87;
  26. }
  27. value += charValue * Math.pow(62, length - i - 1);
  28. }
  29. return value;
  30. };
  31. var customCharsetDecode = function customCharsetDecode (base62String) {
  32. var val = 0,
  33. i = 0,
  34. length = base62String.length,
  35. characterSet = Base62.characterSet;
  36. for (; i < length; i++) {
  37. val += characterSet.indexOf(base62String[i]) * Math.pow(62, length - i - 1);
  38. }
  39. return val;
  40. };
  41. var decodeImplementation = null;
  42. Base62.decode = function(base62String){
  43. return decodeImplementation(base62String);
  44. };
  45. Base62.setCharacterSet = function(chars) {
  46. var arrayOfChars = chars.split(""), uniqueCharacters = [];
  47. if(arrayOfChars.length !== 62) throw Error("You must supply 62 characters");
  48. arrayOfChars.forEach(function(char){
  49. if(!~uniqueCharacters.indexOf(char)) uniqueCharacters.push(char);
  50. });
  51. if(uniqueCharacters.length !== 62) throw Error("You must use unique characters.");
  52. Base62.characterSet = arrayOfChars;
  53. decodeImplementation = chars === DEFAULT_CHARACTER_SET ? defaultCharsetDecode : customCharsetDecode;
  54. };
  55. Base62.setCharacterSet(DEFAULT_CHARACTER_SET);
  56. return Base62;
  57. }({}));