rescript-core
rescript-core copied to clipboard
isNull, isUndefined convenience functions
I was writing some code checking for null and undefined and found it awkward. Originally I tried %raw which worked but wasn't pretty. I tried a bunch of Nullable.toOption and then checked for None and that was a mess. Then I realized I could use the == operator, but that also wasn't pretty. There was the uncertainty of do I use == or ===. In JavaScript null==undefined I think. The worst is if you are checking if something is null or undefined...
Nullable.make(obj)==Nullable.null || Nullable.make(obj)==Nullable.undefined
Nullable.make(obj).isNullOrUndefined
So here are some convenience functions like Nullable.isNull and Nullable.isUndefined that are analogous to Option.isNone and Option.isSome that make the code more readable. Includes tests and docs.
this could be simplified with v11 thanks to the new representation of untagged variants that will allow Nullable.t to be defined like this:
module Nullable = {
@unboxed type t<'a> = Present('a) | @as(null) Null | @as(undefined) Undefined
}
Then those utility functions could be replaced with a simple pattern matching.
It's not related to the post, but I've just thought of a possible problem that Nullable.t<Nullable.t<string>> like Present(Null) is matched as Null which might cause problems. Maybe not a big problem since it wasn't working before as well. But to make it work correctly and improve DX I think that @unboxed types should collapse like Nullable.t<Nullable.t<string>>->Nullable.t<string>
So maybe we should recover the @cristianoc's idea from some time ago? https://forum.rescript-lang.org/t/rfc-automatic-optional-chaining/3791/17?u=dzakh
It's not related to the post, but I've just thought of a possible problem that
Nullable.t<Nullable.t<string>>likePresent(Null)is matched asNullwhich might cause problems. Maybe not a big problem since it wasn't working before as well. But to make it work correctly and improve DX I think that@unboxedtypes should collapse likeNullable.t<Nullable.t<string>>->Nullable.t<string>So maybe we should recover the @cristianoc's idea from some time ago? https://forum.rescript-lang.org/t/rfc-automatic-optional-chaining/3791/17?u=dzakh
That idea amounts to accepting that nested nullable is the same as nullable. One can add a convenience function to that effect.
Even if pattern matching can be used, I still think having boolean-returning convenience functions as in this PR are useful because they are easily discoverable and can sometimes be used for more concise code than pattern matching. I don't have my code in front of me but know I have often used Option.isNone and Option.isSome even though I could use pattern matching for that.
yeah I agree, those utility functions can come handy from time to time (eg as a parameter of a filter function).