Closed
Description
Search Terms
stage 3, tc39, weakref, finalization group
Suggestion
WeakRef and FinalizationGroup are Stage 3 https://github.com/tc39/proposal-weakrefs
Only drawback I could think of is that, implementing a polyfill would make it over engineered and less performant than the real thing (of course), and actually leak memory if not careful.
Use Cases
Key/value cache are a great example (as stated in the proposal itself)
Examples
// Fixed version that doesn't leak memory.
function makeWeakCached(f) {
const cache = new Map();
const cleanup = new FinalizationGroup(iterator => {
for (const key of iterator) {
// See note below on concurrency considerations.
const ref = cache.get(key);
if (ref && !ref.deref()) cache.delete(key);
}
});
return key => {
const ref = cache.get(key);
if (ref) {
const cached = ref.deref();
// See note below on concurrency considerations.
if (cached !== undefined) return cached;
}
const fresh = f(key);
cache.set(key, new WeakRef(fresh));
cleanup.register(fresh, key, key);
return fresh;
};
}
var getImageCached = makeWeakCached(getImage);
Checklist
My suggestion meets these guidelines:
- This wouldn't be a breaking change in existing TypeScript/JavaScript code
- This wouldn't change the runtime behavior of existing JavaScript code
- This could be implemented without emitting different JS based on the types of the expressions
- This isn't a runtime feature (e.g. library functionality, non-ECMAScript syntax with JavaScript output, etc.)
- This feature would agree with the rest of TypeScript's Design Goals.