|
1 | | -function isClass(obj) { |
2 | | - return obj.toString().startsWith("class "); |
3 | | -} |
4 | | - |
5 | | -function isGenerator(obj) { |
6 | | - return obj[Symbol.iterator] && |
7 | | - obj[Symbol.iterator].name === "[Symbol.iterator]" && |
8 | | - typeof obj.next === "function"; |
9 | | -} |
10 | | - |
11 | | -export function toJson(data, indent = 4) { |
12 | | - return JSON.stringify(data, (key, value) => { |
13 | | - switch(typeof value) { |
14 | | - case "function": |
15 | | - if(isClass(value)) { |
16 | | - return `[class ${value.name || key}]`; |
17 | | - } |
18 | | - return `[function ${value.name || key}]`; |
19 | | - |
20 | | - case "object": |
21 | | - if(isGenerator(value)) { |
22 | | - return `[generator ${key || "Generator"}]`; |
23 | | - } |
24 | | - if(Array.isArray(value)) { |
25 | | - return value; |
26 | | - } |
27 | | - let obj = {}; |
28 | | - for(const i in value) { |
29 | | - obj[i] = value[i]; |
30 | | - } |
31 | | - return obj; |
32 | | - |
33 | | - case "undefined": |
34 | | - return null; |
35 | | - |
36 | | - default: |
37 | | - return value; |
38 | | - } |
39 | | - }, indent); |
40 | | -} |
| 1 | +function isClass(obj) { |
| 2 | + return obj.toString().startsWith("class "); |
| 3 | +} |
| 4 | + |
| 5 | +function isGenerator(obj) { |
| 6 | + return obj[Symbol.iterator] && |
| 7 | + obj[Symbol.iterator].name === "[Symbol.iterator]" && |
| 8 | + typeof obj.next === "function"; |
| 9 | +} |
| 10 | + |
| 11 | +export default function toJson(data, indent = 4) { |
| 12 | + return JSON.stringify(data, (key, value) => { |
| 13 | + switch(typeof value) { |
| 14 | + case "function": |
| 15 | + if(isClass(value)) { |
| 16 | + return `[class ${value.name || key}]`; |
| 17 | + } |
| 18 | + return `[function ${value.name || key}]`; |
| 19 | + |
| 20 | + case "object": |
| 21 | + if(isGenerator(value)) { |
| 22 | + return `[generator ${key || "Generator"}]`; |
| 23 | + } |
| 24 | + if(Array.isArray(value)) { |
| 25 | + return value; |
| 26 | + } |
| 27 | + let obj = {}; |
| 28 | + for(const i in value) { |
| 29 | + obj[i] = value[i]; |
| 30 | + } |
| 31 | + return obj; |
| 32 | + |
| 33 | + case "undefined": |
| 34 | + return null; |
| 35 | + |
| 36 | + default: |
| 37 | + return value; |
| 38 | + } |
| 39 | + }, indent); |
| 40 | +} |
0 commit comments