0

I have let intervalId = option(Js.Global.intervalId)

I would like a succinct way to do the side effecting call to Js.Global.clearInterval if the option has a value (ie. is Some(id) and not None)

Maybe the Belt.Option.map function is the answer, but I'm having problems putting it to use.

I'm very new to OCaml and ReasonML, but several languages I know have suitable functions. I'm paraphrasing some of them here to give the idea what I'm looking for:

In Scala I would say: intervalId.foreach(Js.Global.clearInterval)

In Swift I would say: intervalId.map(Js.Global.clearInterval)

Peter Lamberg
  • 8,151
  • 3
  • 55
  • 69

2 Answers2

5

Belt.Option.map(intervalId, Js.Global.clearInterval) should work fine, except it returns a value that you need to discard in some way to avoid a type error or warning.

The safest way to discard values you don't need is to assign it to the wildcard pattern and include a type annotation to ensure the value you discard is what you expect it to be:

let _: option(unit) = Belt.Option.map(intervalId, Js.Global.clearInterval)

You can also use the ignore function, which works particularly well at the end of a sequence of pipes, but beware that you might then accidentally partially apply a function and discard it without actually executing the function and invoking the side-effect.

intervalId
  |> Belt.Option.map(_, Js.Global.clearInterval)
  |> ignore
glennsl
  • 28,186
  • 12
  • 57
  • 75
  • Cool! Thanks! That works. I especially like the last "chaining" syntax. I noticed that it even works on 1 line: `intervalId |> Belt.Option.map(_, Js.Global.clearInterval) |> ignore` (not sure if thats good style though ;) ) – Peter Lamberg May 10 '19 at 15:34
  • 1
    `|>` is really just an ordinary operator, and not whitespace-sensitive in any way. And style-wise I think it's usually fine, as long as it fits. – glennsl May 10 '19 at 15:56
0

For curiosity, I'll leave the obvious thing I had here before the chosen answer:

  switch (intervalId) {
    |Some(id) => Js_global.clearInterval(id)
    |None => ()
  }
Peter Lamberg
  • 8,151
  • 3
  • 55
  • 69