UNPKG

@freelight-software/dont-throw

Version:

Result based function returns that prevent any exceptions from being thrown.

115 lines (113 loc) 2.24 kB
// src/index.ts function ok(value) { return new Ok(value); } function err(err2) { return new Err(err2); } function dontThrow(func, bindThis) { return (...args) => { let finalFunc = func; if (bindThis) { finalFunc = func.bind(bindThis); } try { const result = finalFunc(...args); return ok(result); } catch (e) { return err(e); } }; } function dontThrowAsync(func, bindThis) { return async (...args) => { let finalFunc = func; if (bindThis) { finalFunc = func.bind(bindThis); } try { const result = await finalFunc(...args); return ok(result); } catch (e) { return err(e); } }; } var Ok = class { val; constructor(value) { this.val = value; } isOk() { return true; } isErr() { return !this.isOk(); } get value() { return this.val; } andThen(func) { return func(this.val); } unwrap() { return this.val; } map(func) { return ok(func(this.val)); } }; var Err = class { err; constructor(err2) { this.err = err2; } isOk() { return false; } isErr() { return !this.isOk(); } get error() { return this.err; } andThen(func) { return err(this.err); } unwrap() { throw this.err; } map(func) { return err(this.err); } }; var ResultAsync = class _ResultAsync { promise; constructor(promise) { this.promise = promise; } static fromPromise(promise) { const resultPromise = promise .then((value) => new Ok(value)) .catch((e) => new Err(e)); return new _ResultAsync(resultPromise); } // biome-ignore lint/suspicious/noThenProperty: have to implement PromiseLike then(onfulfilled, onrejected) { return this.promise.then(onfulfilled, onrejected); } andThen(func) { return new _ResultAsync( this.promise.then(async (res) => { if (res.isErr()) { return err(res.error); } const result = await func(res.value); return result instanceof _ResultAsync ? result.promise : result; }), ); } }; export { Err, Ok, ResultAsync, dontThrow, dontThrowAsync, err, ok }; //# sourceMappingURL=index.js.map //# sourceMappingURL=index.js.map