pbojinov
4/18/2015 - 8:24 PM

addPixelValues

addPixelValues

// add 1 or more strings with px in them as they were numbers
// eg: addPixelValues('5px', '5px') === '10px'
function addPixelValues() {
    var args = Array.prototype.slice.call(arguments, 0);
    var total = 0;
    for (var i in args) {
        var arg = args[i];
        // remove px from strings, convert to a number and add it to the total
        if (typeof arg === 'string' && arg.indexOf('px') !== -1) {
            var pixelValue = window.parseFloat(arg.replace('px', ''), 10);
            // passing in 'px' will pass the if test but will produce a `NaN`
            // so make sure we are adding a number
            total += pixelValue ? pixelValue : 0;
        }
        // add numbers directly to the account
        else if (typeof arg === 'number') {
            total += arg;
        }
        // and ignore everything else
    }
    return total + 'px';
}

var a = addPixelValues('1px', '2px', '3px', 3, 'px', 'cats'); // 9px
console.assert(a === '9px');

var b = addPixelValues('10px', '2px'); // 12px
console.assert(b === '12px');

var c = addPixelValues('5.5px', '5px'); // 10.5px
console.assert(c === '10.5px');

var d = addPixelValues('', 'cats', 'numbers'); // 0px
console.assert(d === '0px');