Created
June 17, 2024 19:23
-
-
Save utilmind/e25c88e60590a08d2ad4b816f52d3da1 to your computer and use it in GitHub Desktop.
base62 encoding/decoding for integers 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
(function() { | |
// const | |
var chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz', | |
base = 62; | |
window.int62 = function(int) { | |
if (0 === int) { | |
return '0'; | |
} | |
var result = '', // let | |
num = int, | |
remainder; | |
while (0 < num) { | |
remainder = num % base; | |
result = chars[remainder] + result; | |
num = Math.floor(num / base); | |
} | |
return result; | |
} | |
window.unint62 = function(str) { | |
var i, result = 0; // let | |
for (i = 0; i < str.length; ++i) { | |
result += chars.indexOf(str[str.length - 1 - i]) * Math.pow(base, i); | |
} | |
return result; | |
} | |
})(); | |
/* | |
// if you need BigInts, but this require ECMAScript 2020. Okay to use after 2025, should will be supported by ALL browsers. | |
function int62(int) { // aka base62_encode(integer) | |
const chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'; | |
let result = ''; | |
let num = BigInt(int); // BigInt require ECMAScript 2020 (ES11)! | |
if (num === 0n) { | |
return chars[0]; | |
} | |
while (num > 0n) { | |
result = chars[num % 62n] + result; | |
num = num / 62n; | |
} | |
return result; | |
} | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment