Created
April 30, 2014 13:45
-
-
Save viktorkelemen/7155e0c02f090f16b4e4 to your computer and use it in GitHub Desktop.
An URL shortener algorithm
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
var codeset = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"; | |
var base = codeset.length; | |
function encode(n) { | |
var converted = ""; | |
while (n > 0) { | |
converted = converted + codeset[n%base]; | |
n = Math.floor(n/base); | |
} | |
return converted; | |
} | |
function decode(converted) { | |
var c = 0, ind; | |
for (var i = converted.length-1; i >= 0; i--) { | |
c += (codeset.indexOf(converted[i])) * Math.pow(base, i); | |
} | |
return c; | |
} | |
console.log("Test #1: ", 125 == decode(encode(125))); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment