From ea24297063475c29fd129f8f24c52594284a643a Mon Sep 17 00:00:00 2001 From: Jason Dent Date: Tue, 17 Sep 2024 22:50:41 +0200 Subject: [PATCH] fix: Remove object from cache (#6257) --- packages/flatpack-json/src/Flatpack.mts | 18 ++++++++++++++++++ packages/flatpack-json/src/Flatpack.test.mts | 12 ++++++++++++ 2 files changed, 30 insertions(+) diff --git a/packages/flatpack-json/src/Flatpack.mts b/packages/flatpack-json/src/Flatpack.mts index 8deac849ee01..149d1d3605a1 100644 --- a/packages/flatpack-json/src/Flatpack.mts +++ b/packages/flatpack-json/src/Flatpack.mts @@ -599,6 +599,24 @@ export class FlatpackStore { assigned.set(this.refUndefined, 0); calcAvailableIndexes(); addElements(this.root); + this.#cleanCache(); + } + + /** + * Remove objects from the cache after the FlatpackStore has been built. + */ + #cleanCache() { + const toRemove = new Set(); + + for (const key of this.cache.keys()) { + if (key && typeof key === 'object') { + toRemove.add(key); + } + } + + for (const key of toRemove) { + this.cache.delete(key); + } } toJSON(): Flatpacked { diff --git a/packages/flatpack-json/src/Flatpack.test.mts b/packages/flatpack-json/src/Flatpack.test.mts index bb9c4a02c9e9..66f789bf120a 100644 --- a/packages/flatpack-json/src/Flatpack.test.mts +++ b/packages/flatpack-json/src/Flatpack.test.mts @@ -177,6 +177,18 @@ describe('Flatpack', async () => { const s2 = fp.stringify(); expect(s2).toEqual(s1); }); + + test('Updating the object used.', () => { + const data: Record & { d: number[] } = { a: 1, b: 2, d: [1, 2, 3] }; + const fp = new FlatpackStore(data); + const v = fp.toJSON(); + expect(fromJSON(v)).toEqual(data); + data.c = 3; + data.d.push(4); + fp.setValue(data); + expect(fromJSON(fp.toJSON())).toEqual(data); + expect(fp.toJSON()).not.toEqual(v); + }); }); async function sampleFileList() {