Last active
May 21, 2020 12:01
-
-
Save tennox/92770bba1457de1a221bc5ca1462a6cb to your computer and use it in GitHub Desktop.
Currency.js override with custom defaults
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
import currency from 'currency.js'; | |
// Library docs: https://currency.js.org/ | |
// We create a custom constructor with custom config here | |
export function customCurrency(value, options) { | |
if (value === null || value === undefined) return value; // I don't like that it returns 0.00 | |
if (!(this instanceof customCurrency)) { // this enables calling the function without 'new' | |
return new customCurrency(value, options); | |
} | |
// Call the 'constructor' of currency.js on this | |
currency.call(this, value, { | |
errorOnInvalid: true, // otherwise, invalid values will be 0.00 | |
symbol: '€', | |
formatWithSymbol: true, | |
...options, | |
}); | |
} | |
customCurrency.prototype = currency.prototype; // enables check: 'x instanceof customCurrency' |
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
const c = customCurrency(1.23) || new customCurrency(1.23); // depending on preference | |
c.add(1.11) // 2.34 | |
c instanceof customCurrency // true | |
c instanceof require('currency.js') // true |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment