Skip to content

Commit

Permalink
make it less clever and brittle
Browse files Browse the repository at this point in the history
  • Loading branch information
Rich-Harris committed Feb 10, 2023
1 parent a62408d commit 57a3234
Show file tree
Hide file tree
Showing 2 changed files with 7 additions and 11 deletions.
16 changes: 6 additions & 10 deletions src/uneval.js
Original file line number Diff line number Diff line change
Expand Up @@ -15,15 +15,15 @@ const reserved =
/**
* Turn a value into the JavaScript that creates an equivalent value
* @param {any} value
* @param {(value: any, callback: (value: any) => any) => string | void} [replacer]
* @param {(value: any) => string | void} [replacer]
*/
export function uneval(value, replacer) {
const counts = new Map();

/** @type {string[]} */
const keys = [];

const custom = new Set();
const custom = new Map();

/** @param {any} thing */
function walk(thing) {
Expand All @@ -40,13 +40,10 @@ export function uneval(value, replacer) {
counts.set(thing, 1);

if (replacer) {
const str = replacer(thing, (child) => {
walk(child);
return '<pending>';
});
const str = replacer(thing);

if (typeof str === 'string') {
custom.add(thing);
custom.set(thing, str);
return;
}
}
Expand Down Expand Up @@ -133,8 +130,7 @@ export function uneval(value, replacer) {
}

if (custom.has(thing)) {
const str = replacer(thing, stringify);
if (typeof str === 'string') return str;
return custom.get(thing);
}

const type = get_type(thing);
Expand Down Expand Up @@ -195,7 +191,7 @@ export function uneval(value, replacer) {
params.push(name);

if (custom.has(thing)) {
values.push(/** @type {string} */ (replacer(thing, stringify)));
values.push(/** @type {string} */ (custom.get(thing)));
return;
}

Expand Down
2 changes: 1 addition & 1 deletion test/test.js
Original file line number Diff line number Diff line change
Expand Up @@ -388,7 +388,7 @@ const fixtures = {
value: [instance, instance],
js: '(function(a){return [a,a]}(new Custom({answer:42})))',
json: '[[1,1],["Custom",2],{"answer":3},42]',
replacer: (value, uneval) => {
replacer: (value) => {
if (value instanceof Custom) {
return `new Custom(${uneval(value.value)})`;
}
Expand Down

0 comments on commit 57a3234

Please sign in to comment.