-
Notifications
You must be signed in to change notification settings - Fork 220
/
i18n.ts
828 lines (718 loc) · 22.5 KB
/
i18n.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
import {
formatDate,
isFutureDate,
isLessThanOneHourAgo,
isLessThanOneMinuteAgo,
isLessThanOneWeekAgo,
isLessThanOneYearAgo,
isToday,
isTomorrow,
isYesterday,
TimeUnit,
isLessThanOneWeekAway,
isLessThanOneYearAway,
} from '@shopify/dates';
import {
formatName as importedFormatName,
abbreviateName as importedAbbreviateName,
abbreviateBusinessName as importedAbbreviateBusinessName,
hasFamilyNameGivenNameOrdering as importedHasFamilyNameGivenNameOrdering,
} from '@shopify/name';
import {memoize} from '@shopify/function-enhancers';
import {languageFromLocale, regionFromLocale} from '@shopify/i18n';
import type {
I18nDetails,
PrimitiveReplacementDictionary,
ComplexReplacementDictionary,
TranslationDictionary,
} from './types';
import {LanguageDirection} from './types';
import type {Weekday} from './constants';
import {
dateStyle,
DateStyle,
DEFAULT_WEEK_START_DAY,
WEEK_START_DAYS,
RTL_LANGUAGES,
currencyDecimalPlaces,
DEFAULT_DECIMAL_PLACES,
CurrencyShortFormException,
UnicodeCharacterSet,
} from './constants';
import type {I18nError} from './errors';
import {MissingCurrencyCodeError, MissingCountryError} from './errors';
import type {TranslateOptions as RootTranslateOptions} from './utilities';
import {
getCurrencySymbol,
translate,
getTranslationTree,
memoizedNumberFormatter,
memoizedPluralRules,
convertFirstSpaceToNonBreakingSpace,
identifyScripts,
} from './utilities';
export interface NumberFormatOptions extends Intl.NumberFormatOptions {
as?: 'decimal' | 'currency' | 'percent';
precision?: number;
}
export interface CurrencyFormatOptions extends NumberFormatOptions {
form?: 'auto' | 'short' | 'explicit' | 'none';
}
export interface PercentageFormatOptions extends Intl.NumberFormatOptions {
percentageSignDisplay?: 'auto' | 'never';
}
export interface TranslateOptions {
scope: RootTranslateOptions<any>['scope'];
}
// Used for currencies that don't use fractional units (eg. JPY)
const PERIOD = '.';
const NEGATIVE_SIGN = '-';
const REGEX_DIGITS = /\d/g;
const REGEX_NON_DIGITS = /\D/g;
const REGEX_PERIODS = /\./g;
export class I18n {
readonly locale: string;
readonly pseudolocalize: boolean | string;
readonly defaultCountry?: string;
readonly defaultCurrency?: string;
readonly defaultTimezone?: string;
readonly defaultInterpolate?: RegExp;
readonly onError: NonNullable<I18nDetails['onError']>;
readonly loading: boolean;
get language() {
return languageFromLocale(this.locale);
}
get region() {
return regionFromLocale(this.locale);
}
/**
* @deprecated Use I18n#region instead.
*/
get countryCode() {
return regionFromLocale(this.locale);
}
get languageDirection() {
return RTL_LANGUAGES.includes(this.language)
? LanguageDirection.Rtl
: LanguageDirection.Ltr;
}
get isRtlLanguage() {
return this.languageDirection === LanguageDirection.Rtl;
}
get isLtrLanguage() {
return this.languageDirection === LanguageDirection.Ltr;
}
constructor(
public readonly translations: TranslationDictionary[],
{
locale,
currency,
timezone,
country,
pseudolocalize = false,
onError,
loading,
interpolate,
}: I18nDetails & {loading?: boolean},
) {
this.locale = locale;
this.defaultCountry = country;
this.defaultCurrency = currency;
this.defaultTimezone = timezone;
this.pseudolocalize = pseudolocalize;
this.defaultInterpolate = interpolate;
this.onError = onError || this.defaultOnError;
this.loading = loading || false;
}
translate(
id: string,
options: TranslateOptions,
replacements?: PrimitiveReplacementDictionary,
): string;
translate(
id: string,
options: TranslateOptions,
replacements?: ComplexReplacementDictionary,
): React.ReactElement<any>;
translate(id: string, replacements?: PrimitiveReplacementDictionary): string;
translate(
id: string,
replacements?: ComplexReplacementDictionary,
): React.ReactElement<any>;
translate(
id: string,
optionsOrReplacements?:
| TranslateOptions
| PrimitiveReplacementDictionary
| ComplexReplacementDictionary,
replacements?:
| PrimitiveReplacementDictionary
| ComplexReplacementDictionary,
): any {
const {pseudolocalize, defaultInterpolate} = this;
let normalizedOptions: RootTranslateOptions<
PrimitiveReplacementDictionary | ComplexReplacementDictionary
>;
const defaultOptions: RootTranslateOptions = {
pseudotranslate: pseudolocalize,
interpolate: defaultInterpolate,
};
if (optionsOrReplacements == null) {
normalizedOptions = defaultOptions;
} else if (this.isTranslateOptions(optionsOrReplacements)) {
normalizedOptions = {
...defaultOptions,
...optionsOrReplacements,
replacements,
};
} else {
normalizedOptions = {
...defaultOptions,
replacements: optionsOrReplacements,
};
}
try {
return translate(id, normalizedOptions, this.translations, this.locale);
} catch (error) {
this.onError(error as I18nError);
return '';
}
}
getTranslationTree(
id: string,
replacements?:
| PrimitiveReplacementDictionary
| ComplexReplacementDictionary,
): string | TranslationDictionary {
try {
if (!replacements) {
return getTranslationTree(id, this.translations, this.locale);
}
return getTranslationTree(
id,
this.translations,
this.locale,
replacements,
);
} catch (error) {
this.onError(error as I18nError);
return '';
}
}
translationKeyExists(id: string, absolute = false) {
try {
const result = getTranslationTree(id, this.translations, this.locale);
if (absolute) return typeof result === 'string';
return true;
} catch (error) {
return false;
}
}
formatNumber(
amount: number,
{as, precision, ...options}: NumberFormatOptions = {},
) {
const {locale, defaultCurrency: currency} = this;
if (as === 'currency' && currency == null && options.currency == null) {
this.onError(
new MissingCurrencyCodeError(
`formatNumber(amount, {as: 'currency'}) cannot be called without a currency code.`,
),
);
return '';
}
return memoizedNumberFormatter(locale, {
style: as,
maximumFractionDigits: precision,
currency,
...options,
}).format(amount);
}
unformatNumber(input: string): string {
const {decimalSymbol} = this.numberSymbols();
const normalizedValue = this.normalizedNumber(input, decimalSymbol);
return normalizedValue === '' ? '' : parseFloat(normalizedValue).toString();
}
formatCurrency(
amount: number,
{form, ...options}: CurrencyFormatOptions = {},
) {
switch (form) {
case 'auto':
return this.formatCurrencyAuto(amount, options);
case 'explicit':
return this.formatCurrencyExplicit(amount, options);
case 'short':
return this.formatCurrencyShort(amount, options);
case 'none':
return this.formatCurrencyNone(amount, options);
default:
return this.formatCurrencyAuto(amount, options);
}
}
unformatCurrency(input: string, currencyCode: string): string {
const {decimalSymbol} = this.numberSymbols();
const decimalPlaces = currencyDecimalPlaces.get(currencyCode.toUpperCase());
const normalizedValue = this.normalizedNumber(
input,
decimalSymbol,
decimalPlaces,
);
if (normalizedValue === '') {
return '';
}
if (decimalPlaces === 0) {
const roundedAmount = parseFloat(normalizedValue).toFixed(0);
return `${roundedAmount}.${'0'.repeat(DEFAULT_DECIMAL_PLACES)}`;
}
return parseFloat(normalizedValue).toFixed(decimalPlaces);
}
formatPercentage(amount: number, options: PercentageFormatOptions = {}) {
const {percentageSignDisplay = 'auto', ...otherOptions} = options;
if (percentageSignDisplay === 'auto') {
return this.formatNumber(amount, {as: 'percent', ...otherOptions});
}
const {locale} = this;
const parts = memoizedNumberFormatter(locale, {
style: 'percent',
...otherOptions,
}).formatToParts(amount);
return parts
.filter((part) => part.type !== 'literal' && part.type !== 'percentSign')
.map((part) => part.value)
.join('');
}
formatDate(
date: Date,
options: Intl.DateTimeFormatOptions & {style?: DateStyle} = {},
): string {
const {locale, defaultTimezone} = this;
const {timeZone = defaultTimezone} = options;
const {style = undefined, ...formatOptions} = options || {};
if (style) {
switch (style) {
case DateStyle.Humanize:
return this.humanizeDate(date, {...formatOptions, timeZone});
case DateStyle.DateTime:
return this.formatDateTime(date, {
...formatOptions,
timeZone,
...dateStyle[style],
});
default:
return this.formatDate(date, {...formatOptions, ...dateStyle[style]});
}
}
return formatDate(date, locale, {...formatOptions, timeZone});
}
ordinal(amount: number) {
const {locale} = this;
const group = memoizedPluralRules(locale, {type: 'ordinal'}).select(amount);
return this.translate(group, {scope: 'ordinal'}, {amount});
}
weekStartDay(argCountry?: I18n['defaultCountry']): Weekday {
const country = argCountry || this.defaultCountry;
if (!country) {
throw new MissingCountryError(
'weekStartDay() cannot be called without a country code.',
);
}
return WEEK_START_DAYS.get(country) || DEFAULT_WEEK_START_DAY;
}
getCurrencySymbol = (currencyCode?: string, locale: string = this.locale) => {
const currency = currencyCode || this.defaultCurrency;
if (currency == null) {
throw new MissingCurrencyCodeError(
'formatCurrency cannot be called without a currency code.',
);
}
return this.getShortCurrencySymbol(currency, locale);
};
/**
* @deprecated Replace usage of `i18n.getCurrencySymbolLocalized(locale, currency)` with `i18n.getCurrencySymbol(currency, locale)`
*/
getCurrencySymbolLocalized(locale: string, currency: string) {
return this.getShortCurrencySymbol(currency, locale);
}
formatName(
firstName?: string,
lastName?: string,
options?: {full?: boolean},
) {
return importedFormatName({
name: {givenName: firstName, familyName: lastName},
locale: this.locale,
options,
});
}
abbreviateName({
firstName,
lastName,
idealMaxLength = 3,
}: {
firstName?: string;
lastName?: string;
idealMaxLength?: number;
}) {
return importedAbbreviateName({
name: {
givenName: firstName,
familyName: lastName,
},
locale: this.locale,
options: {idealMaxLength},
});
}
abbreviateBusinessName({
name,
idealMaxLength = 3,
}: {
name: string;
idealMaxLength?: number;
}) {
return importedAbbreviateBusinessName({
name,
idealMaxLength,
});
}
identifyScript(text: string) {
return identifyScripts(text);
}
hasEasternNameOrderFormatter() {
return importedHasFamilyNameGivenNameOrdering(this.locale);
}
// eslint-disable-next-line @typescript-eslint/member-ordering
numberSymbols = memoize(() => {
const formattedNumber = this.formatNumber(123456.7, {
maximumFractionDigits: 1,
minimumFractionDigits: 1,
});
let thousandSymbol;
let decimalSymbol;
for (const char of formattedNumber) {
if (isNaN(parseInt(char, 10))) {
if (thousandSymbol) decimalSymbol = char;
else thousandSymbol = char;
}
}
return {thousandSymbol, decimalSymbol};
});
private formatCurrencyAuto(
amount: number,
options: Intl.NumberFormatOptions = {},
): string {
// use the short format if we can't determine a currency match, or if the
// currencies match, use explicit when the currencies definitively do not
// match.
const formatShort =
options.currency == null ||
this.defaultCurrency == null ||
options.currency === this.defaultCurrency;
return formatShort
? this.formatCurrencyShort(amount, options)
: this.formatCurrencyExplicit(amount, options);
}
private formatCurrencyExplicit(
amount: number,
options: Intl.NumberFormatOptions = {},
): string {
const value = this.formatCurrencyShort(amount, options);
const isoCode = options.currency || this.defaultCurrency || '';
if (value.includes(isoCode)) {
return value;
}
return `${value} ${isoCode}`;
}
private formatCurrencyShort(
amount: number,
options: NumberFormatOptions = {},
): string {
const formattedAmount = this.formatCurrencyNone(amount, options);
const negativeRegex = new RegExp(
`${UnicodeCharacterSet.DirectionControl}*${UnicodeCharacterSet.Negative}`,
'g',
);
const negativeMatch = negativeRegex.exec(formattedAmount)?.shift() || '';
const shortSymbol = this.getShortCurrencySymbol(options.currency);
const formattedWithSymbol = shortSymbol.prefixed
? `${shortSymbol.symbol}${formattedAmount}`
: `${formattedAmount}${shortSymbol.symbol}`;
return `${negativeMatch}${formattedWithSymbol.replace(negativeMatch, '')}`;
}
private formatCurrencyNone(
amount: number,
options: NumberFormatOptions = {},
): string {
const {locale} = this;
let adjustedPrecision = options.precision;
if (adjustedPrecision === undefined) {
const currency = options.currency || this.defaultCurrency || '';
adjustedPrecision = currencyDecimalPlaces.get(currency.toUpperCase());
}
return memoizedNumberFormatter(locale, {
style: 'decimal',
minimumFractionDigits: adjustedPrecision,
maximumFractionDigits: adjustedPrecision,
...options,
}).format(amount);
}
// Intl.NumberFormat sometimes annotates the "currency symbol" with a country code.
// For example, in locale 'fr-FR', 'USD' is given the "symbol" of " $US".
// This method strips out the country-code annotation, if there is one.
// (So, for 'fr-FR' and 'USD', the return value would be " $").
//
// For other currencies, e.g. CHF and OMR, the "symbol" is the ISO currency code.
// In those cases, we return the full currency code without stripping the country.
private getShortCurrencySymbol(
currency: string = this.defaultCurrency || '',
locale: string = this.locale,
) {
const regionCode = currency.substring(0, 2);
let shortSymbolResult: {symbol: string; prefixed: boolean};
// currencyDisplay: 'narrowSymbol' was added to iOS in v14.5. See https://caniuse.com/?search=currencydisplay
// We still support ios 12/13, so we need to check if this works and fallback to the default if not
// All other supported browsers understand narrowSymbol, so once our minimum iOS version is updated we can remove this fallback
try {
shortSymbolResult = getCurrencySymbol(locale, {
currency,
currencyDisplay: 'narrowSymbol',
});
} catch {
shortSymbolResult = getCurrencySymbol(locale, {currency});
}
if (currency in CurrencyShortFormException) {
return {
symbol: CurrencyShortFormException[currency],
prefixed: shortSymbolResult.prefixed,
};
}
const shortSymbol = shortSymbolResult.symbol.replace(regionCode, '');
const alphabeticCharacters = /[A-Za-zÀ-ÖØ-öø-ÿĀ-ɏḂ-ỳ]/;
return alphabeticCharacters.exec(shortSymbol)
? shortSymbolResult
: {symbol: shortSymbol, prefixed: shortSymbolResult.prefixed};
}
private humanizeDate(date: Date, options?: Intl.DateTimeFormatOptions) {
return isFutureDate(date)
? this.humanizeFutureDate(date, options)
: this.humanizePastDate(date, options);
}
private formatDateTime(
date: Date,
options: Intl.DateTimeFormatOptions,
): string {
const {defaultTimezone} = this;
const {timeZone = defaultTimezone} = options;
return this.translate('date.humanize.lessThanOneYearAway', {
date: this.getDateFromDate(date, {
...options,
timeZone,
}),
time: this.getTimeFromDate(date, {
...options,
timeZone,
}),
});
}
private humanizePastDate(date: Date, options?: Intl.DateTimeFormatOptions) {
if (isLessThanOneMinuteAgo(date)) {
return this.translate('date.humanize.lessThanOneMinuteAgo');
}
if (isLessThanOneHourAgo(date)) {
const now = new Date();
const minutes = Math.floor(
(now.getTime() - date.getTime()) / TimeUnit.Minute,
);
return this.translate('date.humanize.lessThanOneHourAgo', {
count: minutes,
});
}
const timeZone = options?.timeZone;
const time = this.getTimeFromDate(date, options);
if (isToday(date, timeZone)) {
return time;
}
if (isYesterday(date, timeZone)) {
return this.translate('date.humanize.yesterday', {time});
}
if (isLessThanOneWeekAgo(date)) {
const weekday = this.getWeekdayFromDate(date, options);
return this.translate('date.humanize.lessThanOneWeekAgo', {
weekday,
time,
});
}
if (isLessThanOneYearAgo(date)) {
const monthDay = this.getMonthDayFromDate(date, options);
return this.translate('date.humanize.lessThanOneYearAgo', {
date: monthDay,
time,
});
}
return this.formatDate(date, {
...options,
style: DateStyle.Short,
});
}
private humanizeFutureDate(date: Date, options?: Intl.DateTimeFormatOptions) {
const timeZone = options?.timeZone;
const time = this.getTimeFromDate(date, options);
if (isToday(date, timeZone)) {
return this.translate('date.humanize.today', {time});
}
if (isTomorrow(date, timeZone)) {
return this.translate('date.humanize.tomorrow', {time});
}
if (isLessThanOneWeekAway(date)) {
const weekday = this.getWeekdayFromDate(date, options);
return this.translate('date.humanize.lessThanOneWeekAway', {
weekday,
time,
});
}
if (isLessThanOneYearAway(date)) {
const monthDay = this.getMonthDayFromDate(date, options);
return this.translate('date.humanize.lessThanOneYearAway', {
date: monthDay,
time,
});
}
return this.formatDate(date, {
...options,
style: DateStyle.Short,
});
}
private getTimeZone(
date: Date,
options?: Intl.DateTimeFormatOptions,
): string {
const {localeMatcher, formatMatcher, timeZone} = options || {};
const hourZone = this.formatDate(date, {
localeMatcher,
formatMatcher,
timeZone,
hour12: false,
timeZoneName: 'short',
hour: 'numeric',
});
const zoneMatchGroup = /\s([\w()+\-:.]+$)/.exec(hourZone);
return zoneMatchGroup ? zoneMatchGroup[1] : '';
}
private getDateFromDate(date: Date, options?: Intl.DateTimeFormatOptions) {
const {
localeMatcher,
formatMatcher,
weekday,
day,
month,
year,
era,
timeZone,
timeZoneName,
} = options || {};
const formattedDate = this.formatDate(date, {
localeMatcher,
formatMatcher,
weekday,
day,
month,
year,
era,
timeZone,
timeZoneName: timeZoneName === 'short' ? undefined : timeZoneName,
});
return formattedDate;
}
private getTimeFromDate(date: Date, options?: Intl.DateTimeFormatOptions) {
const {localeMatcher, formatMatcher, hour12, timeZone, timeZoneName} =
options || {};
const formattedTime = this.formatDate(date, {
localeMatcher,
formatMatcher,
hour12,
timeZone,
timeZoneName: timeZoneName === 'short' ? undefined : timeZoneName,
hour: 'numeric',
minute: '2-digit',
}).toLocaleLowerCase();
const time =
timeZoneName === 'short'
? `${formattedTime} ${this.getTimeZone(date, options)}`
: formattedTime;
return convertFirstSpaceToNonBreakingSpace(time);
}
private getWeekdayFromDate(date: Date, options?: Intl.DateTimeFormatOptions) {
const {localeMatcher, formatMatcher, hour12, timeZone} = options || {};
return this.formatDate(date, {
localeMatcher,
formatMatcher,
hour12,
timeZone,
weekday: 'long',
});
}
private getMonthDayFromDate(
date: Date,
options?: Intl.DateTimeFormatOptions,
) {
const {localeMatcher, formatMatcher, hour12, timeZone} = options || {};
return this.formatDate(date, {
localeMatcher,
formatMatcher,
hour12,
timeZone,
month: 'short',
day: 'numeric',
});
}
private normalizedNumber(
input: string,
decimalSymbol: string,
decimalPlaces: number = DEFAULT_DECIMAL_PLACES,
) {
const maximumDecimalPlaces = Math.max(
decimalPlaces,
DEFAULT_DECIMAL_PLACES,
);
const lastIndexOfPeriod = input.lastIndexOf(PERIOD);
let lastIndexOfDecimal = input.lastIndexOf(decimalSymbol);
// For locales that do not use period as the decimal symbol, users may still input a period
// and expect it to be treated as the decimal symbol for their locale.
if (
decimalSymbol !== PERIOD &&
(input.match(REGEX_PERIODS) || []).length === 1 &&
this.decimalValue(input, lastIndexOfPeriod).length <= maximumDecimalPlaces
) {
lastIndexOfDecimal = lastIndexOfPeriod;
}
const integerValue = this.integerValue(input, lastIndexOfDecimal);
const decimalValue = this.decimalValue(input, lastIndexOfDecimal);
const negativeRegex = new RegExp(
`^(${UnicodeCharacterSet.DirectionControl}|\\s)*${UnicodeCharacterSet.Negative}`,
'u',
);
const negativeSign = input.match(negativeRegex) ? NEGATIVE_SIGN : '';
const normalizedDecimal = lastIndexOfDecimal === -1 ? '' : PERIOD;
const normalizedValue = `${negativeSign}${integerValue}${normalizedDecimal}${decimalValue}`;
return normalizedValue.match(REGEX_DIGITS) ? normalizedValue : '';
}
private integerValue(input: string, lastIndexOfDecimal: number) {
return input.substring(0, lastIndexOfDecimal).replace(REGEX_NON_DIGITS, '');
}
private decimalValue(input: string, lastIndexOfDecimal: number) {
return input
.substring(lastIndexOfDecimal + 1)
.replace(REGEX_NON_DIGITS, '');
}
private isTranslateOptions(
object:
| TranslateOptions
| PrimitiveReplacementDictionary
| ComplexReplacementDictionary,
): object is TranslateOptions {
return 'scope' in object;
}
private defaultOnError(error: I18nError) {
throw error;
}
}