Skip to content

Instantly share code, notes, and snippets.

@dinjas
Last active November 24, 2018 09:17
Show Gist options
  • Save dinjas/5689273 to your computer and use it in GitHub Desktop.
Save dinjas/5689273 to your computer and use it in GitHub Desktop.
Simple shortener of an integer string into a base62 string. Sample usage at bottom of each file.
var codeset = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
var base = codeset.length;
function encode(intStr) {
var hash = "";
intStr = parseInt(intStr);
while (intStr > 0) {
hash = self.codeset[parseInt(intStr % base)] + hash;
intStr = Math.floor(intStr / base);
}
return hash;
}
function decode(encoded) {
var intStr = 0;
for (var i = 0; i < encoded.length; i++) {
var char, n, power;
char = encoded[i];
n = codeset.indexOf(char);
if (n == -1) {
return -1; // bad hash
}
power = (encoded.length-1)-i;
intStr += n * Math.pow(base, power);
}
return parseInt(intStr);
}
var result = encode("12345");
console.log("encode '12345' = "+result);
console.log("decode "+result+" = "+decode(result));
@codeset = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
@base = @codeset.length
def encode(intStr)
hash = ""
while (intStr.to_i > 0)
hash = "#{@codeset[(intStr % @base).to_i]}#{hash}"
intStr = (intStr.to_i / @base).floor
end
return hash;
end
def decode(encoded)
intStr = 0
encoded = encoded.split('')
(0..encoded.length-1).each do |i|
char = encoded[i]
n = @codeset.index(char)
return nil if n.nil? # bad hash
power = (encoded.length-1)-i
intStr += n * (@base ** power)
end
return intStr.to_i
end
result = encode("12345")
puts("'12345' encodes to: #{result}")
puts("#{result} decodes to: #{decode(result)}")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment