Skip to content

Commit 21d4ffa

Browse files
committed
Serialization improvements
1 parent 07158d0 commit 21d4ffa

File tree

1 file changed

+28
-10
lines changed

1 file changed

+28
-10
lines changed

website/src/js/playground.js

Lines changed: 28 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -94,15 +94,15 @@ function init() {
9494
if (typeof value === 'number' || typeof value === 'boolean' || value === undefined) return String(value);
9595
if (typeof value === 'function') return `[Function ${ value.name || 'anonymous' }]`;
9696

97+
if (value instanceof Promise) {
98+
return 'Promise { <pending> }';
99+
}
100+
97101
if (typeof value === 'object') {
98102
if (visited.has(value)) return '[Circular]';
99103
visited.add(value);
100104
}
101105

102-
if (value instanceof Promise) {
103-
return 'Promise { <pending> }';
104-
}
105-
106106
if (value instanceof Set) {
107107
const arr = Array.from(value, v => serializeLog(v, visited));
108108
return `Set {${ arr.join(', ') }}`;
@@ -141,13 +141,31 @@ function init() {
141141
}
142142

143143
if (typeof value === 'object') {
144-
const keys = Array.from(new Set([
144+
const isPlain = value.constructor === Object || Object.getPrototypeOf(value) === null;
145+
const allKeysSet = new Set([
145146
...Object.getOwnPropertyNames(value),
146-
...Object.getOwnPropertySymbols(value)
147-
]));
148-
if (!keys.length) return '{}';
149-
const props = keys.map(k => `${ JSON.stringify(k) }: ${ serializeLog(value[k], visited) }`);
150-
return `{${ props.join(', ') }}`;
147+
...Object.getOwnPropertySymbols(value),
148+
]);
149+
// eslint-disable-next-line no-restricted-syntax -- needed to enumerate prototype properties
150+
for (const k in value) allKeysSet.add(k);
151+
const keys = Array.from(allKeysSet);
152+
if (!keys.length) return isPlain ? '{}' : `${ value.constructor?.name || 'Object' } {}`;
153+
const props = keys.map(k => {
154+
const displayKey = typeof k === 'symbol' ? k.toString() : JSON.stringify(k);
155+
try {
156+
const v = value[k];
157+
if (typeof v === 'object' && v !== null) {
158+
if (Array.isArray(v)) return `${ displayKey }: [Array(${ v.length })]`;
159+
return `${ displayKey }: [object ${ v.constructor?.name || 'Object' }]`;
160+
}
161+
return `${ displayKey }: ${ serializeLog(v, visited) }`;
162+
} catch {
163+
return `${ displayKey }: [Thrown error]`;
164+
}
165+
});
166+
return isPlain
167+
? `{${ props.join(', ') }}`
168+
: `${ value.constructor?.name || 'Object' } {${ props.join(', ') }}`;
151169
}
152170

153171
return String(value);

0 commit comments

Comments
 (0)