Skip to content

Instantly share code, notes, and snippets.

@BartMassey
Last active July 26, 2019 21:37
Show Gist options
  • Select an option

  • Save BartMassey/49d40797350ed147e8833dc5d5052a3f to your computer and use it in GitHub Desktop.

Select an option

Save BartMassey/49d40797350ed147e8833dc5d5052a3f to your computer and use it in GitHub Desktop.
"Option type" for Javascript
"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