Skip to content

Instantly share code, notes, and snippets.

@crossjs
Last active December 19, 2019 01:05
Show Gist options
  • Save crossjs/9390e0afc7326ad1069b26ab53cc720b to your computer and use it in GitHub Desktop.
Save crossjs/9390e0afc7326ad1069b26ab53cc720b to your computer and use it in GitHub Desktop.
Encrypt number to string with provided radix chars
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,
};
}
}
@crossjs
Copy link
Author

crossjs commented Nov 8, 2019

encode(Date.now() + Math.floor(Math.random() * 1e3) * 1e13)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment