/
index.js
94 lines (71 loc) · 1.67 KB
/
index.js
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
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
const fixKey = (key) =>
/[^\w]/.test(key) || /\d/.test(key) ? `"${key}"` : key;
// END
function addTab(str) {
let res = str.replace(/\r\n/g, '\n');
res = res.replace(/\r/g, '\n');
const arr = res.split('\n');
const callback = (item, i) => {
const last = (arr.length - 1);
if (i === 0) {
return item;
}
if (i === last) {
item = ` ${item}`;
return item;
}
return ` ${item}`;
}
return arr.map(callback).join('\n');
}
function toStr(thing) {
if (thing === null) {
return 'null';
}
if (thing instanceof String) {
let i = 0;
let str = '';
while (thing[String(i)]) {
str += thing[String(i)];
i++;
}
return str;
}
if (Array.isArray(thing)) {
let toReturn = '[';
thing.forEach(
(value, i) => {
const comma = i === (thing.length - 1) ? '' : ', ';
toReturn += `${toStr(value)}${comma}`;
}
);
toReturn += ']';
return toReturn;
}
if (typeof thing === 'number' || typeof thing === 'function') {
return thing.toString();
}
if (typeof thing === 'object') {
let toReturn = '{';
const keys = Object.keys(thing);
keys.forEach(
(key, i) => {
const elm = thing[key];
let val = toStr(elm);
if (typeof elm === 'object') {
val = addTab(toStr(elm));
}
const comma = i === (keys.length - 1) ? '\n' : ',';
toReturn += `\n ${fixKey(key)}: ${val}${comma}`;
}
);
toReturn += '}';
return toReturn;
}
if (typeof thing === 'string') {
thing = thing.replace(/"/g, '\\"');
return `"${thing}"`;
}
return String(thing);
}
exports.toStr = toStr;