Skip to content

Instantly share code, notes, and snippets.

@viktorkelemen
Created April 30, 2014 13:45
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save viktorkelemen/7155e0c02f090f16b4e4 to your computer and use it in GitHub Desktop.
Save viktorkelemen/7155e0c02f090f16b4e4 to your computer and use it in GitHub Desktop.
An URL shortener algorithm
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