Fix nested map issue

This commit is contained in:
Michaël Lemaire 2021-07-30 22:48:28 +02:00
parent f76867da5e
commit 9e0d1d623e
2 changed files with 26 additions and 7 deletions

View file

@ -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", () => {

View file

@ -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) {