Skip to content

Instantly share code, notes, and snippets.

@scryptonite
Created February 11, 2014 04:16
Show Gist options
  • Save scryptonite/8929182 to your computer and use it in GitHub Desktop.
Save scryptonite/8929182 to your computer and use it in GitHub Desktop.
JavaScript Number::toString and parseInt for bases above 36.
function encode(input, base, map){
var num = input, arr = [], item;
if(typeof base != "number" && typeof base == "string" || Array.isArray(base)){
map = base;
base = map.length;
}
if(typeof base != "number") throw "Base must be a number";
if(typeof base < 2) throw "Base must be greater than 1";
while(num){
item = num % base;
if(typeof map == "string" || Array.isArray(map)) item = map[item];
if(typeof map == "function") item = map(item);
arr[arr.length] = item;
num = Math.floor(num / base);
}
return arr.reverse();
}
function decode(input, base, map){
var num = 0, arr = input, item;
if(typeof base != "number" && typeof base == "string" || Array.isArray(base)){
map = base;
base = map.length;
}
if(typeof base != "number") throw "Base must be a number";
if(typeof base < 2) throw "Base must be greater than 1";
var i = 0;
while(arr.length){
item = arr.shift();
if(typeof map == "string" || Array.isArray(map)) item = map.indexOf(item);
if(typeof map == "function") item = map(item);
num += item * Math.pow(base, arr.length);
if(i++ >= 1000) throw "Overflow!";
}
return num;
}
var dict = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
encode(10, 16, dict).join(""); // "a"
encode(1000000, dict).join(""); // "4c92"
decode([1, 0], 16); // 16
decode([1, 1], 2); // 3
decode([1, 0], "0123456789"); // 10
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment