/
formatValueDictionary.ts
77 lines (76 loc) 路 2.37 KB
/
formatValueDictionary.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
import {
foregroundBlue,
foregroundBrightGreen,
foregroundBrightRed,
foregroundYellow,
} from "@lou.codes/ansi";
import { isArray } from "@lou.codes/constants/Array.js";
import { entries } from "@lou.codes/constants/Object.js";
import { EMPTY_STRING } from "@lou.codes/constants/empty.js";
import type { ReadOnlyRecord, TypeOfValue } from "@lou.codes/types";
import { formatValue } from "./formatValue.js";
/**
* Dictionary type->formatter to be used by `formatValue`.
*
* @category Output
*/
export const formatValueDictionary: ReadOnlyRecord<
TypeOfValue,
(value: unknown) => string
> = {
bigint: value => `${foregroundBrightGreen`${value}`}${foregroundBlue`n`}`,
boolean: value => foregroundBlue`${value}`,
function: () => foregroundYellow`Function`,
null: () => foregroundBlue`null`,
number: value => foregroundBrightGreen`${value}`,
object: value =>
isArray(value) ?
`${foregroundBrightGreen`Array`}([ ${value
.map(formatValue)
.join(", ")} ])`
: value instanceof Date ?
`${foregroundBrightGreen`Date`}(${foregroundBrightRed`"${value.toISOString()}"`})`
: value instanceof RegExp ?
`${foregroundBrightGreen`RegExp`}(${foregroundBrightRed(
value.toString(),
)})`
: value instanceof URL ?
`${foregroundBrightGreen`URL`}(${foregroundBrightRed`"${value.href}"`})`
: value instanceof Error ?
`${foregroundBrightGreen(
value.name,
)}(${foregroundBrightRed`"${value.message}"`})`
: `${foregroundBrightGreen(
(
value as {
readonly constructor?: { readonly name: string };
}
).constructor?.name ?? "Object",
)}({ ${((
typeof (value as ReadonlyMap<unknown, unknown>).entries ===
"function"
) ?
[...(value as ReadonlyMap<unknown, unknown>).entries()]
: entries(value as ReadOnlyRecord)
)
.map(
([key, propertyValue]) =>
`${foregroundBrightRed`"${
key as string
}"`}: ${formatValue(propertyValue)}`,
)
.join(", ")} })`,
string: value =>
foregroundBrightRed`"${(value as string).replaceAll(
// eslint-disable-next-line no-control-regex
/[\u001B\u009B][[()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-ORZcf-nqry=><]/gu,
EMPTY_STRING,
)}"`,
symbol: value =>
foregroundBrightGreen`Symbol${
(value as symbol).description === undefined ?
EMPTY_STRING
: `(${foregroundBrightRed`"${(value as symbol).description}"`})`
}`,
undefined: () => foregroundBlue`undefined`,
};