1
+ 'use strict' ;
2
+ const utils = require ( 'handlebars-utils' ) ;
3
+
4
+ const factory = ( ) => {
5
+ return function ( price , locale = 'fr' ) {
6
+ if ( ! utils . isObject ( price ) || ! utils . isString ( price . currency )
7
+ || isNaN ( price . value ) || ! utils . isString ( price . formatted ) ) {
8
+ // Return empty string if this does not appear to be a price object
9
+ return ''
10
+ }
11
+
12
+ if ( ! utils . isString ( locale ) || locale . length < 2 ) {
13
+ // Valid browser language strings are at least two characters
14
+ // https://www.metamodpro.com/browser-language-codes
15
+ // If provided locale is less than two characters (or not a string),
16
+ // return the normal formatted price
17
+ return price . formatted ;
18
+ }
19
+
20
+ // Detect ICU support
21
+ const hasFullICU = ( ( ) => {
22
+ try {
23
+ const january = new Date ( 9e8 ) ;
24
+ const spanish = new Intl . DateTimeFormat ( 'es' , { month : 'long' } ) ;
25
+ return spanish . format ( january ) === 'enero' ;
26
+ } catch ( err ) {
27
+ return false ;
28
+ }
29
+ } ) ( ) ;
30
+
31
+ // If the if full ICU is not installed, fall back to normal price
32
+ if ( ! hasFullICU ) {
33
+ return price . formatted ;
34
+ }
35
+
36
+ // Try to format the price to the provided locale,
37
+ // but if anything goes wrong,
38
+ // just return the usual price
39
+ // Could happen if the full ICU is not installed,
40
+ // or if an invalid locale is provided.
41
+ try {
42
+ return new Intl . NumberFormat (
43
+ locale , { style : 'currency' , currency : price . currency }
44
+ ) . format ( price . value ) ;
45
+ }
46
+ catch ( err ) {
47
+ return price . formatted ;
48
+ }
49
+ } ;
50
+ } ;
51
+
52
+ module . exports = [ {
53
+ name : 'localizePrice' ,
54
+ factory : factory ,
55
+ } ] ;
0 commit comments