UNPKG

@bubblewrap/core

Version:

Core Library to generate, build and sign TWA projects

98 lines (97 loc) 2.88 kB
"use strict"; /* * Copyright 2020 Google Inc. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ Object.defineProperty(exports, "__esModule", { value: true }); exports.Result = void 0; /** * While throwing exceptions show be used to handle truly exception cases, `Result<V, E>` can be * used to handle cases where failures are expected, therefore not really exceptions. * * The outcome can be verified with `Result.isOk()`: * ``` * const result = someMethod(); * if (result.isOk()) { * const value = result.unwrap(); * ... * } * ``` */ class Result { constructor(result) { this._result = result; } /** * Creates a new `ok` Result, with the outcome `value`. */ // eslint-disable-next-line @typescript-eslint/no-explicit-any static ok(value) { return new Result({ type: 'ok', value: value, }); } /** * Creates a new `error` Result, with the outcome `error`. */ // eslint-disable-next-line @typescript-eslint/no-explicit-any static error(error) { return new Result({ type: 'error', error: error, }); } /** * Returns the value if this result is `ok`. Otherwise, throws `E`. */ unwrap() { if (this._result.type === 'error') { throw this._result.error; } return this._result.value; } /** * If the result is an Error, returns `defaultValue`. Otherwise returns the result value. */ unwrapOr(defaultValue) { if (this._result.type === 'error') { return defaultValue; } return this._result.value; } /** * If the result is an Error, returns the `Error` instance without throwing. Otherwise, * throws an Exception. */ unwrapError() { if (this._result.type === 'error') { return this._result.error; } throw new Error('Expected result to be "ok", but it is "error"'); } /** * @returns `true` if the result is `ok`. `false` if it is an `Error`. */ isOk() { return this._result.type === 'ok'; } /** * @returns `true` if the result is an `Error`. `false` if the result is `ok`. */ isError() { return this._result.type === 'error'; } } exports.Result = Result;