diff --git a/gitbook/reactjrx/bindings/react/useobserve.md b/gitbook/reactjrx/bindings/react/useobserve.md index 4874b22..5b94f9c 100644 --- a/gitbook/reactjrx/bindings/react/useobserve.md +++ b/gitbook/reactjrx/bindings/react/useobserve.md @@ -43,7 +43,7 @@ interface Options { * `source`: An observable, a function returning one, or `undefined`. Pass a stable observable directly: the hook subscribes to it again when its reference changes. Otherwise pass a function with `deps`, so the observable is only created again when a dependency changes. With `undefined`, nothing is observed and the default value is returned. * **optional** `options`: * `defaultValue`: returned until the source emits its first value. A `BehaviorSubject`, or any source that emits synchronously when subscribed, doesn't need it: its value is there on the first render. - * `compareFn`: tells whether a new value equals the previous one. An equal value doesn't re-render. Defaults to strict equality (`===`). Pass `isShallowEqual` (exported by reactjrx), or your own function, to compare objects by content. + * `compareFn`: tells whether a new value equals the previous one. An equal value doesn't re-render. Defaults to strict equality (`===`). Pass [isShallowEqual](../../utils/javascript/isshallowequal.md) (exported by reactjrx) to compare own enumerable properties one level deep, or your own function for a different equality rule. `isShallowEqual` does not compare the contents of `Date`, `Map` or `Set` objects. * **optional** `deps`: The values the function depends on. When one of them changes (compared with [`Object.is`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is)), the function is called again and its observable replaces the previous one. ### Returns diff --git a/gitbook/reactjrx/utils/javascript/isshallowequal.md b/gitbook/reactjrx/utils/javascript/isshallowequal.md index 9acec94..40f277b 100644 --- a/gitbook/reactjrx/utils/javascript/isshallowequal.md +++ b/gitbook/reactjrx/utils/javascript/isshallowequal.md @@ -1,6 +1,6 @@ # isShallowEqual -Returns true when two values are equal one level deep: the same primitive, or two objects with the same `constructor` and the same own enumerable string keys holding `===` values. Symbol and non-enumerable properties are not compared. +Returns true when two values are equal one level deep: primitives compared with `Object.is`, or two objects with the same `constructor` and the same own enumerable string keys holding `Object.is`-equal values. Objects with a null prototype and objects with an own `hasOwnProperty` key are supported. Symbol and non-enumerable properties are not compared. ### Usage @@ -9,10 +9,18 @@ import { isShallowEqual } from "reactjrx" isShallowEqual({ a: 1, b: "x" }, { a: 1, b: "x" }) // true isShallowEqual({ a: { b: 1 } }, { a: { b: 1 } }) // false, `a` holds two different objects +isShallowEqual({ a: NaN }, { a: NaN }) // true +isShallowEqual(0, -0) // false ``` Pass it as the `compareFn` of [useObserve](../../bindings/react/useobserve.md) to skip the render of a new object that holds the same values. +### Comparison semantics + +`NaN` compares equal to `NaN`, and positive and negative zero compare as different values. If your application treats both zero signs as the same value, normalize them to `0` before comparison, or pass a custom `compareFn`. + +This is a shallow comparison of enumerable properties, not a comparison of built-in object contents. Two `Date` objects with different timestamps or two `Map` or `Set` objects with different entries can compare equal because they have the same constructor and no own enumerable string keys. Use a comparator that checks their contents when those differences matter. + ### Reference ```typescript diff --git a/src/lib/binding/useObserve/useObserve.compare.test.tsx b/src/lib/binding/useObserve/useObserve.compare.test.tsx index e0c8995..470f16b 100644 --- a/src/lib/binding/useObserve/useObserve.compare.test.tsx +++ b/src/lib/binding/useObserve/useObserve.compare.test.tsx @@ -75,6 +75,62 @@ it("should not return new value when the hook re-render but the value is the sam }) describe("given a custom compareFn", () => { + it("keeps null-prototype emissions live and only renders changed values", () => { + const initial = Object.assign(Object.create(null), { x: 1 }) + const source$ = new BehaviorSubject>(initial) + const values: UseObserveResult< + Record, + Record + >[] = [] + const { result } = renderHook(() => { + const value = useObserve(source$, { compareFn: isShallowEqual }) + useEffect(() => { + values.push(value) + }, [value]) + return value + }) + + act(() => { + source$.next(Object.assign(Object.create(null), { x: 1 })) + }) + expect(values).toHaveLength(1) + expect(result.current.error).toBeUndefined() + expect(result.current.observableState).toBe("live") + + act(() => { + source$.next(Object.assign(Object.create(null), { x: 2 })) + }) + expect(values).toHaveLength(2) + expect(result.current.data?.x).toBe(2) + expect(result.current.error).toBeUndefined() + }) + + it("deduplicates NaN properties while delivering signed-zero changes", () => { + const source$ = new BehaviorSubject({ x: Number.NaN }) + const values: Array<{ x: number } | undefined> = [] + const { result } = renderHook(() => { + const value = useObserve(source$, { compareFn: isShallowEqual }) + useEffect(() => { + values.push(value.data) + }, [value]) + return value + }) + + act(() => { + source$.next({ x: Number.NaN }) + }) + expect(values).toHaveLength(1) + + act(() => { + source$.next({ x: 0 }) + }) + act(() => { + source$.next({ x: -0 }) + }) + expect(values).toHaveLength(3) + expect(result.current.data?.x).toBe(-0) + }) + it("should re-render when the object is same but new reference", async () => { const values: Array<{ a: string } | undefined> = [] const source$ = new BehaviorSubject({ a: "a" }) diff --git a/src/lib/utils/shallowEqual.test.ts b/src/lib/utils/shallowEqual.test.ts index 6974b82..f464277 100644 --- a/src/lib/utils/shallowEqual.test.ts +++ b/src/lib/utils/shallowEqual.test.ts @@ -19,6 +19,12 @@ describe("shallowEqual", () => { expect(isShallowEqual(null, undefined)).toBe(false) }) + it("compares a null-prototype object with null", () => { + const value = Object.create(null) + expect(isShallowEqual(value, null)).toBe(false) + expect(isShallowEqual(null, value)).toBe(false) + }) + it("returns true for two string values that are equal", () => { expect(isShallowEqual("hello", "hello")).toBe(true) }) @@ -66,4 +72,52 @@ describe("shallowEqual", () => { const obj2 = "hello" expect(isShallowEqual(obj1, obj2)).toBe(false) }) + + it("compares null-prototype dictionaries by their own keys", () => { + const a = Object.assign(Object.create(null), { x: 1 }) + const b = Object.assign(Object.create(null), { x: 1 }) + expect(isShallowEqual(a, b)).toBe(true) + b.x = 2 + expect(isShallowEqual(a, b)).toBe(false) + }) + + it("handles an own property named hasOwnProperty", () => { + expect(isShallowEqual({ hasOwnProperty: 1 }, { hasOwnProperty: 1 })).toBe( + true, + ) + expect(isShallowEqual({ hasOwnProperty: 1 }, { hasOwnProperty: 2 })).toBe( + false, + ) + }) + + it("does not mistake inherited keys for own keys", () => { + const b = Object.assign(Object.create({ x: 1 }), { y: 1 }) + expect(isShallowEqual({ x: 1 }, b)).toBe(false) + }) + + it("considers NaN equal to itself and to another NaN property", () => { + expect(isShallowEqual(Number.NaN, Number.NaN)).toBe(true) + expect(isShallowEqual({ x: Number.NaN }, { x: Number.NaN })).toBe(true) + expect( + isShallowEqual({ constructor: Number.NaN }, { constructor: Number.NaN }), + ).toBe(true) + }) + + it("distinguishes positive and negative zero", () => { + expect(isShallowEqual(0, -0)).toBe(false) + expect(isShallowEqual(-0, 0)).toBe(false) + expect(isShallowEqual({ x: 0 }, { x: -0 })).toBe(false) + expect(isShallowEqual({ x: -0 }, { x: -0 })).toBe(true) + }) + + it("keeps different constructors distinct", () => { + expect(isShallowEqual(Object.create(null), {})).toBe(false) + expect(isShallowEqual([], {})).toBe(false) + }) + + it("compares nested objects by reference", () => { + const value = { x: 1 } + expect(isShallowEqual({ value }, { value })).toBe(true) + expect(isShallowEqual({ value }, { value: { x: 1 } })).toBe(false) + }) }) diff --git a/src/lib/utils/shallowEqual.ts b/src/lib/utils/shallowEqual.ts index 9e7414b..853457d 100644 --- a/src/lib/utils/shallowEqual.ts +++ b/src/lib/utils/shallowEqual.ts @@ -1,18 +1,21 @@ export function isShallowEqual(objA: A, objB: B): boolean { - // Check if both objects are null or undefined - if (objA === null || objA === undefined || objB === undefined) { - // biome-ignore lint/suspicious/noExplicitAny: TODO - return (objA as any) === (objB as any) + // Return early if either value is null or undefined + if ( + objA === null || + objB === null || + objA === undefined || + objB === undefined + ) { + return Object.is(objA, objB) } // Check if both objects are primitives if (typeof objA !== "object" || typeof objB !== "object") { - // biome-ignore lint/suspicious/noExplicitAny: TODO - return (objA as any) === (objB as any) + return Object.is(objA, objB) } - // Check if both objects have the same prototype - if (objA.constructor !== objB?.constructor) { + // Check if both objects have the same constructor + if (!Object.is(objA.constructor, objB.constructor)) { return false } @@ -26,9 +29,10 @@ export function isShallowEqual(objA: A, objB: B): boolean { // Check if the values of the keys are equal for (const key of keysA) { - // biome-ignore lint/suspicious/noPrototypeBuiltins: TODO - // biome-ignore lint/suspicious/noExplicitAny: TODO - if (!objB.hasOwnProperty(key) || objA[key] !== (objB as any)[key]) { + if ( + !Object.hasOwn(objB, key) || + !Object.is(objA[key], (objB as Record)[key]) + ) { return false } }