trycat
Version:
A lightweight, type-safe, zero-dependency implementation of the Result type.
145 lines (144 loc) • 2.27 kB
JavaScript
// trycat.ts
var Ok = class _Ok {
constructor(value) {
this.value = value;
}
isOk() {
return true;
}
isErr() {
return false;
}
inspect(f) {
f(this.value);
return this;
}
inspectErr(f) {
return this;
}
map(mapper) {
return new _Ok(mapper(this.value));
}
mapOr(def, mapper) {
return mapper(this.value);
}
mapOrElse(errMapper, mapper) {
return mapper(this.value);
}
mapErr(mapper) {
return this;
}
or(other) {
return this;
}
orElse(op) {
return this;
}
and(other) {
return other;
}
andThen(op) {
return op(this.value);
}
unwrap() {
return this.value;
}
unwrapOr(def) {
return this.value;
}
unwrapOrElse(op) {
return this.value;
}
expect(msg) {
return this.value;
}
unwrapErr() {
throw new Error(`${this.value}`);
}
expectErr(message) {
throw new Error(`${message}: ${this.value}`);
}
};
var Err = class _Err {
constructor(error) {
this.error = error;
}
isOk() {
return false;
}
isErr() {
return true;
}
inspect(f) {
return this;
}
inspectErr(f) {
f(this.error);
return this;
}
map(mapper) {
return this;
}
mapOr(def, mapper) {
return def;
}
mapOrElse(errMapper, mapper) {
return errMapper(this.error);
}
mapErr(mapper) {
return new _Err(mapper(this.error));
}
or(other) {
return other;
}
orElse(op) {
return op(this.error);
}
and(other) {
return this;
}
andThen(op) {
return this;
}
unwrap() {
throw new Error(`${this.error}`);
}
unwrapOr(def) {
return def;
}
unwrapOrElse(op) {
return op(this.error);
}
expect(message) {
throw new Error(`${message}: ${this.error}`);
}
unwrapErr() {
return this.error;
}
expectErr(message) {
return this.error;
}
};
function ok(value) {
return value ? new Ok(value) : new Ok(void 0);
}
function err(error) {
return error ? new Err(error) : new Err(void 0);
}
function trys(fn) {
try {
const retval = fn();
return retval ? ok(retval) : ok();
} catch (e) {
return err(e);
}
}
function tryp(promise) {
return promise.then((value) => ok(value)).catch((e) => err(e));
}
export {
err,
ok,
tryp,
trys
};