import {
type IOption,
type OptionNone,
type OptionSome,
type Option as OptionType,
Some,
None,
} from "./option";
import { Err, Ok, type Result } from "./result";
class Option implements IOption {
readonly result!: boolean;
// eslint-disable-next-line @typescript-eslint/no-redundant-type-constituents
readonly value!: A | never;
match(onSome: (value: A) => B, onNone: () => B): B {
return this.isSome() ? onSome(this.value) : onNone();
}
isSome(): this is OptionSome {
return this.result;
}
assertSome(): asserts this is OptionSome {
if (!this.isSome()) {
throw new TypeError("Expected Some but got None");
}
}
isNone(): this is OptionNone {
return !this.result;
}
assertNone(): asserts this is OptionNone {
if (!this.isNone()) {
throw new TypeError("Expected None but got Some");
}
}
ifSome(onSome: (value: A) => void) {
if (this.isSome()) {
onSome(this.value);
}
}
ifNone(onNone: () => void) {
if (this.isNone()) {
onNone();
}
}
chain(f: (value: A) => OptionType): OptionType {
return this.isSome() ? f(this.value) : None;
}
chainNone(f: () => OptionType): OptionType {
return this.isNone() ? f() : (this as OptionType);
}
map(f: (value: A) => B): OptionType {
return this.isSome() ? Some(f(this.value)) : None;
}
ap(f: OptionType<(a: A) => B>): OptionType {
return this.isSome() && f.isSome() ? Some(f.value(this.value)) : None;
}
and(option: OptionType): OptionType {
return this.isNone() ? option : None;
}
or(option: OptionType): OptionType {
return this.isNone() ? this : option;
}
getOr(defaultValue: A): A {
return this.isSome() ? this.value : defaultValue;
}
getOrElse(f: () => A): A {
return this.isSome() ? this.value : f();
}
okOr(error: E): Result {
return this.isSome() ? Ok(this.value) : Err(error);
}
okOrElse(f: () => E): Result {
return this.isSome() ? Ok(this.value) : Err(f());
}
unwrap(): A | undefined {
return this.isSome() ? this.value : undefined;
}
unwrapExact(message?: string): A {
if (this.isNone()) {
throw new TypeError(message ?? "Option.unwrapThrow(): value was None");
} else {
return this.value;
}
}
toJSON(): { result: true; value: A } | { result: false } {
return this.isSome() ? { result: true, value: this.value } : { result: false };
}
}
export { Option as OptionClass };