Skip to content

Commit

Permalink
Maintain key order when restoring references
Browse files Browse the repository at this point in the history
  • Loading branch information
eemeli committed Apr 18, 2020
1 parent 3155073 commit d8c8305
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 4 deletions.
23 changes: 20 additions & 3 deletions src/index.spec.ts
Expand Up @@ -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;}())"
);
});

Expand Down Expand Up @@ -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() {
Expand All @@ -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;}())"
);
});
});
Expand Down
3 changes: 2 additions & 1 deletion src/index.ts
Expand Up @@ -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.
Expand Down

0 comments on commit d8c8305

Please sign in to comment.