Skip to content

Instantly share code, notes, and snippets.

@blia
Created March 15, 2017 17:46
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save blia/1c00a8ded585a0bb70992d8897a6f822 to your computer and use it in GitHub Desktop.
Save blia/1c00a8ded585a0bb70992d8897a6f822 to your computer and use it in GitHub Desktop.
let price = 234
, tax = price * 0.05;
function currency(strings, ...expressions) {
const regExp = /^:c(\((.+),(.+)\))?/;
const local = (string, value) => {
const [currency, locale] = regExp.exec(string).slice(2);
return value.toLocaleString(locale, { style: 'currency', currency });
}
const {raw, values} = strings.reduceRight(({raw, values}, string, i) => {
const value = expressions.pop();
const test = regExp.test(string);
return {
raw: test ? [string.replace(regExp, ""), ...raw] : [string, ...raw],
values: test ? [local(string, value), ...values] : i > 0 ? [value, ...values] : values
}
}, {raw: [], values: []});
return String.raw({raw}, ...values);
}
let message = currency`Товар стоит ${price + tax}:c(UAH,uk-ua), это вам не хрен собачий, а без налогов всего: ${price}:c(UAH,uk-ua). Так то.`;
console.log(message);
// Товар стоит 245,70 грн., это вам не хрен собачий, а без налогов всего: 234,00 грн.. Так то.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment