Skip to content

Commit 1d32d25

Browse files
authored
Maintain key order when restoring references (#33)
1 parent 3155073 commit 1d32d25

File tree

2 files changed

+22
-4
lines changed

2 files changed

+22
-4
lines changed

src/index.spec.ts

Lines changed: 20 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -682,7 +682,7 @@ describe("javascript-stringify", () => {
682682
const result = stringify(obj, null, null, { references: true });
683683

684684
expect(result).toEqual(
685-
"(function(){var x={key:'value'};x.obj=x;return x;}())"
685+
"(function(){var x={key:'value',obj:undefined};x.obj=x;return x;}())"
686686
);
687687
});
688688

@@ -727,7 +727,9 @@ describe("javascript-stringify", () => {
727727

728728
const result = stringify(obj, null, null, { references: true });
729729

730-
expect(result).toEqual("(function(){var x={a:{}};x.b=x.a;return x;}())");
730+
expect(result).toEqual(
731+
"(function(){var x={a:{},b:undefined};x.b=x.a;return x;}())"
732+
);
731733
});
732734

733735
it("should restore repeated values with indentation", function() {
@@ -740,7 +742,22 @@ describe("javascript-stringify", () => {
740742
const result = stringify(obj, null, 2, { references: true });
741743

742744
expect(result).toEqual(
743-
"(function () {\nvar x = {\n a: {}\n};\nx.b = x.a;\nreturn x;\n}())"
745+
"(function () {\nvar x = {\n a: {},\n b: undefined\n};\nx.b = x.a;\nreturn x;\n}())"
746+
);
747+
});
748+
749+
it("should maintain key order when restoring repeated values", () => {
750+
const obj: any = {};
751+
const child = {};
752+
753+
obj.a = child;
754+
obj.b = child;
755+
obj.c = "C";
756+
757+
const result = stringify(obj, null, null, { references: true });
758+
759+
expect(result).toEqual(
760+
"(function(){var x={a:{},b:undefined,c:'C'};x.b=x.a;return x;}())"
744761
);
745762
});
746763
});

src/index.ts

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -66,7 +66,8 @@ export function stringify(
6666
// Track nodes to restore later.
6767
if (tracking.has(value)) {
6868
unpack.set(path.slice(1), tracking.get(value)!);
69-
return; // Avoid serializing referenced nodes on an expression.
69+
// Use `undefined` as temporaray stand-in for referenced nodes
70+
return valueToString(undefined, space, onNext, key);
7071
}
7172

7273
// Track encountered nodes.

0 commit comments

Comments
 (0)