How do I use JS's less-than operator?

I want to directly compare two JS Temporals. I can convert them to bigints and in JS I could use the less than operator: t1 < t2. I know there is compare, but looking at the generated JS, that goes through a bunch of Caml functions. Is there a zero-cost way to use JS’s built-in less-than operator?


What are JS Temporals? Dates?

If there is no better solution maybe you can use raw and hopefully such a small function always called with dates would be optimized and inlined by the JIT.

let compareDates: (
) => bool = %raw(`function compareDates(a, b) {
  return a < b;

Js.log(compareDates(Js.Date.make(), Js.Date.make()))

A temporal is a new browser API to get fix some of the issues of Dates. It has nanosecond support vs millisecond for Dates. See Temporal documentation. Rescript-webapi has some bindings in a PR, not yet merged.

I went with using raw for now. Feels odd that that’s the best approach, given Rescript’s goal of zero-cost bindings, but it certainly works.

I think the only zero-cost approach in this case it will be if you bind to the compare function from the Temporal API yourself.

Maybe you can try to bind an external value to %lessthan? The compiler will try to use the operator where possible. If not possible, it will fallback to Caml_obj.lessthan

module Temporal = {
    type t
    external \"<": (t, t) => bool = "%lessthan"
    // ... 


let res = {
   open! Temporal
   t1 < t2
1 Like

Just in case, bigint doesn’t work with compare. I was going to create an issue (and possibly a PR), but didn’t have time for it.

Yeah, that’s my bad. The last year or so has been so busy that I haven’t had time to finish up the webapi 1.0 release and get cracking on new API things.

Well, after copying things from that PR, I realized that Temporal isn’t in a released version of chrome yet. Whoops! I switched to using a global monotonically-increasing integer instead.

You can use a polyfill. Although it weights a lot