Skip to content

Commit 7edc790

Browse files
committed
readme driven development
1 parent 9c3420f commit 7edc790

File tree

3 files changed

+19
-1
lines changed

3 files changed

+19
-1
lines changed

README.md

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -109,6 +109,18 @@ console.log(vector.magnitude()); // 50
109109

110110
If a function passed to `stringify` returns a truthy value, it's treated as a match.
111111

112+
You can also use custom types with `uneval` by specifying a custom replacer:
113+
114+
```js
115+
devalue.uneval(vector, (value, uneval) => {
116+
if (value instanceof Vector) {
117+
return `new Vector(${value.x},${value.y})`;
118+
}
119+
}); // `new Vector(30,40)`
120+
```
121+
122+
Note that any variables referenced in the resulting JavaScript (like `Vector` in the example above) must be in scope when it runs.
123+
112124
## Error handling
113125

114126
If `uneval` or `stringify` encounters a function or a non-POJO, it will throw an error. You can find where in the input data the offending value lives by inspecting `error.path`:

src/uneval.js

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -15,8 +15,9 @@ 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
1819
*/
19-
export function uneval(value) {
20+
export function uneval(value, replacer) {
2021
const counts = new Map();
2122

2223
/** @type {string[]} */

test/test.js

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -388,6 +388,11 @@ const fixtures = {
388388
value: [instance, instance],
389389
js: '(function(a){return [a,a]}(new Custom({answer:42})))',
390390
json: '[[1,1],["Custom",2],{"answer":3},42]',
391+
replacer: (value, uneval) => {
392+
if (value instanceof Custom) {
393+
return `new Custom(${uneval(value.value)})`;
394+
}
395+
},
391396
reducers: {
392397
Custom: (x) => x instanceof Custom && x.value
393398
},

0 commit comments

Comments
 (0)