Last active
July 26, 2019 21:37
-
-
Save BartMassey/49d40797350ed147e8833dc5d5052a3f to your computer and use it in GitHub Desktop.
"Option type" for Javascript
This file contains hidden or 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
| "use strict"; | |
| class Some { | |
| constructor(value) { | |
| this.value = value; | |
| } | |
| is_some(self) { | |
| return true; | |
| } | |
| is_none(self) { | |
| return false; | |
| } | |
| unwrap(self) { | |
| return self.value; | |
| } | |
| map(self, lambda) { | |
| return Some(lambda(self.value)); | |
| } | |
| } | |
| class NoneType { | |
| constructor() { | |
| } | |
| is_some(self) { | |
| return false; | |
| } | |
| is_none(self) { | |
| return true; | |
| } | |
| unwrap(self) { | |
| throw new Error("unwrap of None"); | |
| } | |
| map(self, lambda) { | |
| return self; | |
| } | |
| } | |
| var None = new NoneType(); | |
| function find_first_vowel(s) { | |
| for (var c in s) { | |
| if ("aeiou".indexOf(c) >= 0) { | |
| return new Some(c); | |
| } | |
| } | |
| return None; | |
| } | |
| var v = find_first_vowel("iou"); | |
| print(v === "a"); | |
| print(v === "i"); | |
| print(v.unwrap() === "i"); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment