Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Maybe monad in JavaScript

In the examples for monads.maybe on npm we have:

function find(collection, predicate) {
  for (var i = 0; i < collection.length; ++i) {
    var item = collection[i]
    if (predicate(item))  return Maybe.Just(item)
  }
  return Maybe.Nothing()
}

Can someone explain what Maybe.Just(item); and Maybe.Nothing() are actually doing?

Put another way; are monads essentially objects used as return values that implement specific interfaces that enable the definition of a sequence of function invocations?

like image 914
Ben Aston Avatar asked Feb 18 '26 03:02

Ben Aston


2 Answers

Maybe is used to represent an operation that might fail.

In the case of this function, you return Just(the element) if an element fulfills the predicate, else, you return Nothing to show that it had "failed" (in this case, none of the elements fulfill the predicate).

It's preferred to just returning a null because the return type explicitly shows that it can fail, and the answer can be pattern matched against.

like image 83
Carcigenicate Avatar answered Feb 20 '26 16:02

Carcigenicate


Monads are abstract containers with an API to operate on the data contained within. In the instance of the Option monad I think of it as a giftbox that either has a gift or is empty. Wrapping your data in a Maybe.Just() signifies that this container does infact contain data, while at the same time it maintains the returned value as a Maybe. The caller of your find() method can then do this:

var userPredicate = function(user) { return user.name === 'billy bob'; };
var users = collections.getUsersCollection();

var maybeData = find(users, userPredicate);
if(maybeData.isJust()) {
    // there was data...do something with it
} else {
    // no data...do something else
}

On the other hand, Maybe.Nothing() indicates the absence of data (the else part in the example above). Ideally, you would wrap your data within like so: var maybeData = Maybe(data) and then operate on this, pass it around etc. This is a signal to anyone receiving this object that they need to handle the case of missing data consciously.

Disclosure: I'm working on a similar library called Giftbox that has a richer API. Take a look at the readme there for some more explanations to help you understand what the Option monad is and how to use it effectively.

Here's an article describing Monads, Applicatives and Functors that might be useful to you.

like image 44
nitindhar7 Avatar answered Feb 20 '26 17:02

nitindhar7