-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstringify.js
More file actions
56 lines (56 loc) · 1.75 KB
/
Copy pathstringify.js
File metadata and controls
56 lines (56 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
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.stringify = void 0;
const convertType = (obj, ignoreDataLoss) => {
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 = (obj, options = {}) => {
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 = {};
for (const [key, value] of Object.entries(obj)) {
tmpObj[key] = decent(value, options);
}
return tmpObj;
}
return convertType(obj, ignoreDataLoss);
};
const stringify = (obj, options) => {
return JSON.stringify(decent(obj, options));
};
exports.stringify = stringify;