import { Err, type IResult, Ok, type Result as ResultType, type ResultOk, type ResultErr, } from "./result"; import { None, type Option, Some } from "./option"; class Result implements IResult { readonly result!: boolean; readonly value!: A | E; match(onOk: (value: A) => B, onErr: (value: E) => B): B { return this.isOk() ? onOk(this.value) : onErr(this.value as E); } isOk(): this is ResultOk { return this.result; } isErr(): this is ResultErr { return !this.result; } assertOk(): asserts this is ResultOk { if (!this.isOk()) { throw new TypeError("Expected Ok but got Err"); } } assertErr(): asserts this is ResultErr { if (!this.isErr()) { throw new TypeError("Expected Err but got Ok"); } } ifOk(onOk: (value: A) => void) { if (this.isOk()) { onOk(this.value); } } ifErr(onErr: (value: E) => void) { if (this.isErr()) { onErr(this.value); } } chain(f: (value: A) => ResultType): ResultType { if (this.isOk()) { return f(this.value); } return this as unknown as ResultType; } chainErr(f: (value: E) => ResultType): ResultType { if (this.isErr()) { return f(this.value); } return this as unknown as ResultType; } bichain: ( ok: (okValue: A) => ResultType, err: (errValue: E) => ResultType ) => ResultType = this.match; map(f: (value: A) => B): ResultType { if (this.isOk()) { return Ok(f(this.value)); } return this as unknown as ResultType; } mapErr(f: (value: E) => F): ResultType { if (this.isErr()) { return Err(f(this.value)); } return this as unknown as ResultType; } bimap(ok: (okValue: A) => B, err: (errValue: E) => F): ResultType { return this.isOk() ? Ok(ok(this.value)) : Err(err(this.value as E)); } ap(f: ResultType<(a: A) => B, E>): ResultType { if (f.isErr()) { return f as unknown as ResultType; } if (this.isOk()) { return Ok(f.value(this.value)); } return this as unknown as ResultType; } and(result: ResultType): ResultType { return this.isOk() ? result : (this as unknown as ResultType); } or(result: ResultType): ResultType { return this.isErr() ? (this as unknown as ResultType) : result; } getOr(defaultValue: A): A { return this.isOk() ? this.value : defaultValue; } getOrElse(f: () => A): A { return this.isOk() ? this.value : f(); } unwrap(): A | undefined { return this.isOk() ? this.value : undefined; } unwrapErr(): E | undefined { return this.isErr() ? this.value : undefined; } unwrapExact(): A { if (this.isErr()) { // eslint-disable-next-line @typescript-eslint/only-throw-error throw this.value; } else { return this.value as A; } } ok(): Option { return this.isOk() ? Some(this.value) : None; } err(): Option { return this.isErr() ? Some(this.value) : None; } isAborted(): this is ResultErr { return ( this.isErr() && this.value instanceof DOMException && this.value.name === "AbortError" ); } toJSON(): { result: boolean; value: A | E } { return { result: this.result, value: this.value }; } } export { Result as ResultClass };