Skip to content

Instantly share code, notes, and snippets.

@bcherny
Last active July 9, 2019 22:52
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bcherny/f7db2a1e40c9c18e0a0acc739f5d34d8 to your computer and use it in GitHub Desktop.
Save bcherny/f7db2a1e40c9c18e0a0acc739f5d34d8 to your computer and use it in GitHub Desktop.
Draft: Reference Option implementation for Programming TypeScript
function Option<T>(value?: null | undefined): None
function Option<T>(value: T): Some<T>
function Option<T>(value?: T): Option<T> {
if (value == null) {
return new None
}
return new Some(value)
}
interface Option<T> {
flatMap<U>(f: (value: T) => None): None
flatMap<U>(f: (value: T) => Option<U>): Option<U>
getOrElse(value: T): T
}
class Some<T> implements Option<T> {
constructor(protected value?: T) {}
flatMap<U>(f: (value: T) => None): None
flatMap<U>(f: (value: T) => Some<U>): Some<U>
flatMap<U>(f: (value: T) => Option<U>): Option<U> {
return f(this.value)
}
getOrElse(_value: T): T {
return this.value
}
}
class None implements Option<never> {
flatMap<U>(_f: (value: never) => Option<U>): None {
return new None
}
getOrElse<U>(value: U): U {
return value
}
}
let a = Option(2)
.flatMap(n => new Some('a'))
.flatMap(n => new Some(5 * n))
.flatMap(() => new None)
.flatMap(n => new Some(5 * n))
.flatMap(n => new Some(5 * n))
.flatMap(() => new None)
.getOrElse('a')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment