-
Notifications
You must be signed in to change notification settings - Fork 2.9k
/
LocaleDigitUtils.js
82 lines (74 loc) · 2.53 KB
/
LocaleDigitUtils.js
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
import invariant from 'invariant';
import _ from 'underscore';
import * as NumberFormatUtils from './NumberFormatUtils';
const STANDARD_DIGITS = Object.freeze(['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '.', '-', ',']);
const INDEX_DECIMAL = 10;
const INDEX_MINUS_SIGN = 11;
const INDEX_GROUP = 12;
const getLocaleDigits = _.memoize((locale) => {
const localeDigits = _.clone(STANDARD_DIGITS);
for (let i = 0; i <= 9; i++) {
localeDigits[i] = NumberFormatUtils.format(locale, i);
}
_.forEach(NumberFormatUtils.formatToParts(locale, 1000000.5), (part) => {
switch (part.type) {
case 'decimal':
localeDigits[INDEX_DECIMAL] = part.value;
break;
case 'minusSign':
localeDigits[INDEX_MINUS_SIGN] = part.value;
break;
case 'group':
localeDigits[INDEX_GROUP] = part.value;
break;
default:
break;
}
});
return Object.freeze(localeDigits);
});
/**
* Checks whether the given character is a valid locale digit.
*
* @param {String} locale
* @param {String} char A single character
* @returns {Boolean}
*/
function isValidLocaleDigit(locale, char) {
return getLocaleDigits(locale).includes(char);
}
/**
* Gets the locale digit corresponding to a standard digit.
*
* @param {String} locale
* @param {String} digit Character of a single standard digit . It may be "0" ~ "9" (digits),
* "," (group separator), "." (decimal separator) or "-" (minus sign).
* @returns {String}
*
* @throws If `digit` is not a valid standard digit.
*/
function toLocaleDigit(locale, digit) {
const index = _.indexOf(STANDARD_DIGITS, digit);
invariant(index > -1, `"${digit}" must be in ${JSON.stringify(STANDARD_DIGITS)}`);
return getLocaleDigits(locale)[index];
}
/**
* Gets the standard digit corresponding to a locale digit.
*
* @param {String} locale
* @param {String} localeDigit Character of a single locale digit. It may be **the localized version** of
* "0" ~ "9" (digits), "," (group separator), "." (decimal separator) or "-" (minus sign).
* @returns {String}
*
* @throws If `localeDigit` is not a valid locale digit.
*/
function fromLocaleDigit(locale, localeDigit) {
const index = _.indexOf(getLocaleDigits(locale), localeDigit);
invariant(index > -1, `"${localeDigit}" must be in ${JSON.stringify(getLocaleDigits(locale))}`);
return STANDARD_DIGITS[index];
}
export {
isValidLocaleDigit,
toLocaleDigit,
fromLocaleDigit,
};