Created
October 18, 2019 16:49
-
-
Save tynor/393098f8e54d846df8c69ca1a7e85e8e to your computer and use it in GitHub Desktop.
This file contains 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
class Option<T> { | |
private readonly value?: T; | |
constructor(value?: T) { | |
this.value = value; | |
} | |
public isSome() { | |
return this.value !== void 0; | |
} | |
public isNone() { | |
return this.value === void 0; | |
} | |
public unwrap() { | |
if (this.value === void 0) { | |
throw new Error('unwrapped none option'); | |
} | |
return this.value; | |
} | |
public unwrapOr(def: T) { | |
return this.value === void 0 ? def : this.value; | |
} | |
public unwrapOrElse(f: () => T) { | |
return this.value === void 0 ? f() : this.value; | |
} | |
public map<U>(f: (v: T) => U): Option<U> { | |
if (this.value === void 0) { | |
return this as unknown as Option<U>; | |
} | |
return new Option(f(this.value)); | |
} | |
public mapOr<U>(def: U, f: (v: T) => U): U { | |
return this.value === void 0 ? def : f(this.value); | |
} | |
} | |
export const some = <T>(value: T) => new Option(value); | |
export const none = () => new Option(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment