Last active
November 20, 2018 18:06
-
-
Save Clickys/f0c457adc677bedc0f552dd1f1ec7487 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* CASE-1: Valid string contains %v -> return an object. | |
* checkCurrencyFormat('%v') -> { pos: '%v', neg: '-%v', zero: '%v'} | |
* | |
* CASE-2: Invalid string -> return defaults object/convert it. | |
* checkCurrencyFormat('%s') -> If its the first time that runs it will replace defaults lib.settings.currency.format | |
* from string '%s%v' to an object { pos: '%s%v', neg: '%s-%v', zero: '%s%v'} and return it. | |
* | |
* Case-3: Valid object -> Return the object without mutating it | |
* checkCurrencyFormat( {pos: '%v'} ) -> { pos: '%v' } | |
* | |
* Case-4: Invalid object -> return defaults object/convert it. | |
* checkCurrencyFormat({}) -> If its the first time that runs it will replace defaults lib.settings.currency.format | |
* from string '%s%v' to an object { pos: '%s%v', neg: '%s-%v', zero: '%s%v'} and return it. | |
* | |
* Case-5: Function , could be anything of the above cases. | |
* checkCurrencyFormat(function() {}) -> depends what the function returns. | |
* | |
* Case-6: Undefined or null or falsy, would return/convert { pos: '%s%v', neg: '%s-%v', zero: '%s%v'} . | |
*/ | |
function checkCurrencyFormat(format) { | |
var defaults = lib.settings.currency.format; | |
// Allow function as format parameter (should return string or object): | |
if ( typeof format === "function" ) format = format(); | |
// Format can be a string, in which case `value` ("%v") must be present: | |
if ( isString( format ) && format.match("%v") ) { | |
// Create and return positive, negative and zero formats: | |
return { | |
pos : format, | |
neg : format.replace("-", "").replace("%v", "-%v"), | |
zero : format | |
}; | |
// If no format, or object is missing valid positive value, use defaults: | |
} else if ( !format || !format.pos || !format.pos.match("%v") ) { | |
// If defaults is a string, casts it to an object for faster checking next time: | |
return ( !isString( defaults ) ) ? defaults : lib.settings.currency.format = { | |
pos : defaults, | |
neg : defaults.replace("%v", "-%v"), | |
zero : defaults | |
}; | |
} | |
// Otherwise, assume format was fine: | |
return format; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment