Sorting an Int array

I’m sorting an array based on an int value called index. And currently I’m doing it like this:

someArray->SortArray.stableSortBy(({index: aIndex}, {index: bIndex}) => {
  if aIndex < bIndex {
    -1
  } else if aIndex == bIndex {
    0
  } else {
    1
  }
})

Is there a smarter way? I can see there’s something called SortArrayInt in the docs, but I’m not sure how to use it

1 Like

There’s nothing wrong with what you’re doing, but you can use the built in compare function which does almost exactly what your function does.

someArray->SortArray.stableSortBy((a, b) => compare(a.index, b.index))

You can swap the positions of a and b to sort it the opposite direction.

SortArrayInt is a specialized module for sorting arrays of integers, but your someArray example is an array of records, so it wouldn’t be applicable.

2 Likes

Thanks, I didn’t know about the compare function. I have used String.compare and was looking for Int.compare :sweat_smile:

Note that compare works differently than a normal function. It’s polymorphic, so it can accept any type. However, if you use it with a string, int, or float then the compiler will use a specialized version of it for each of those types. (In fact, String.compare is just that.)

If the compiler isn’t able to use a specialized function for a type (e.g., for a record or abstract type) then it will fall back on the polymorphic version, which is considered unsafe. ReScript can also be configured to warn you if you use it this way.

1 Like

Nice, thanks for the added details!

If the compiler isn’t able to use a specialized function for a type (e.g., for a record or abstract type) then it will fall back on the polymorphic version, which is considered unsafe. ReScript can also be configured to warn you if you use it this way.

Yes, turn the warning as error in your config and use compare is safe. We specialised more than just string/int

2 Likes

Thanks, I’ll do that. It blows my mind that you take the time to answer so many questions. That’s really nice of you, thanks!

1 Like