alphabeticID

by disfated

JavaScript

var alphabeticID = (function () {
    var samp = 'abcdefghijklmnopqrstuvwxyz0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ',
        L = samp.length,
        floor = Math.floor, log = Math.log, pow = Math.pow,
        bcpow = function (a, b) { return floor(pow(a, b)); };
    return {
        encode: function (num) {
            if (typeof num != 'number' || !isFinite(num) || num <= 0) return null;
            var ret = '', int = parseInt(num, 10), i = floor(log(int) / log(L)) + 1;
            while (i--) ret = samp[floor(int / bcpow(L, i)) % L] + ret;
            return ret;
        },
        decode: function (str) {
            if (typeof str != 'string' || !str) return null;
            var ret = 0, len = str.length, i = len;
            while (i--) ret += samp.indexOf(str[i]) * bcpow(L, i);
            return ret;
        }
    };
})();

$(function () {
    var tests = [ 9007199254740989, 5547779646876, 65468684, 1111, 89, 1 ];
    $('body').html('<pre>' + $.map(tests, function(num) {
        var enc = alphabeticID.encode(num);
        var dec = alphabeticID.decode(enc);
        return (dec === num ? 'pass' : 'fail') + ': ' + num + ' => ' + enc + ' => ' + dec;
    }).join('\n') + '</pre>');
});