Comparing object references

Hello.

I’m implementing a react hook wrapping “ResizeObserver”.
If I’m understanding ResizeObserver correctly you create an instance passing a callback that receives an array of ResizeObserverEntry’s
You then have to call the instance “observe” method and pass it an element to be observed.
The hook should create a single instance internally and call the appropriate callbacks for each hook use.
The thing is that I think I can’t escape having to compare the DOM element passed in the observe method to some data structure holding the element’s passed to the hook itself so…
Long story short…
What’s the proper way of comparing objects (for equality) in rescript?
Is there a data structure that can hold object references as keys?

Thanks

I guess it would be the same way as it would do in JS. E.g. if you want to compare two references pointing to the same objects, you would use:

let a = { "test": "test" }
let b = a

Js.log(a === b) // true

which would check for referential equality of the two references according to MDN. Records are represented as JS objects, so the same ruleset would apply here.

If you are handling two Dom.elements, you may bind to Node.isEqualNode() and use that instead:

@val external document: Dom.element = "document"

@send external getElementById: (Dom.element, string) => Dom.element = "getElementById"
@send external isEqualNode: (Dom.element, Dom.element) => bool = "isEqualNode"

let a = document->getElementById("root")
let b = document->getElementById("root")

isEqualNode(a,b)->Js.log

Playground Link

2 Likes

Thanks Patrick.
Sorry for the obvious questions but sometimes I get insecure about the “proper way” to do things in ReScript.
Meanwhile I found Belt.MutableMap that seems to accept any type of key but I’m having some trouble understanding the docs.
Would it be a good option to use MutableMap or should I stick with iterating over an array to find the appropriate entry?

When in doubt, think about how you’d do it in JS :smiley:

You can also just use a Js.Dict.t I’d say?

Aren’t Js.Dict keys always strings?
I managed to create a Belt.MutableMap using Dom.Element as keys but that “Belt.Id.MakeComparable” functor thing is still a little confusing but it seems to be working