-
Notifications
You must be signed in to change notification settings - Fork 1
/
index.js
102 lines (93 loc) · 2.14 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
95
96
97
98
99
100
101
102
'use strict';
function stableStringifyImpl(value, cycles, keyOrIndex) {
if (value != null) {
var toJSON = value.toJSON;
if (typeof toJSON === 'function') {
value = toJSON.call(value, keyOrIndex);
}
}
if (typeof value === 'object') {
if (value instanceof Number) {
value = Number(value);
} else if (value instanceof String) {
value = String(value);
} else if (value instanceof Boolean) {
value = value.valueOf();
}
}
if (value === null) {
return 'null';
}
if (value === true) {
return 'true';
}
if (value === false) {
return 'false';
}
if (typeof value === 'string') {
return JSON.stringify(value);
}
if (typeof value === 'number') {
if (isFinite(value)) {
return String(value);
} else {
return 'null';
}
}
var i, str, comma;
if (Array.isArray(value)) {
if (cycles.has(value)) {
return '"[Circular]"';
} else {
cycles.add(value);
str = '[';
comma = false;
for (i = 0; i < value.length; ++i) {
var item = stableStringifyImpl(value[i], cycles, i);
if (comma) {
str += ',';
} else {
comma = true;
}
if (item === undefined) {
str += 'null';
} else {
str += item;
}
}
str += ']';
cycles.delete(value);
return str;
}
} else if (typeof value === 'object') {
if (cycles.has(value)) {
return '"[Circular]"';
} else {
cycles.add(value);
str = '{';
comma = false;
var keys = Object.keys(value).sort();
for (i = 0; i < keys.length; ++i) {
var key = keys[i];
var val = stableStringifyImpl(value[key], cycles, key);
if (val === undefined) {
continue;
}
if (comma) {
str += ',';
} else {
comma = true;
}
str += JSON.stringify(key) + ':' + val;
}
str += '}';
cycles.delete(value);
return str;
}
} else {
return undefined;
}
}
module.exports = function stableStringify(value) {
return stableStringifyImpl(value, new WeakSet(), '');
};