Last active
December 31, 2015 16:29
-
-
Save jcaxmacher/8013629 to your computer and use it in GitHub Desktop.
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
/* | |
Converts any integer into a base [BASE] number. I have chosen 36 | |
as it is meant to represent the integers using case-insensitive alphanumeric | |
characters, [no special characters] = {0..9}, {A..Za..z} | |
I plan on using this to shorten the representation of possibly long ids, | |
a la url shortenters | |
base36.saturate('5t6C9') takes the base 36 key, as a string, and turns it back into an integer | |
base36.dehydrate(9759321) takes an integer and turns it into the base 36 string | |
*/ | |
var base36 = { | |
BASE: 36, | |
LOWERCASEOFFSET: 87, | |
DIGITOFFSET: 48, | |
trueOrd: function(char) { | |
var ord = char.toLowerCase().charCodeAt(0); | |
if (ord >= 48 && ord <= 57) { | |
return ord - this.DIGITOFFSET; | |
} else if (ord >= 97 && ord <= 122) { | |
return ord - this.LOWERCASEOFFSET; | |
} else { | |
throw new Error(char + " is not a valid character"); | |
} | |
}, | |
trueChr: function(integer) { | |
if (integer < 10) { | |
return String.fromCharCode(integer + this.DIGITOFFSET); | |
} else if (integer >= 10 && integer <= 35) { | |
return String.fromCharCode(integer + this.LOWERCASEOFFSET); | |
} else { | |
throw new Error(integer + " is not a valid integer in the range of base " + this.BASE); | |
} | |
}, | |
saturate: function(key) { | |
var intSum = 0, | |
reversedKey = key.split('').reverse().join(''), | |
char = ''; | |
for (var i = 0; i < reversedKey.length; i++) { | |
char = reversedKey[i]; | |
intSum += this.trueOrd(char) * parseInt(Math.pow(this.BASE, i)); | |
} | |
return intSum; | |
}, | |
dehydrate: function(integer) { | |
var str = '', | |
remainder = 0; | |
if (integer == 0) { | |
return '0'; | |
} | |
while (integer > 0) { | |
remainder = integer % this.BASE; | |
str = this.trueChr(remainder) + str; | |
integer = Math.floor(integer / this.BASE); | |
} | |
return str; | |
} | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment