UNPKG

return-style

Version:

Non-intrusively convert the result of any function or promise to the user's desired style.

129 lines 2.89 kB
import { Option } from './option.js'; var ResultType; (function (ResultType) { ResultType[ResultType["Ok"] = 0] = "Ok"; ResultType[ResultType["Err"] = 1] = "Err"; })(ResultType || (ResultType = {})); export class Result { type; value; error; constructor(type, valueOrError) { this.type = type; if (type === ResultType.Ok) { this.value = valueOrError; } else { this.error = valueOrError; } } static Ok(value) { return new Result(ResultType.Ok, value); } static Err(error) { return new Result(ResultType.Err, error); } isOk() { return this.type === ResultType.Ok; } isErr() { return this.type === ResultType.Err; } map(mapper) { if (this.isOk()) { return Result.Ok(mapper(this.value)); } else { return Result.Err(this.error); } } mapErr(mapper) { if (this.isOk()) { return Result.Ok(this.value); } else { return Result.Err(mapper(this.error)); } } mapOr(defaultValue, mapper) { if (this.isOk()) { return mapper(this.value); } else { return defaultValue; } } mapOrElse(createDefaultValue, mapper) { if (this.isOk()) { return mapper(this.value); } else { return createDefaultValue(this.error); } } unwrap() { if (this.isOk()) { return this.value; } else { throw this.error; } } unwrapOr(defaultValue) { if (this.isOk()) { return this.value; } else { return defaultValue; } } unwrapOrElse(createDefaultValue) { if (this.isOk()) { return this.value; } else { return createDefaultValue(this.error); } } unwrapErr() { if (this.isErr()) { return this.error; } else { throw new Error('unwrapErr called on a Ok'); } } expect(message) { if (this.isOk()) { return this.value; } else { throw new Error(message, { cause: this.error }); } } expectErr(message) { if (this.isErr()) { return this.error; } else { throw new Error(message, { cause: this.value }); } } ok() { if (this.isOk()) { return Option.Some(this.value); } else { return Option.None(); } } err() { if (this.isOk()) { return Option.None(); } else { return Option.Some(this.error); } } } //# sourceMappingURL=result.js.map