Skip to content

Commit ee23f63

Browse files
committed
Add "localizePrice" helper
1 parent 395533e commit ee23f63

File tree

2 files changed

+39
-0
lines changed

2 files changed

+39
-0
lines changed

helpers/localizePrice.js

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
'use strict';
2+
const common = require('./lib/common.js');
3+
4+
const factory = globals => {
5+
return function(price, locale) {
6+
7+
if (!common.isObject(price) || !common.isString(price.currency)
8+
|| isNaN(price.value) || !common.isString(price.formatted)) {
9+
// Return empty string if this does not appear to be a price object
10+
return ''
11+
}
12+
13+
if (!common.isString(locale) || locale.length < 2) {
14+
// Valid browser language strings are at least two characters
15+
// https://www.metamodpro.com/browser-language-codes
16+
// If provided locale is less than two characters (or not a string),
17+
// return the normal formatted price
18+
return price.formatted;
19+
}
20+
21+
// Try to format the price to the provided locale,
22+
// but if anything goes wrong,
23+
// just return the usual price
24+
try {
25+
return new Intl.NumberFormat(
26+
locale, { style: 'currency', currency: price.currency}
27+
).format(price.value);
28+
}
29+
catch {
30+
return price.formatted;
31+
}
32+
};
33+
};
34+
35+
module.exports = [{
36+
name: 'localizePrice',
37+
factory: factory,
38+
}];

spec/helpers.js

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -39,6 +39,7 @@ describe('helper registration', () => {
3939
'lang',
4040
'langJson',
4141
'limit',
42+
'localizePrice',
4243
'money',
4344
'nl2br',
4445
'or',

0 commit comments

Comments
 (0)