Code coverage report for number/currencyFormat.js

Statements: 100% (14 / 14)      Branches: 100% (10 / 10)      Functions: 100% (4 / 4)      Lines: 100% (13 / 13)     

All files » number/ » currencyFormat.js
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 401         1       3     25 25 25       25       25 11   14         3   3       1      
define(function () {
 
    /**
     * Converts number into currency format
     */
    var currencyFormatter = {
 
        create : function($nDecimalDigits, $decimalSeparator, $thousandsSeparator){
 
            var format = function (val, nDecimalDigits, decimalSeparator, thousandsSeparator) {
                //defaults will be bound inside the closure, only way to replace
                //them is by creating a new instance (avoids undesired side-effect)
                nDecimalDigits = nDecimalDigits == null? $nDecimalDigits : nDecimalDigits;
                decimalSeparator = decimalSeparator == null? $decimalSeparator : decimalSeparator;
                thousandsSeparator = thousandsSeparator == null? $thousandsSeparator : thousandsSeparator;
 
                //can't use enforce precision since it returns a number and we are
                //doing a RegExp over the string
                var fixed = val.toFixed(nDecimalDigits),
                    //separate begin [$1], middle [$2] and decimal digits [$4]
                    parts = new RegExp('^(-?\\d{1,3})((?:\\d{3})+)(\\.(\\d{'+ nDecimalDigits +'}))?$').exec( fixed );
 
                if(parts){ //val >= 1000 || val <= -1000
                    return parts[1] + parts[2].replace(/\d{3}/g, thousandsSeparator + '$&') + (parts[4] ? decimalSeparator + parts[4] : '');
                }else{
                    return fixed.replace('.', decimalSeparator);
                }
            };
 
            //inception
            format.create = currencyFormatter.create;
 
            return format;
        }
    };
 
    return currencyFormatter.create(2, '.', ',');
 
});