Skip to content

Instantly share code, notes, and snippets.

@tynor
Created October 18, 2019 16:49
Show Gist options
  • Save tynor/393098f8e54d846df8c69ca1a7e85e8e to your computer and use it in GitHub Desktop.
Save tynor/393098f8e54d846df8c69ca1a7e85e8e to your computer and use it in GitHub Desktop.
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