Use a Maybe functor to halt transformer functions from acting on null or undefined values

Thomas Greco
InstructorThomas Greco
Share this video with your friends

Social Share Links

Send Tweet
Published 6 years ago
Updated 4 years ago

As its name suggests, a Maybe is a type that may or may not hold a value. In JavaScript, we can use Maybes to check whether a value is undefined or null prior to passing it through to a transformer function and ultimately give us better control over the flow of our

In this lesson, we walk through the process of writing a factory function for creating objects that implement a Maybe functor. The overall goal of the lesson is to become more comfortable working with the functor data type while learning about Maybe, a widely-known implementation in the functional programming world

Tre' Codez
Tre' Codez
~ 4 years ago

I tend to use my own Either impl and I think I've been abusing it, like: ... https://github.com/elastic/kibana/blob/699959b484aad65366b73458d48a2df61a398b94/src/dev/code_coverage/ingest_coverage/transforms.js#L23

I feel like that was my worst use of it. I'm trying to really get good at knowing when to use a Maybe vs an Either.

Anyway, thanks again for a great fp contrib!

Thomas Greco
Thomas Grecoinstructor
~ 4 years ago

Hey Tre! Apologies for the late response. Thanks for the feedback though! It is really appreciated.

In regards to your question on Maybe vs Either, I believe that the difference is this:

Maybe

  • Used to check for a null or undefined value (a.k.a. Nothing). You can think of it as the ADT for null checks.
  • If the value is null or undefined, Maybe(null) will always return, therefore you can't get anything meaningful information.

Either

  • Whereas Maybe is great for null checks, Either is suited for situations where an error may occur (a.k.a. Left), as it allows you to store information about the error, which you can then handle however you choose.
  • I like to think of Either as Maybe's older sibling :).

I've adapted your code to gist - maybe-vs-either

Hope it helps!

Tre' Codez
Tre' Codez
~ 4 years ago

Thanks very much!!!

Markdown supported.
Become a member to join the discussionEnroll Today