This is the second time I am writing about WeakMap. Previously, I wrote an article about WeakMap in JavaScript and this was a review about a code snippet from next-mdx source code and the code looks like below:
const cache = new WeakMap()/** * A webpack loader for mdx-rs. This is largely based on existing @mdx-js/loader, * replaces internal compilation logic to use mdx-rs instead. */function loader(value, bindings, callback) { ... const compiler = this._compiler || marker let map = cache.get(compiler) if (!map) { map = new Map() cache.set(compiler, map) }...
What’s one thing that’s common here? cache….
Below is how cache is initialized in react-scan source code:
const cache = new WeakMap<object, string>();
Below is how cache is initialized in next-mdx source code
const cache = new WeakMap()
Well, there is types in the react-scan source code.
A WeakMap is a collection of key/value pairs whose keys must be objects or non-registered symbols, with values of any arbitrary JavaScript type, and which does not create strong references to its keys. That is, an object's presence as a key in a WeakMap does not prevent the object from being garbage collected. Once an object used as a key has been collected, its corresponding values in any WeakMap become candidates for garbage collection as well — as long as they aren't strongly referred to elsewhere. The only primitive type that can be used as a WeakMap key is symbol — more specifically, non-registered symbols — because non-registered symbols are guaranteed to be unique and cannot be re-created.
Hey, my name is Ramu Narasinga. I study large open-source projects and create content about their codebase architecture and best practices, sharing it through articles, videos.