Last active
December 19, 2019 01:05
-
-
Save vvenv/9390e0afc7326ad1069b26ab53cc720b to your computer and use it in GitHub Desktop.
Encrypt number to string with provided radix chars
This file contains hidden or 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
class Encrypt { | |
static create(chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789') { | |
const radix = chars.length; | |
function encode(num) { | |
if (num < radix) { | |
return chars.charAt(num); | |
} | |
return `${encode(Math.floor(num / radix))}${chars.charAt(num % radix)}`; | |
} | |
function decode(str) { | |
const len = str.length; | |
let num = 0; | |
for (let i = 0; i < len; i++) { | |
num += chars.indexOf(str.charAt(len - i - 1)) * Math.pow(radix, i); | |
} | |
return num; | |
} | |
return { | |
encode, | |
decode, | |
}; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
encode(Date.now() + Math.floor(Math.random() * 1e3) * 1e13)