Base62

From Chorke Wiki
Jump to navigation Jump to search

About Base62

Base62 consist of 0-9A-Za-z and use to compress big Base10 into sort number. That may considered one kind of Encryption like Base64.

Why Base62

Base10 Big Integer Number quite difficult to memorized where Base62 compress/represent by sort length String.

Base62 Encode

/**
 * =============================================================================
 * Number.prototype.toBase62() developed aim to reduce(compress) the length of
 * big sized Integer Number. We developed it like regular base62 convention to
 * support popular most web browser in prior to the Sencha Ext JS MVVM
 * =============================================================================
 * @author    Chorke Inc<devs@chorke.org>
 * @version   0.0.00.GA
 * @since     0.0.00.GA
 * =============================================================================
 * @method    Number.prototype.toBase62()
 * @package   Number.prototype
 * @class     Number
 * @public
 * =============================================================================
 */
CKi.proto(Number, 'toBase62', function(){
    var base10  = parseInt(this),
        modulus, base62;
    
    //for((confirm base10 integer);(prevents base10 negative integer);(bitwise hack to fail big integer))
    for ((base10 = base10 !== +base10 || base10 % 1 ? -1 : base10, base62 = ''); (base10 >= 0); (base10 = Math.floor(base10 / 62) || -1)){
        // base10 % 62 ->  0 - 61
        // 0 - 9 | 36-61 | 10- 35
        // 48-57 | 65-90 | 97-121
        // 0 - 9 | A - Z | a -  z
        base62 = String.fromCharCode(((modulus = base10 % 62) > 9 ? modulus > 35 ? 29 : 87 : 48) + modulus) + base62;
    }
    return base62;
});

Base62 Dencode

/**
 * =============================================================================
 * String.prototype.toBase10() developed aim to expand(decompress) the length
 * of big sized Integer Number. We developed it like regular base62 convention
 * to support popular most web browser in prior to the Sencha Ext JS MVVM
 * =============================================================================
 * @author    Chorke Inc<devs@chorke.org>
 * @version   0.0.00.GA
 * @since     0.0.00.GA
 * =============================================================================
 * @method    String.prototype.toBase10()
 * @package   String.prototype
 * @class     String
 * @public
 * =============================================================================
 */
CKi.proto(String, 'toBase10', function(){
    var base62  = String(this),
        iterator, ascii, base10;
    
    //for((confirm base10 string);(if 'iterator' equals '-1', 'ascii' is 'NaN' cases break the loop);)
    for ((base10 = iterator = (base62 === (/\W|_|^$/.test(base62 += '') || base62) ) - 1);(ascii = base62.charCodeAt(iterator++));){
        base10 = base10 * 62 + ascii - [, 48, 29, 87][ascii >> 5];
    }
    return base10;
});