Skip to content

Instantly share code, notes, and snippets.

@tennox
Last active May 21, 2020 12:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tennox/92770bba1457de1a221bc5ca1462a6cb to your computer and use it in GitHub Desktop.
Save tennox/92770bba1457de1a221bc5ca1462a6cb to your computer and use it in GitHub Desktop.
Currency.js override with custom defaults
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'
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