ngxtension / ngxtension-platform

Utilities for Angular
https://ngxtension.netlify.app/
MIT License
531 stars 77 forks source link

Signal notifier numeric increment boundaries #428

Open leonelvsc opened 3 weeks ago

leonelvsc commented 3 weeks ago

https://github.com/ngxtension/ngxtension-platform/blob/658830c2fa6dc9eaf9f8e813c0509f9d8b5064bf/libs/ngxtension/create-notifier/src/create-notifier.ts#L8

I just want to remove existing theorical limitations and make the new implementation safe for all use cases

There's a concern that this operation might exceed the maximum safe integer value in JavaScript (Number.MAX_SAFE_INTEGER).

While the maximum safe integer (2^53 - 1) is indeed a large number, it's important to ensure calculations remain within this boundary to avoid potential unexpected behavior.

I propose some possible solutions to address this limitation:

Unique Symbol Generation: Instead of relying on numeric increments, the code could return a new Symbol() object for each signal change. Symbols are unique and immutable values, making them suitable for efficiently identifying distinct states.

sourceSignal.set(Symbol())

Unsigned Integer Wrapping: Another approach involves using the bitwise unsigned right shift operator (>>> 0) before the increment. This effectively "wraps" the numeric value around when it reaches the maximum value for a 32-bit unsigned integer (2^32 - 1), ensuring it stays within a safe range. This should be more performant over Symbol generation

v => (v >>> 0) + 1

Angular itself uses Arrays for tracking dependencies in the signal graph and the maximum index for an is Array 2^32 - 1

Call Math.random(): Simplier but don't know if it's more performant

sourceSignal.set(Math.random() + 1)

Boolean negation: Simplier

sourceSignal.update(v => !v)

https://developer.mozilla.org/es/docs/Web/JavaScript/Reference/Global_Objects/Number/MAX_SAFE_INTEGER