/
applyFormatters.ts
52 lines (42 loc) · 1.72 KB
/
applyFormatters.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
/* eslint-disable import/no-extraneous-dependencies */
import type { IFormatter } from '@interfaces/IFormatter';
function applyFormatter(initialValue: string | boolean | number | Date, formatter: IFormatter) {
const orders = formatter.order ?? ['number', 'string', 'dateTime'];
const formatted: any = orders.reduce((processing, order) => {
// stage 01. number format processing
if (order === 'number' && formatter.number != null && typeof processing === 'number') {
return formatter.number(processing);
}
// stage 02. string format processing
if (
order === 'string' &&
formatter.string != null &&
(typeof processing === 'string' || typeof processing === 'boolean' || typeof processing === 'number')
) {
if (typeof processing === 'number' || typeof processing === 'boolean') {
return formatter.string(`${processing}`);
}
return formatter.string(processing);
}
// stage 03. date format processing
if (order === 'dateTime' && formatter.dateTime != null && processing instanceof Date) {
return formatter.dateTime(processing);
}
return processing;
}, initialValue);
return formatted;
}
export function applyFormatters(initialValue: string | Date | number | boolean, formatter: IFormatter): string;
export function applyFormatters(
initialValue: string[] | Date[] | number[] | boolean[],
formatter: IFormatter,
): string[];
export function applyFormatters(
initialValue: string | Date | number | boolean | string[] | Date[] | number[] | boolean[],
formatter: IFormatter,
) {
if (Array.isArray(initialValue)) {
return initialValue.map((value) => applyFormatter(value, formatter));
}
return applyFormatter(initialValue, formatter);
}