-
Notifications
You must be signed in to change notification settings - Fork 11
Expand file tree
/
Copy pathformatterUtils.ts
More file actions
197 lines (153 loc) · 7.48 KB
/
Copy pathformatterUtils.ts
File metadata and controls
197 lines (153 loc) · 7.48 KB
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
import { DateTime, Duration, type DurationUnit } from 'luxon';
import {
DateFormat,
NumberFormat,
dateFormats,
numberFormats,
type DynamicOption,
type INumberFormat,
} from './formatterUtilsDefinitions';
export interface IFormatNumberOptions extends INumberFormat {
/**
* Number format to use.
* @default GENERIC_LONG
*/
format?: NumberFormat;
}
export interface IFormatDateOptions {
/**
* Date format to use.
* @default YEAR_MONTH_DAY_TIME
*/
format?: DateFormat;
}
const cache: Record<string, Intl.NumberFormat | undefined> = {};
class FormatterUtils {
numberLocale = 'en';
dateLocale = 'en';
currencyLocale = 'USD';
private baseSymbolRanges = [
{ value: 1e15, symbol: (value: number) => ` x 10^${(this.getDecimalPlaces(value) - 1).toString()}` },
{ value: 1e12, symbol: () => 'T' },
{ value: 1e9, symbol: () => 'B' },
{ value: 1e6, symbol: () => 'M' },
{ value: 1e3, symbol: () => 'K' },
];
private relativeDateOrder: DurationUnit[] = ['years', 'months', 'days', 'hours', 'minutes', 'seconds'];
formatNumber = (value: number | string | null | undefined, options: IFormatNumberOptions = {}): string | null => {
const { format = NumberFormat.GENERIC_LONG, ...otherOptions } = options;
const mergedOptions = { ...numberFormats[format], ...otherOptions };
const {
fixedFractionDigits,
maxFractionDigits,
minFractionDigits,
maxSignificantDigits,
useBaseSymbol,
isCurrency,
isPercentage,
withSign,
fallback,
displayFallback,
} = mergedOptions;
const parsedValue = typeof value === 'number' ? value : parseFloat(value ?? '');
const fallbackValue = this.getDynamicOption(parsedValue, fallback);
if (Boolean(displayFallback?.(parsedValue)) || isNaN(parsedValue)) {
return fallbackValue ?? null;
}
let processedValue = isPercentage ? parsedValue * 100 : parsedValue;
const fixedFractionDigitsOption = this.getDynamicOption(processedValue, fixedFractionDigits);
const maxSignificantDigitsOption = this.getDynamicOption(processedValue, maxSignificantDigits);
const maxDigitsFallback = fixedFractionDigitsOption ?? maxFractionDigits;
const maxDigits = maxSignificantDigitsOption
? this.significantDigitsToFractionDigits(processedValue, maxSignificantDigitsOption, maxDigitsFallback)
: maxDigitsFallback;
const minDigits = fixedFractionDigitsOption ?? minFractionDigits;
const cacheKey = `number/${this.numberLocale}/${this.currencyLocale}/${isCurrency?.toString() ?? '-'}/${maxDigits?.toString() ?? '-'}/${minDigits?.toString() ?? '-'}`;
cache[cacheKey] ??= new Intl.NumberFormat(this.numberLocale, {
style: isCurrency ? 'currency' : undefined,
currency: isCurrency ? this.currencyLocale : undefined,
maximumFractionDigits: maxDigits,
minimumFractionDigits: minDigits,
});
const baseRange = this.baseSymbolRanges.find((range) => Math.abs(processedValue) >= range.value);
const baseRangeDenominator =
processedValue > 1e15 ? 10 ** (this.getDecimalPlaces(processedValue) - 1) : (baseRange?.value ?? 1);
if (useBaseSymbol) {
processedValue = processedValue / baseRangeDenominator;
}
let formattedValue = cache[cacheKey].format(processedValue);
if (withSign && processedValue > 0) {
formattedValue = `+${formattedValue}`;
}
if (useBaseSymbol && baseRange != null) {
formattedValue = `${formattedValue}${baseRange.symbol(parsedValue)}`;
}
if (isPercentage) {
return `${formattedValue}%`;
}
return formattedValue;
};
formatDate = (value: DateTime | number | string | undefined, options: IFormatDateOptions = {}) => {
const { format = DateFormat.YEAR_MONTH_DAY_TIME } = options;
const { useRelativeCalendar, useRelativeDate, isDuration, ...dateFormat } = dateFormats[format];
if (value == null) {
return null;
}
const dateObject =
typeof value === 'string'
? DateTime.fromISO(value)
: typeof value === 'number'
? DateTime.fromMillis(value)
: value;
const shouldUseRelativeCalendar = useRelativeCalendar && this.isYesterdayTodayTomorrow(dateObject);
if (shouldUseRelativeCalendar) {
const relativeCalendarDate = dateObject.toRelativeCalendar({ locale: this.dateLocale })!;
const dateTime = dateObject.toLocaleString(
{ ...DateTime.TIME_SIMPLE, hourCycle: 'h23' },
{ locale: this.dateLocale },
);
const dateLiteral = this.getDateLiteral();
return useRelativeCalendar === 'with-time'
? `${relativeCalendarDate}${dateLiteral}${dateTime}`
: relativeCalendarDate;
}
if (useRelativeDate) {
const [unit, roundedDiff] = this.getRoundedDateUnitDiff(dateObject);
const roundedTarget = DateTime.now().plus({ [unit]: roundedDiff });
return roundedTarget.toRelative({ locale: this.dateLocale });
}
if (isDuration) {
const [unit, roundedDiff] = this.getRoundedDateUnitDiff(dateObject);
const roundedDuration = Duration.fromObject({ [unit]: roundedDiff }, { locale: this.dateLocale });
const processedDuration = roundedDuration.valueOf() < 0 ? roundedDuration.negate() : roundedDuration;
return processedDuration.toHuman();
}
return dateObject.toLocaleString({ ...dateFormat, hourCycle: 'h23' }, { locale: this.dateLocale });
};
private isYesterdayTodayTomorrow = (value: DateTime): boolean => {
const today = DateTime.local().startOf('day');
const datesToCheck = [today.minus({ day: 1 }), today, today.plus({ day: 1 })];
return datesToCheck.some((date) => date.hasSame(value, 'day'));
};
private getDateLiteral = () => {
const dateTimeFormat = new Intl.DateTimeFormat(this.dateLocale, DateTime.DATETIME_FULL);
const dateTimeParts = dateTimeFormat.formatToParts();
const hourPartIndex = dateTimeParts.findIndex((part) => part.type === 'hour');
const timeLiteral = dateTimeParts[hourPartIndex - 1] as Intl.DateTimeFormatPart | undefined;
return timeLiteral?.value ?? ', ';
};
private getDynamicOption = <TValue = number, TOptionValue extends string | number | boolean = number>(
value: TValue,
option?: DynamicOption<TValue, TOptionValue>,
): TOptionValue | undefined => (typeof option === 'function' ? option(value) : option);
private getDecimalPlaces = (value: number) => value.toString().split('.')[0].length;
private getRoundedDateUnitDiff = (target: DateTime): [DurationUnit, number] => {
const dateDiff = target.diffNow();
const unit = this.relativeDateOrder.find((unit) => Math.abs(dateDiff.as(unit)) >= 1) ?? 'seconds';
const roundedValue = Math.round(dateDiff.as(unit));
return [unit, roundedValue];
};
private significantDigitsToFractionDigits = (value: number, digits: number, fallback?: number) =>
value === 0 ? fallback : Math.floor(digits - Math.log10(Math.abs(value)));
}
export const formatterUtils = new FormatterUtils();