Skip to content

fix: withTrim caches wrapper functions via WeakMap (fixes #8)#18

Open
handsomesix wants to merge 2 commits into
bogeeee:mainfrom
handsomesix:main
Open

fix: withTrim caches wrapper functions via WeakMap (fixes #8)#18
handsomesix wants to merge 2 commits into
bogeeee:mainfrom
handsomesix:main

Conversation

@handsomesix

Copy link
Copy Markdown

Summary

withTrim currently creates a new wrapper function on every call, making it incompatible with addEventListener/removeEventListener patterns that rely on reference identity. This PR adds a WeakMap-based cache that reuses the same wrapper for identical (callbackFn, useSignatureFrom) pairs.

Changes

  • Added withTrimCache WeakMap to cache wrapper functions per callbackFn
  • Inner Map tracks different useSignatureFrom variants for the same callback
  • Cache automatically GCs when original callbackFn is no longer needed
  • Updated JSDoc to reflect the change and remove the TODO

Closes #8

This addresses issue bogeeee#8: withTrim no longer creates a new function
instance on every call. Instead, it reuses the same wrapper for
identical (callbackFn, useSignatureFrom) pairs, enabling use with
addEventListener/removeEventListener patterns.
- WeakMap cache per callbackFn with auto-GC
- Inner Map tracks useSignatureFrom variants
Implements iterable weak collection types using WeakRef + FinalizationRegistry,
enabling safe cleanup of connection-bound callbacks without memory leaks.

These classes solve the issue where ClientCallbacks/ClientCallbacksForEntities
need to be forgettable but also iterable - something the built-in WeakSet/WeakMap
don't support and the not-so-weak package's implementation has correctness bugs.

Implementation details:
- Uses WeakRef to hold weak references to values/keys
- Uses FinalizationRegistry to detect when entries are GC'd
- Automatically compacts internal storage during iteration
- Fully typed with proper TypeScript generics
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Minor: Improve withTrim

1 participant