UNPKG

ts-results-es

Version:

A TypeScript implementation of Rust's Result and Option objects.

299 lines 10.2 kB
"use strict"; var __spreadArray = (this && this.__spreadArray) || function (to, from, pack) { if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) { if (ar || !(i in from)) { if (!ar) ar = Array.prototype.slice.call(from, 0, i); ar[i] = from[i]; } } return to.concat(ar || Array.prototype.slice.call(from)); }; Object.defineProperty(exports, "__esModule", { value: true }); exports.Result = exports.Ok = exports.OkImpl = exports.Err = exports.ErrImpl = void 0; var utils_js_1 = require("./utils.js"); var option_js_1 = require("./option.js"); var asyncresult_js_1 = require("./asyncresult.js"); /** * Contains the error value */ var ErrImpl = /** @class */ (function () { function ErrImpl(val) { if (!(this instanceof ErrImpl)) { return new ErrImpl(val); } this.error = val; var stackLines = new Error().stack.split('\n').slice(2); if (stackLines && stackLines.length > 0 && stackLines[0].includes('ErrImpl')) { stackLines.shift(); } this._stack = stackLines.join('\n'); } ErrImpl.prototype.isOk = function () { return false; }; ErrImpl.prototype.isErr = function () { return true; }; ErrImpl.prototype[Symbol.iterator] = function () { return { next: function () { return { done: true, value: undefined }; }, }; }; /** * @deprecated in favor of unwrapOr * @see unwrapOr */ ErrImpl.prototype.else = function (val) { return val; }; ErrImpl.prototype.unwrapOr = function (val) { return val; }; ErrImpl.prototype.unwrapOrElse = function (f) { return f(this.error); }; ErrImpl.prototype.expect = function (msg) { // The cause casting required because of the current TS definition being overly restrictive // (the definition says it has to be an Error while it can be anything). // See https://github.com/microsoft/TypeScript/issues/45167 throw new Error("".concat(msg, " - Error: ").concat((0, utils_js_1.toString)(this.error), "\n").concat(this._stack), { cause: this.error }); }; ErrImpl.prototype.expectErr = function (_msg) { return this.error; }; ErrImpl.prototype.unwrap = function () { // The cause casting required because of the current TS definition being overly restrictive // (the definition says it has to be an Error while it can be anything). // See https://github.com/microsoft/TypeScript/issues/45167 throw new Error("Tried to unwrap Error: ".concat((0, utils_js_1.toString)(this.error), "\n").concat(this._stack), { cause: this.error }); }; ErrImpl.prototype.unwrapErr = function () { return this.error; }; ErrImpl.prototype.map = function (_mapper) { return this; }; ErrImpl.prototype.andThen = function (op) { return this; }; ErrImpl.prototype.mapErr = function (mapper) { return new exports.Err(mapper(this.error)); }; ErrImpl.prototype.mapOr = function (default_, _mapper) { return default_; }; ErrImpl.prototype.mapOrElse = function (default_, _mapper) { return default_(this.error); }; ErrImpl.prototype.or = function (other) { return other; }; ErrImpl.prototype.orElse = function (other) { return other(this.error); }; ErrImpl.prototype.toOption = function () { return option_js_1.None; }; ErrImpl.prototype.toString = function () { return "Err(".concat((0, utils_js_1.toString)(this.error), ")"); }; Object.defineProperty(ErrImpl.prototype, "stack", { get: function () { return "".concat(this, "\n").concat(this._stack); }, enumerable: false, configurable: true }); ErrImpl.prototype.toAsyncResult = function () { return new asyncresult_js_1.AsyncResult(this); }; /** An empty Err */ ErrImpl.EMPTY = new ErrImpl(undefined); return ErrImpl; }()); exports.ErrImpl = ErrImpl; // This allows Err to be callable - possible because of the es5 compilation target exports.Err = ErrImpl; /** * Contains the success value */ var OkImpl = /** @class */ (function () { function OkImpl(val) { if (!(this instanceof OkImpl)) { return new OkImpl(val); } this.value = val; } OkImpl.prototype.isOk = function () { return true; }; OkImpl.prototype.isErr = function () { return false; }; OkImpl.prototype[Symbol.iterator] = function () { return [this.value][Symbol.iterator](); }; /** * @see unwrapOr * @deprecated in favor of unwrapOr */ OkImpl.prototype.else = function (_val) { return this.value; }; OkImpl.prototype.unwrapOr = function (_val) { return this.value; }; OkImpl.prototype.unwrapOrElse = function (_f) { return this.value; }; OkImpl.prototype.expect = function (_msg) { return this.value; }; OkImpl.prototype.expectErr = function (msg) { throw new Error(msg); }; OkImpl.prototype.unwrap = function () { return this.value; }; OkImpl.prototype.unwrapErr = function () { // The cause casting required because of the current TS definition being overly restrictive // (the definition says it has to be an Error while it can be anything). // See https://github.com/microsoft/TypeScript/issues/45167 throw new Error("Tried to unwrap Ok: ".concat((0, utils_js_1.toString)(this.value)), { cause: this.value }); }; OkImpl.prototype.map = function (mapper) { return new exports.Ok(mapper(this.value)); }; OkImpl.prototype.andThen = function (mapper) { return mapper(this.value); }; OkImpl.prototype.mapErr = function (_mapper) { return this; }; OkImpl.prototype.mapOr = function (_default_, mapper) { return mapper(this.value); }; OkImpl.prototype.mapOrElse = function (_default_, mapper) { return mapper(this.value); }; OkImpl.prototype.or = function (_other) { return this; }; OkImpl.prototype.orElse = function (_other) { return this; }; OkImpl.prototype.toOption = function () { return (0, option_js_1.Some)(this.value); }; /** * Returns the contained `Ok` value, but never throws. * Unlike `unwrap()`, this method doesn't throw and is only callable on an Ok<T> * * Therefore, it can be used instead of `unwrap()` as a maintainability safeguard * that will fail to compile if the error type of the Result is later changed to an error that can actually occur. * * (this is the `into_ok()` in rust) */ OkImpl.prototype.safeUnwrap = function () { return this.value; }; OkImpl.prototype.toString = function () { return "Ok(".concat((0, utils_js_1.toString)(this.value), ")"); }; OkImpl.prototype.toAsyncResult = function () { return new asyncresult_js_1.AsyncResult(this); }; OkImpl.EMPTY = new OkImpl(undefined); return OkImpl; }()); exports.OkImpl = OkImpl; // This allows Ok to be callable - possible because of the es5 compilation target exports.Ok = OkImpl; var Result; (function (Result) { /** * Parse a set of `Result`s, returning an array of all `Ok` values. * Short circuits with the first `Err` found, if any */ function all(results) { var okResult = []; for (var _i = 0, results_1 = results; _i < results_1.length; _i++) { var result = results_1[_i]; if (result.isOk()) { okResult.push(result.value); } else { return result; } } return new exports.Ok(okResult); } Result.all = all; /** * Parse a set of `Result`s, short-circuits when an input value is `Ok`. * If no `Ok` is found, returns an `Err` containing the collected error values */ function any(results) { var errResult = []; // short-circuits for (var _i = 0, results_2 = results; _i < results_2.length; _i++) { var result = results_2[_i]; if (result.isOk()) { return result; } else { errResult.push(result.error); } } // it must be a Err return new exports.Err(errResult); } Result.any = any; /** * Wrap an operation that may throw an Error (`try-catch` style) into checked exception style * @param op The operation function */ function wrap(op) { try { return new exports.Ok(op()); } catch (e) { return new exports.Err(e); } } Result.wrap = wrap; /** * Wrap an async operation that may throw an Error (`try-catch` style) into checked exception style * @param op The operation function */ function wrapAsync(op) { try { return op() .then(function (val) { return new exports.Ok(val); }) .catch(function (e) { return new exports.Err(e); }); } catch (e) { return Promise.resolve(new exports.Err(e)); } } Result.wrapAsync = wrapAsync; /** * Partitions a set of results, separating the `Ok` and `Err` values. */ function partition(results) { return results.reduce(function (_a, v) { var oks = _a[0], errors = _a[1]; return v.isOk() ? [__spreadArray(__spreadArray([], oks, true), [v.value], false), errors] : [oks, __spreadArray(__spreadArray([], errors, true), [v.error], false)]; }, [[], []]); } Result.partition = partition; function isResult(val) { return val instanceof exports.Err || val instanceof exports.Ok; } Result.isResult = isResult; })(Result || (exports.Result = Result = {})); //# sourceMappingURL=result.js.map