Skip to content

Commit

Permalink
feat(repl): better stringification of Symbols
Browse files Browse the repository at this point in the history
  • Loading branch information
michaelfig committed May 12, 2021
1 parent bef7d37 commit 658cf1b
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 31 deletions.
14 changes: 3 additions & 11 deletions packages/vats/src/repl.js
Original file line number Diff line number Diff line change
Expand Up @@ -12,14 +12,6 @@ const UNJSONABLES = new Map([
[undefined, 'undefined'],
]);

for (const [name, { value }] of Object.entries(
Object.getOwnPropertyDescriptors(Symbol),
)) {
if (typeof value === 'symbol' && typeof name === 'string') {
UNJSONABLES.set(value, `Symbol(Symbol.${name})`);
}
}

// A REPL-specific JSON stringify.
export function stringify(
value,
Expand All @@ -32,13 +24,13 @@ export function stringify(
if (typeof value === 'bigint') {
return `${value}n`;
}
if (typeof value === 'symbol') {
return String(value);
}
const rawString = UNJSONABLES.get(value);
if (rawString) {
return rawString;
}
if (typeof value === 'symbol') {
return `Symbol(?)`;
}
return JSON.stringify(value, null, spaces);
}

Expand Down
31 changes: 11 additions & 20 deletions packages/vats/test/test-repl.js
Original file line number Diff line number Diff line change
Expand Up @@ -91,25 +91,16 @@ test('repl: Symbols', async t => {
let m = sentMessages.shift();

let histnum = 0;
for (const expr of ['asyncIterator', 'toStringTag', 'hasInstance'].map(
name => `Symbol.${name}`,
)) {
t.deepEqual(doEval(histnum, expr), {});
m = sentMessages.shift();
t.deepEqual(m.type, 'updateHistory');
t.is(sentMessages.length, 1);

t.is(m.histnum, histnum);
t.is(m.display, `working on eval(${expr})`);
m = sentMessages.shift();
t.is(m.type, 'updateHistory');
t.is(m.histnum, histnum);
t.is(m.display, `Symbol(${expr})`);
t.deepEqual(sentMessages, []);
histnum += 1;
}

for (const expr of [`Symbol.for('foo')`, `Symbol('foo')`]) {
const exprDisplays = [
'asyncIterator',
'toStringTag',
'hasInstance',
].map(name => [`Symbol.${name}`, `Symbol(Symbol.${name})`]);
exprDisplays.push(
[`Symbol.for('foo')`, `Symbol(foo)`],
[`Symbol('foo')`, `Symbol(foo)`],
);
for (const [expr, display] of exprDisplays) {
t.deepEqual(doEval(histnum, expr), {});
m = sentMessages.shift();
t.deepEqual(m.type, 'updateHistory');
Expand All @@ -120,7 +111,7 @@ test('repl: Symbols', async t => {
m = sentMessages.shift();
t.is(m.type, 'updateHistory');
t.is(m.histnum, histnum);
t.is(m.display, `Symbol(?)`);
t.is(m.display, display);
t.deepEqual(sentMessages, []);
histnum += 1;
}
Expand Down

0 comments on commit 658cf1b

Please sign in to comment.