Skip to content

Commit a62408d

Browse files
committed
implement replacers
1 parent ad4a7bb commit a62408d

File tree

2 files changed

+26
-2
lines changed

2 files changed

+26
-2
lines changed

src/uneval.js

Lines changed: 25 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -15,14 +15,16 @@ const reserved =
1515
/**
1616
* Turn a value into the JavaScript that creates an equivalent value
1717
* @param {any} value
18-
* @param {(value: any) => string | void} replacer
18+
* @param {(value: any, callback: (value: any) => any) => string | void} [replacer]
1919
*/
2020
export function uneval(value, replacer) {
2121
const counts = new Map();
2222

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

26+
const custom = new Set();
27+
2628
/** @param {any} thing */
2729
function walk(thing) {
2830
if (typeof thing === 'function') {
@@ -37,6 +39,18 @@ export function uneval(value, replacer) {
3739

3840
counts.set(thing, 1);
3941

42+
if (replacer) {
43+
const str = replacer(thing, (child) => {
44+
walk(child);
45+
return '<pending>';
46+
});
47+
48+
if (typeof str === 'string') {
49+
custom.add(thing);
50+
return;
51+
}
52+
}
53+
4054
const type = get_type(thing);
4155

4256
switch (type) {
@@ -118,6 +132,11 @@ export function uneval(value, replacer) {
118132
return stringify_primitive(thing);
119133
}
120134

135+
if (custom.has(thing)) {
136+
const str = replacer(thing, stringify);
137+
if (typeof str === 'string') return str;
138+
}
139+
121140
const type = get_type(thing);
122141

123142
switch (type) {
@@ -175,6 +194,11 @@ export function uneval(value, replacer) {
175194
names.forEach((name, thing) => {
176195
params.push(name);
177196

197+
if (custom.has(thing)) {
198+
values.push(/** @type {string} */ (replacer(thing, stringify)));
199+
return;
200+
}
201+
178202
if (is_primitive(thing)) {
179203
values.push(stringify_primitive(thing));
180204
return;

test/test.js

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -412,7 +412,7 @@ for (const [name, tests] of Object.entries(fixtures)) {
412412
const test = uvu.suite(`uneval: ${name}`);
413413
for (const t of tests) {
414414
test(t.name, () => {
415-
const actual = uneval(t.value);
415+
const actual = uneval(t.value, t.replacer);
416416
const expected = t.js;
417417
assert.equal(actual, expected);
418418
});

0 commit comments

Comments
 (0)