UNPKG

ez-shp-storefront

Version:

A helper function collection for Shopify storefront.

63 lines (62 loc) 2.33 kB
export class MoneyFormatter { constructor() { } setMoneyFormat(format) { this.moneyFormat = format; return this; } getMoneyFormat() { return this.moneyFormat; } static getInstance() { if (!this.instance) { this.instance = new MoneyFormatter(); } return this.instance; } formatWithDelimiters(number, precision, thousands, decimal) { thousands = thousands || ','; decimal = decimal || '.'; if (isNaN(number) || number === null) { return '0'; } number = (number / 100.0).toFixed(precision); var parts = number.split('.'); var dollarsAmount = parts[0].replace(/(\d)(?=(\d\d\d)+(?!\d))/g, '$1' + thousands); var centsAmount = parts[1] ? decimal + parts[1] : ''; return dollarsAmount + centsAmount; } get(cents, format) { if (typeof cents === 'string') { cents = cents.replace('.', ''); } var value = ''; var placeholderRegex = /\{\{\s*(\w+)\s*\}\}/; var formatString = format || this.getMoneyFormat(); formatString = formatString.length < 2 ? this.getMoneyFormat() : formatString; const matches = formatString.match(placeholderRegex); const amountStr = matches && matches.length ? matches[1] : 'amount'; switch (amountStr) { case 'amount': value = this.formatWithDelimiters(cents, 2); break; case 'amount_no_decimals': value = this.formatWithDelimiters(cents, 0); break; case 'amount_with_comma_separator': value = this.formatWithDelimiters(cents, 2, '.', ','); break; case 'amount_no_decimals_with_comma_separator': value = this.formatWithDelimiters(cents, 0, '.', ','); break; case 'amount_no_decimals_with_space_separator': value = this.formatWithDelimiters(cents, 0, ' '); break; case 'amount_with_apostrophe_separator': value = this.formatWithDelimiters(cents, 2, "'"); break; } return formatString.replace(placeholderRegex, value); } } MoneyFormatter.instance = null;