-
-
Notifications
You must be signed in to change notification settings - Fork 15
Expand file tree
/
Copy pathstringify.ts
More file actions
36 lines (31 loc) · 1.02 KB
/
stringify.ts
File metadata and controls
36 lines (31 loc) · 1.02 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
import { quoteString } from "./quote";
import { Next, ToString } from "./types";
import { objectToString } from "./object";
import { functionToString } from "./function";
/**
* Stringify primitive values.
*/
const PRIMITIVE_TYPES: Record<string, ToString> = {
string: quoteString,
number: (value: number) => (Object.is(value, -0) ? "-0" : String(value)),
boolean: String,
symbol: (value: symbol, space: string, next: Next) => {
const key = Symbol.keyFor(value);
if (key !== undefined) return `Symbol.for(${next(key)})`;
// ES2018 `Symbol.description`.
return `Symbol(${next((value as any).description)})`;
},
bigint: (value: bigint, space: string, next: Next) => {
return `BigInt(${next(String(value))})`;
},
undefined: String,
object: objectToString,
function: functionToString,
};
/**
* Stringify a value recursively.
*/
export const toString: ToString = (value, space, next, key) => {
if (value === null) return "null";
return PRIMITIVE_TYPES[typeof value](value, space, next, key);
};