-
Notifications
You must be signed in to change notification settings - Fork 1.3k
/
should-polyfill.ts
84 lines (79 loc) · 2 KB
/
should-polyfill.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
import {match} from '@formatjs/intl-localematcher'
import {supportedLocales} from './supported-locales.generated'
/**
* Check if this is old Node that only supports en
* @returns
*/
function onlySupportsEn() {
return (
!(Intl.NumberFormat as any).polyfilled &&
!Intl.NumberFormat.supportedLocalesOf(['es']).length
)
}
/**
* Check if Intl.NumberFormat is ES2020 compatible.
* Caveat: we are not checking `toLocaleString`.
*
* @public
* @param unit unit to check
*/
function supportsES2020() {
try {
const s = new Intl.NumberFormat('en', {
style: 'unit',
unit: 'bit',
unitDisplay: 'long',
notation: 'scientific',
}).format(10000)
// Check for a plurality bug in environment that uses the older versions of ICU:
// https://unicode-org.atlassian.net/browse/ICU-13836
if (s !== '1E4 bits') {
return false
}
} catch (e) {
return false
}
return true
}
/**
* Check if Intl.NumberFormat is ES2020 compatible.
* Caveat: we are not checking `toLocaleString`.
*
* @public
* @param unit unit to check
*/
function supportsES2023() {
try {
const s = new Intl.NumberFormat('en', {
notation: 'compact',
minimumSignificantDigits: 3,
maximumSignificantDigits: 3,
minimumFractionDigits: 2,
maximumFractionDigits: 2,
// @ts-ignore TS types are old
roundingPriority: 'morePrecision',
}).format(1e8)
return s === '100.00M'
} catch (e) {
return false
}
}
function supportedLocalesOf(locale?: string | string[]) {
if (!locale) {
return true
}
const locales = Array.isArray(locale) ? locale : [locale]
return Intl.NumberFormat.supportedLocalesOf(locales).length === locales.length
}
export function shouldPolyfill(locale = 'en') {
if (
typeof Intl === 'undefined' ||
!('NumberFormat' in Intl) ||
!supportsES2020() ||
!supportsES2023() ||
onlySupportsEn() ||
!supportedLocalesOf(locale)
) {
return locale ? match([locale], supportedLocales, 'en') : undefined
}
}