Ramda Pass "Maybe" Error Message Through Chain Calls

451 views Asked by At

Lets say I have bunch of functions returns Just or Nothing values and I want to chain them together like this;

var a = M.Just("5").map(function(data){
    return 1;
}).chain(function(data){
/*Make some operation return Just or Nothing */
    console.log(data);
    return M.Just(2);
}).chain(function(data){
/*Make some operation return Just or Nothing */
    console.log(data);
    return M.Nothing("Reason 1");
}).chain(function(data){
/*Make some operation return Just or Nothing */
    console.log(data);
    return M.Nothing("Reason 2");
}).getOrElse(function(data){
    console.log(data);
    return "Message";
});

console.log(a());

Output:

>     1
>     2
>     undefined
>     Message

In this above code since it is failing at step where function returns M.Nothing("Reason 1") it does not go through over other functions which is what I expected. I believe there is no valid constructor for Nothing that takes parameters. Is there a way to get this failure message at the end of the execution ? I have tried this in folktale as-well, does it related with fantasy land spec?

Thanks

1

There are 1 answers

0
sanver On BEST ANSWER

You can use Either monad for this purpose as it is stated in docs.

The Either type is very similar to the Maybe type, in that it is often used to represent the notion of failure in some way.

I modified the example you gave with Either monad below.

var R = require('ramda');
var M = require('ramda-fantasy').Either;

var a = M.Right("5").map(function(data){
return 1;
}).chain(function(data){
/*Make some operation return Just or Nothing */
console.log(data);
return M.Right(2);
}).chain(function(data){
/*Make some operation return Just or Nothing */
console.log(data);
return M.Left("Reason 1");
}).chain(function(data){
/*Make some operation return Just or Nothing */
console.log(data);
return M.Left("Reason 2");
});
console.log(a);
console.log(a.isLeft);