Skip to content

Instantly share code, notes, and snippets.

@jonahwilliams
Last active December 11, 2015 18:24
Show Gist options
  • Save jonahwilliams/4558604718adbaedc8f0 to your computer and use it in GitHub Desktop.
Save jonahwilliams/4558604718adbaedc8f0 to your computer and use it in GitHub Desktop.
Option<?A> in JavaScript
type Maybe = Some | None;
class Option<A> {
value: A;
constructor(x: ?A) {
if (x == null) {
return new None();
} else {
return new Some(x);
}
}
static of(x: ?A): Maybe {
return new Option(x);
}
}
class Some<A> {
value: A;
constructor(x: A) {
this.value = x;
}
map<B>(f: (x: A) => ?B): Maybe {
const result: ?B = f(this.value);
if (result === null || result === undefined) {
return new None();
} else {
return new Some(result);
}
}
isNothing(): boolean {
return false;
}
getOrElse<B>(other: B): A {
return this.value;
}
}
class None {
constructor() { }
isNothing(): boolean {
return true;
}
map<B>(f: (x: any) => B): None {
return this;
}
getOrElse<B>(other: B): B {
return other;
}
}
Option.of(233) // Some<number>
.map(x => x * 42) // Some<number>
.map(x => x + 'hello') // Some<string>
.map(x => null) // None
.map(x => x.length) // None
.getOrElse('yo'); // => 'yo'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment