From 9e0d1d623e55285b06cfad7dc2c4f231ecadd87e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C3=ABl=20Lemaire?= Date: Fri, 30 Jul 2021 22:48:28 +0200 Subject: [PATCH] Fix nested map issue --- serializer.test.ts | 3 +++ serializer.ts | 30 +++++++++++++++++++++++------- 2 files changed, 26 insertions(+), 7 deletions(-) diff --git a/serializer.test.ts b/serializer.test.ts index d0e8615..b3ed531 100644 --- a/serializer.test.ts +++ b/serializer.test.ts @@ -78,6 +78,9 @@ it("serializes simple objects", () => { expect(result["d"].has(2)).toBe(false); expect(result["e"].get("z")).toBe(8); expect(result["e"].get("k")).toBeUndefined(); + + checkReversability(new Set(["a", new Set([1, "b"])])); + checkReversability(new Map([["a", new Map([[1, "test"]])]])); }); it("restores objects constructed from class", () => { diff --git a/serializer.ts b/serializer.ts index 1bb6575..d529e77 100644 --- a/serializer.ts +++ b/serializer.ts @@ -184,33 +184,49 @@ function crawl( } if (obj !== undefined && obj !== null && typeof obj != "function") { - let result = callback(obj); + const result = callback(obj); if (result === STOP_CRAWLING) { return; } if (Array.isArray(obj)) { - let subresult = obj.map((value) => crawl(value, callback, replace, memo)); + const subresult = obj.map((value) => + crawl(value, callback, replace, memo) + ); if (replace) { subresult.forEach((value, index) => { obj[index] = value; }); } } else if (obj instanceof Set) { - let subresult = new Set(); - for (let item of obj) { + const subresult = new Set(); + for (const item of obj) { subresult.add(crawl(item, callback, replace, memo)); } if (replace) { obj.clear(); - for (let item of subresult) { + for (const item of subresult) { obj.add(item); } } + } else if (obj instanceof Map) { + const subresult = new Map(); + for (const [key, item] of obj.entries()) { + subresult.set( + crawl(key, callback, replace, memo), + crawl(item, callback, replace, memo), + ); + } + if (replace) { + obj.clear(); + for (const [key, item] of subresult.entries()) { + obj.set(key, item); + } + } } else if (obj instanceof Object) { - let subresult: any = {}; - for (let key in obj) { + const subresult: any = {}; + for (const key in obj) { subresult[key] = crawl(obj[key], callback, replace, memo); } if (replace) {