Last active
August 29, 2015 13:55
-
-
Save mattbaker/8789404 to your computer and use it in GitHub Desktop.
"Wealthfront-style" Option Monad using ES6 Iterators
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
* A Wealthfront-style Option implementation in Javascript implementing ES6 iterables | |
* Reference: | |
* http://eng.wealthfront.com/2010/05/better-option-for-java.html | |
* | |
* This only runs in current versions of Firefox. | |
* It's recommended you use the FF Scratchpad with the web console open to see logging results: | |
* https://developer.mozilla.org/en-US/docs/Tools/Scratchpad | |
*/ | |
function Option(v) { | |
this.v = v; | |
} | |
Option.prototype.__iterator__ = function(){ | |
return new OptionIterator(this); | |
}; | |
Option.of = function (v) { | |
return new Option(v); | |
} | |
function OptionIterator(option) { | |
this.option = option; | |
this.accessed = false; | |
} | |
OptionIterator.prototype.next = function() { | |
if (this.accessed || this.option.v === null) { | |
throw StopIteration; | |
} | |
this.accessed = true; | |
return this.option.v; | |
} | |
var maybeThereButIsnt = Option.of(null); | |
var maybeThereAndIs = Option.of(20); | |
for(var value in maybeThereButIsnt) { | |
console.log("I'm not here! " + value); | |
} | |
for(var value in maybeThereAndIs) { | |
console.log("I'm here! " + value); | |
} | |
/* | |
* Console Output: | |
* | |
* > "I'm here! 20" | |
* | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment