Friday, 17 May 2013

Modulo adjustment

If you open MDN pages, describing Math.ceil, Math.floor, and Math.round, you will find the good example of the adjustment and rounding based on the decimal logarithm. For exdample, Math.ceil10(55, 2) returns 100 where 2 expresses an exponent for 10^2.

Besides of logarithmic adjustment we can use modulo based adjustment. It is almost the same as above but uses an arbitrary number for adjustment.



/**
 * Modulo base adjustment of a number
 *
 * Math.floorModulo(value, modulo)
 * Math.ceilModulo(value, modulo)
 * Math.roundModulo(value, modulo)
 *
 * @param   {number} value   The number
 * @param   {number} modulo  The modulo
 * @return  {number] The adjusted value
 */
(function()
{
    var names = ['floor', 'ceil', 'round'];

    for (var i = 0; i < names.length; i++) {
        var name = names[i];
        (function(name, method)
        {
            //Math[name] = 
            Math[name + 'Modulo'] = 
            function(value, modulo)
            {
                return arguments.length < 2 
                    ? method(value) 
                    : method(value / modulo) * modulo;
            };
        })(name, Math[name]);
    }
})();

// Floor
Math.floorModulo(5, 5); // 5
Math.floorModulo(6, 5); // 5
Math.floorModulo(7, 5); // 5
Math.floorModulo(8, 5); // 5
Math.floorModulo(9, 5); // 5
Math.floorModulo(10, 5); // 10

// Ceil
Math.ceilModulo(5, 5); // 5
Math.ceilModulo(6, 5); // 10
Math.ceilModulo(7, 5); // 10
Math.ceilModulo(8, 5); // 10
Math.ceilModulo(9, 5); // 10
Math.ceilModulo(10, 5); // 10

// Round
Math.roundModulo(5, 5); // 5
Math.roundModulo(6, 5); // 5
Math.roundModulo(7, 5); // 5
Math.roundModulo(8, 5); // 10
Math.roundModulo(9, 5); // 10
Math.roundModulo(10, 5); // 10

1 comment: