Cleanup Bag (Dispose Subscriptions)

easy
By FrontendAtlas Editorial · Updated Oct 10, 2026
Implement createCleanupBag() that helps prevent memory leaks by tracking cleanup functions (like removing event listeners or cancelling timers). It should return { add, dispose, size }. add(fn) registers a cleanup and returns a function to remove it. dispose() runs all remaining cleanups once and clears the bag.

Returns

{ add: (fn: () => void) => () => void, dispose: () => void, size: () => number } — A cleanup registry that can be disposed safely.

Solution idea

Track cleanup callbacks in a Set. add() registers a cleanup and returns a remover. dispose() runs each cleanup once and clears the Set. If add() is called after dispose(), run it immediately to avoid leaks.

Examples
const bag = createCleanupBag();
const off = bag.add(() => clearInterval(id));
// later...
bag.dispose();

// add after dispose runs immediately
bag.dispose();
bag.add(() => console.log('cleanup'));