UNPKG

@daisugi/anzen

Version:

Anzen helps write safe code without exceptions, taking roots from Rust's Result and Haskell's Either.

139 lines 3.29 kB
export class ResultSuccess { isSuccess = true; isFailure = false; #value; constructor(value) { this.#value = value; } getValue() { return this.#value; } getOrElse(_) { return this.#value; } getError() { throw new Error('Cannot get the error of a success.'); } chain(fn) { return fn(this.#value); } elseChain(_) { return this; } map(fn) { return new ResultSuccess(fn(this.#value)); } elseMap(_) { return this; } unwrap() { return [this, this.#value]; } unsafeUnwrap() { return this.#value; } toJSON() { return JSON.stringify({ value: this.#value, isSuccess: this.isSuccess, }); } } export class ResultFailure { isSuccess = false; isFailure = true; #error; constructor(err) { this.#error = err; } getValue() { throw new Error('Cannot get the value of a failure.'); } getOrElse(defaultVal) { return defaultVal; } getError() { return this.#error; } chain(_) { return this; } elseChain(fn) { return fn(this.#error); } map(_) { return this; } elseMap(fn) { return new ResultSuccess(fn(this.#error)); } unwrap(defaultVal) { return [this, defaultVal]; } unsafeUnwrap() { return this.#error; } toJSON() { return JSON.stringify({ error: this.#error, isSuccess: this.isSuccess, }); } } async function handleResult(whenRes) { const res = await whenRes; return res.isSuccess ? res.getValue() : Promise.reject(res.getError()); } export class Result { static success = (val) => new ResultSuccess(val); static failure = (err) => new ResultFailure(err); static async promiseAll(whenRes) { try { const vals = await Promise.all(whenRes.map(handleResult)); return Result.success(vals); } catch (err) { return Result.failure(err); } } static async unwrapPromiseAll(args) { const [defaultsVals, ...whenRes] = args; try { const vals = await Promise.all(whenRes.map(handleResult)); return [Result.success(vals), ...vals]; } catch (err) { return [Result.failure(err), ...defaultsVals]; } } static unwrap(defaultVal) { return (res) => res.isSuccess ? [res, res.getValue()] : [res, defaultVal]; } static fromJSON(json) { const obj = JSON.parse(json); return obj.isSuccess ? new ResultSuccess(obj.value) : new ResultFailure(obj.error); } static fromSyncThrowable(fn, parseErr) { try { return Result.success(fn()); } catch (err) { return Result.failure(parseErr?.(err) ?? err); } } static async fromThrowable(fn, parseErr) { try { return Result.success(await fn()); } catch (err) { return Result.failure(parseErr?.(err) ?? err); } } } //# sourceMappingURL=anzen.js.map