Last active
July 9, 2019 22:52
-
-
Save bcherny/f7db2a1e40c9c18e0a0acc739f5d34d8 to your computer and use it in GitHub Desktop.
Draft: Reference Option implementation for Programming TypeScript
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
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