EitherFunctor.js

//Implementing Either //We have seen the problem Either is going to solve for us; //now let’s see its implementation. //Either Functor Parts Definition const Nothing = function(val) { this.value = val; }; Nothing.of = function(val) { return new Nothing(val); }; Nothing.prototype.map = function(f) { return this; }; const Some = function(val) { this.value = val; }; Some.of = function(val) { return new Some(val); }; Some.prototype.map = function(fn) { return Some.of(fn(this.value)); } //The implementation has two functions, Some and Nothing. //You can see that Some is just a copy of a Container with a name change. //The interesting part is with Nothing. //Nothing is also a Container, but its map doesn’t run over a given //function but rather just returns this: Nothing.prototype.map = function(f) { return this; }; //In other words, you can run your functions on Some but not on Nothing //(not a technical statement, right?). Here’s a quick example: Some.of("test").map((x) => x.toUpperCase()) => Some {value: "TEST"} Nothing.of("test").map((x) => x.toUpperCase()) => Nothing {value: "test"}
We have seen the problem Either is going to solve for us; now let’s see its implementation.

Be the first to comment

You can use [html][/html], [css][/css], [php][/php] and more to embed the code. Urls are automatically hyperlinked. Line breaks and paragraphs are automatically generated.