-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstringify.ts
More file actions
61 lines (58 loc) · 1.75 KB
/
Copy pathstringify.ts
File metadata and controls
61 lines (58 loc) · 1.75 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
import { CustomStringify, StringifyType, TypedValue } from './types';
const convertType = (obj: unknown, ignoreDataLoss: boolean): TypedValue => {
if (obj === null) {
return { t: 'null' };
}
if (obj === undefined) {
return { t: 'undefined' };
}
if (obj instanceof Date) {
return { t: 'Date', v: obj.toISOString() };
}
switch (typeof obj) {
case 'bigint':
return { t: 'bigint', v: obj.toString() };
case 'boolean':
return { t: 'boolean', v: obj ? '1' : '0' };
case 'function':
if (!ignoreDataLoss) {
throw new Error('Function can not be stringified without data loss');
}
return { t: 'function' };
case 'number':
return { t: 'number', v: obj.toString() };
case 'string':
return { t: 'string', v: obj };
case 'symbol':
return { t: 'symbol', v: Symbol.keyFor(obj) };
}
throw new Error(`Unknown datatype: ${typeof obj}`);
};
const decent = <T extends string = StringifyType>(
obj: unknown,
options: { customStringify?: CustomStringify<T>; ignoreDataLoss?: boolean } = {}
): unknown => {
const { customStringify, ignoreDataLoss = false } = options;
if (customStringify) {
const tmpObj = customStringify(obj);
if (tmpObj) {
return tmpObj;
}
}
if (Array.isArray(obj)) {
return obj.map((obj) => decent(obj, options));
} else if (obj && typeof obj === 'object' && !(obj instanceof Date)) {
const tmpObj: { [key: string]: unknown } = {};
for (const [key, value] of Object.entries(obj)) {
tmpObj[key] = decent(value, options);
}
return tmpObj;
}
return convertType(obj, ignoreDataLoss);
};
export const stringify = <T = unknown, U extends string = StringifyType>(
obj: T,
options?: { customStringify?: CustomStringify<U>; ignoreDataLoss?: boolean }
): string => {
return JSON.stringify(decent(obj, options));
};