Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Native Equality Support for Structs #60

Open
musicq opened this issue Dec 5, 2024 · 2 comments
Open

Native Equality Support for Structs #60

musicq opened this issue Dec 5, 2024 · 2 comments

Comments

@musicq
Copy link

musicq commented Dec 5, 2024

Currently, since struct instances are sealed, there is no built-in mechanism for native deep equality checks.

This limitation often requires developers to rely on helper functions like deepEqual to compare objects based on their data rather than their references.

const a1 = {name: "a", school: {grade: 1}}
const a2 = {name: "a", school: {grade: 1}}

deepEqual(a1, a2)

While this works, certain scenarios make implementing deep equality challenging. For example, in React, dependency arrays ([]) in hooks like useEffect rely on strict reference equality (===). If an object is passed directly without ensuring it retains the same reference, the behavior can become unpredictable:

const person = {name: "a"}

useEffect(() => {
  console.log(Math.random()) // // This runs unexpectedly if `person`'s reference changes
}, [person])

In cases like these, the lack of a native equality mechanism for struct instances increases cognitive overhead and complicates development.

Proposed Solution

If struct could natively support deep equality checks, it would significantly reduce the mental load for developers, particularly in scenarios where strict reference equality is not practical or desired. For example:

struct Person {
  constructor(name) { this.name = name; }
  name;
}

const a1 = new Person("a")
const a2 = new Person("a")

assert(a1 === a2)

Benefits

  • Improved Developer Experience: Reduces the need for custom deep equality functions.
  • Enhanced React Usability: Simplifies dependency tracking in hooks by ensuring consistent behavior with structured data.
  • Cleaner Code: Avoids unnecessary boilerplate or workaround patterns to achieve expected equality checks.
@acutmore
Copy link

acutmore commented Dec 5, 2024

Struct fields are writable. Two separate struct instances can't be === referentially equal because either of them could be modified, so they need to remain separate instances.

const a1 = new Person("a")
const a2 = new Person("a")

a1 === a2; // needs to be false
a1.name = "b";
a1 === a2; // because this must be false

@musicq
Copy link
Author

musicq commented Dec 5, 2024

I see. Seems like it's hard to support deepEqual for structs🤔

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

No branches or pull requests

2 participants