128 lines
2.7 KiB
JavaScript
Raw Normal View History

/**
* The sad, lonely enum that should be more tightly coupled
* to the Option type...but this isn't Rust
*/
enum OptionType {
Some = 'Some',
None = 'None',
}
const isOption = <T>(v: any): v is Option<T> => v instanceof Option;
/**
* Rust-style optional type
*
* Based on https://gist.github.com/s-panferov/575da5a7131c285c0539
*/
export class Option<T> {
/**
* The placeholder for the 'None' value type
*/
private static _noneInstance: Option<any> = new Option();
/**
* Is this a 'Some' or a 'None'?
*/
private optionType: OptionType;
/**
* The value for the 'Some' type
*/
private value?: T;
private constructor(v?: T | null) {
if (v !== undefined && v !== null) {
this.optionType = OptionType.Some;
this.value = v;
} else {
this.optionType = OptionType.None;
this.value = undefined;
}
}
public static get None(): Option<any> {
return <Option<any>> Option._noneInstance;
}
public static Some<X>(v: X): Option<X> {
return new Option(v);
}
public static from<X>(v: any): Option<X> {
return (isOption(v)) ? Option.from(v.unwrap()) : new Option(v);
}
isSome(): boolean {
return this.optionType === OptionType.Some && this.value !== undefined;
}
isNone(): boolean {
return this.optionType === OptionType.None;
}
isSomeAnd(fn: (a: T) => boolean): boolean {
return this.isSome() ? fn(this.unwrap()) : false;
}
isNoneAnd(fn: () => boolean): boolean {
return this.isNone() ? fn() : false;
}
map<U>(fn: (a: T) => U): Option<U> {
return this.isSome() ? new Option(fn(this.unwrap())) : Option._noneInstance;
}
mapOr<U>(def: U, f: (a: T) => U): U {
return this.isSome() ? f(this.unwrap()) : def;
}
mapOrElse<U>(def: () => U, f: (a: T) => U): U {
return this.isSome() ? f(this.unwrap()) : def();
}
unwrap(): T | never {
if (this.isSome() && this.value !== undefined) {
return this.value;
}
console.error('None.unwrap()');
throw 'None.get';
}
unwrapOr(def: T): T {
return this.isSome() ? this.unwrap() : def;
}
unwrapOrElse(f: () => T): T {
return this.isSome() ? this.unwrap() : f();
}
and<U>(optb: Option<U>): Option<U> {
return this.isSome() ? optb : Option._noneInstance;
}
andThen<U>(f: (a: T) => Option<U>): Option<U> {
return this.isSome() ? f(this.unwrap()) : Option._noneInstance;
}
or(optb: Option<T>): Option<T> {
return this.isNone() ? optb : this;
}
orElse(f: () => Option<T>): Option<T> {
return this.isNone() ? f() : this;
}
toString(): string {
const innerValue = (this.value !== undefined)
? JSON.stringify(this.value)
: '';
const prefix = this.optionType.valueOf();
return (innerValue.length > 0) ? `${prefix} (${innerValue})` : prefix;
}
}
export const { Some, None } = Option;
export default Option;