cache.js in snapDOM codebase.
In this article, we review cache.js file in snapDOM codebase. We will look at:
-
cache initialization and resetCache function
-
How is this cache applied in snapDOM codebase?
cache initialization and resetCache function
You will see the following at the top of cache.js file
/**
* Caches for images, backgrounds, resources, and
* computed styles used during DOM capture.
* @module cache
*/
cache
cache is initialised as shown below:
export const cache = {
image: new Map(),
background: new Map(),
resource: new Map(),
defaultStyle: new Map(),
baseStyle: new Map(),
computedStyle: new WeakMap(),
font: new Set(),
snapshot: new WeakMap(),
snapshotKey: new Map(),
preStyleMap: new Map(),
preStyle: new WeakMap(),
preNodeMap: new Map(),
reset: resetCache
};
resetCache
function resetCache() {
cache.computedStyle = new WeakMap();
cache.snapshot = new WeakMap();
cache.snapshotKey.clear();
cache.preStyleMap.clear();
cache.preStyle = new WeakMap();
cache.preNodeMap.clear();
}
This usage of WeakMap/Map/Set in the cache is a common pattern found in the OSS projects. I have seen WeakMap used for caching in react-scan as well, here is the article I wrote about — https://medium.com/@ramunarasinga/weakmap-in-react-scan-vs-next-mdx-source-code-14adb48821a7
How is this cache applied in snapDOM codebase?
One usecase I found is in snapdom/src/core/capture.js and this example pretty much demonstrates — get, set, has and reset.
About me:
Hey, my name is Ramu Narasinga. I study codebase architecture in large open-source projects.
Email: ramu.narasinga@gmail.com
Want to learn from open-source? Solve challenges inspired by open-source projects.
References:
-
https://github.com/zumerlab/snapdom/blob/main/src/core/cache.js#L3
-
https://github.com/zumerlab/snapdom/blob/main/src/core/capture.js#L12