Skip to content

Commit 13691a1

Browse files
committed
1 parent 9b8a3ed commit 13691a1

File tree

2 files changed

+35
-1
lines changed

2 files changed

+35
-1
lines changed

src/monitor.js

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
import ContextMenu from './context-menu.js';
22
import DropArea from './drop-area.js';
33
import downloadBlob from './download-file.js';
4+
import {safeStringify} from './safe-stringify.js';
45

56
const readAsText = (blob) => new Promise((resolve, reject) => {
67
const fr = new FileReader();
@@ -200,9 +201,11 @@ class VariableMonitor extends Monitor {
200201
}
201202

202203
let value = monitor.get('value');
203-
if (typeof value === 'number') {
204+
if (typeof value === 'number' && !Object.is(value, -0)) {
204205
value = Number(value.toFixed(6));
205206
}
207+
value = safeStringify(value);
208+
206209
if (this._value !== value) {
207210
this._value = value;
208211
this.valueElement.textContent = value;
@@ -364,6 +367,8 @@ class Row {
364367
}
365368

366369
setValue (value) {
370+
value = safeStringify(value);
371+
367372
if (this.value !== value && !this.locked) {
368373
this.value = value;
369374
if (this.editable) {

src/safe-stringify.js

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
const circularReplacer = () => {
2+
const seen = new WeakSet();
3+
return (_, value) => {
4+
if (typeof value === 'object' && value !== null) {
5+
if (seen.has(value)) {
6+
return Array.isArray(value) ? '[...]' : '{...}';
7+
}
8+
seen.add(value);
9+
}
10+
return value;
11+
};
12+
};
13+
14+
/**
15+
* Safely stringify, properly handling circular relations and -0.
16+
* @param {unknown} input Any value
17+
* @returns {string} A stringified version of the input.
18+
*/
19+
export const safeStringify = input => {
20+
if (typeof input === 'object' && input !== null) {
21+
// TODO: this will not handle -0 inside the input properly, though that is very low priority.
22+
return JSON.stringify(input, circularReplacer());
23+
}
24+
// -0 stringifies as "0" by default.
25+
if (Object.is(input, -0)) {
26+
return '-0';
27+
}
28+
return `${input}`;
29+
};

0 commit comments

Comments
 (0)