I’ve written a good amount about the Option Data Structure in my articles relating to Monads. But in light of my series on Data Structures, Option deserves its own full article outside of its relation to Monad. For this article we will forego all of the Monad talk and just understand Option for what it is.

First, let’s discuss null and undefined values. Let’s imagine we’re examining an object, possibly one that we’ve parsed from JSON received from the back-end of an application we’re working on. The objects we are receiving have a varying schema for whatever reason, so sometimes we have unexpected null or undefined values wreaking havoc on our client side. Option could well be the solution to this problem!

The Option is a special type of container that consists of two _variants. _That means that an instance of an Option can exist in one of two states (the variants). We call these two variants Some and None. _Some _represents the state of a present value in the container, while None represents an empty container. No matter what state your Option instance is in, it won’t be throwing around any null or undefined values. Here’s the core of the data portion of Option:

I like to use Symbols to hide the internal value of the Option (and other containers I write, too). I’ve opted for the constructor function approach, allowing us to create instances of Some and None using the new keyword. You can see that Some takes a value, while None does not. The TAG Symbol is used to quickly identify a Some or None instance. I’ve also packaged some core functions into the Option namespace object. Most notably, either and of. You can use the of constructor to create instances of Some or None by calling Option.of. Using of has some benefits — it obscures the use of new behind a plain function call, and it’s smart enough to figure out whether to give you a Some or a None instance without any effort on your part. We can use the either function to call a function conditionally depending on whether it is a Some or None value.

#functional-programming #programming #data-science #javascript #technology

JavaScript Data Structures: Option
1.20 GEEK