Skip to content

Instantly share code, notes, and snippets.

@tejzpr
Last active January 25, 2018 21:26
Show Gist options
  • Save tejzpr/41b3b97a13427bc128c6ed3b22d4c714 to your computer and use it in GitHub Desktop.
Save tejzpr/41b3b97a13427bc128c6ed3b22d4c714 to your computer and use it in GitHub Desktop.
// JavaScript (ES6) port of the code at https://gist.github.com/bhelx/778542
// Also handles leading 0's in strings
const BASE = 62;
const UPPERCASE_OFFSET = 55;
const LOWERCASE_OFFSET = 61;
const DIGIT_OFFSET = 48;
class Base62{
constructor() {
}
isDigit(char) {
return !isNaN(parseInt(char, 10));
}
trueOrd(char) {
if(this.isDigit(char)) {
return char.charCodeAt(0) - DIGIT_OFFSET;
} else if(('A' <= char) && (char <= 'Z')) {
return char.charCodeAt(0) - UPPERCASE_OFFSET;
} else if(('a' <= char) && (char <= 'z')) {
return char.charCodeAt(0) - LOWERCASE_OFFSET;
} else {
throw new Error(char + " is not a valid character");
}
}
trueChr(int) {
if(int < 10) {
return String.fromCharCode(int + DIGIT_OFFSET);
} else if((10 <= int) && (int <= 35)) {
return String.fromCharCode(int + UPPERCASE_OFFSET);
} else if((36 <= int) && (int< 62)) {
return String.fromCharCode(int + LOWERCASE_OFFSET);
} else {
throw new Error(int+" is not a valid integer in the range of base "+ BASE);
}
}
encode(key) {
const reversed_key = Array.from(key).reverse();
let int_sum = 0;
for(const idx of reversed_key.keys()) {
int_sum += this.trueOrd(reversed_key[idx]) * Number(Math.pow(BASE, idx))
}
return int_sum;
}
decode(int) {
if(int == 0) {
return '0';
}
let str = '';
while(int >= 0) {
let rem = int % BASE;
str = this.trueChr(rem) + str;
if (int === 0)
{
break;
}
int = Math.floor(int/BASE);
}
return str;
}
}
// let b62 = new Base62();
// console.log(b62.decode(b62.encode('0Zebra'))); // => 0Zebra
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment