From d8c830565e4ba91ed19f84f5a8dfa1aa7eab7bd5 Mon Sep 17 00:00:00 2001 From: Eemeli Aro Date: Sat, 18 Apr 2020 16:16:38 +0300 Subject: [PATCH] Maintain key order when restoring references --- src/index.spec.ts | 23 ++++++++++++++++++++--- src/index.ts | 3 ++- 2 files changed, 22 insertions(+), 4 deletions(-) diff --git a/src/index.spec.ts b/src/index.spec.ts index 789f952..713046a 100644 --- a/src/index.spec.ts +++ b/src/index.spec.ts @@ -682,7 +682,7 @@ describe("javascript-stringify", () => { const result = stringify(obj, null, null, { references: true }); expect(result).toEqual( - "(function(){var x={key:'value'};x.obj=x;return x;}())" + "(function(){var x={key:'value',obj:undefined};x.obj=x;return x;}())" ); }); @@ -727,7 +727,9 @@ describe("javascript-stringify", () => { const result = stringify(obj, null, null, { references: true }); - expect(result).toEqual("(function(){var x={a:{}};x.b=x.a;return x;}())"); + expect(result).toEqual( + "(function(){var x={a:{},b:undefined};x.b=x.a;return x;}())" + ); }); it("should restore repeated values with indentation", function() { @@ -740,7 +742,22 @@ describe("javascript-stringify", () => { const result = stringify(obj, null, 2, { references: true }); expect(result).toEqual( - "(function () {\nvar x = {\n a: {}\n};\nx.b = x.a;\nreturn x;\n}())" + "(function () {\nvar x = {\n a: {},\n b: undefined\n};\nx.b = x.a;\nreturn x;\n}())" + ); + }); + + it("should maintain key order when restoring repeated values", () => { + const obj: any = {}; + const child = {}; + + obj.a = child; + obj.b = child; + obj.c = "C"; + + const result = stringify(obj, null, null, { references: true }); + + expect(result).toEqual( + "(function(){var x={a:{},b:undefined,c:'C'};x.b=x.a;return x;}())" ); }); }); diff --git a/src/index.ts b/src/index.ts index 8c50769..3ba1b0d 100644 --- a/src/index.ts +++ b/src/index.ts @@ -66,7 +66,8 @@ export function stringify( // Track nodes to restore later. if (tracking.has(value)) { unpack.set(path.slice(1), tracking.get(value)!); - return; // Avoid serializing referenced nodes on an expression. + // Use `undefined` as temporaray stand-in for referenced nodes + return valueToString(undefined, space, onNext, key); } // Track encountered nodes.