URL Shortner
by kshep92
JavaScript
alphabet = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-_".split("")
base = alphabet.length
var ids = [100, 345, 536374, 9378937377465];
function encode(id) {
var remainders = [];
while(id > 0) {
var remainder = id % base;
remainders.push(remainder);
id = parseInt(id/base);
}
var encoded = "";
remainders.reverse();
remainders.forEach(function(elm) {
encoded += alphabet[elm];
});
return encoded;
}
function decode(shortCode) {
var decoded = 0;
var chars = shortCode.split("");
var indexes = [];
chars.forEach((elm) => {
indexes.push(alphabet.indexOf(elm));
});
indexes.reverse().forEach((elm, idx) => {
decoded += elm * Math.pow(base, idx);
});
return decoded;
}
ids.forEach(function(elm) {
var encoded = encode(elm);
var decoded = decode(encoded);
console.log(elm + " -> " + encoded + ", " + decoded);
});