UNPKG

1.51 kBJavaScriptView Raw
1"use strict";
2Object.defineProperty(exports, "__esModule", { value: true });
3exports.assertUnreachable = exports.assertReturn = exports.assert = void 0;
4const function_js_1 = require("./is/function.js");
5/**
6 * @name assert
7 * @summary Checks for a valid test, if not Error is thrown.
8 * @description
9 * Checks that `test` is a truthy value. If value is falsy (`null`, `undefined`, `false`, ...), it throws an Error with the supplied `message`. When `test` passes, `true` is returned.
10 * @example
11 * <BR>
12 *
13 * ```javascript
14 * const { assert } from '@polkadot/util';
15 *
16 * assert(true, 'True should be true'); // passes
17 * assert(false, 'False should not be true'); // Error thrown
18 * assert(false, () => 'message'); // Error with 'message'
19 * ```
20 */
21function assert(condition, message) {
22 if (!condition) {
23 throw new Error((0, function_js_1.isFunction)(message)
24 ? message()
25 : message);
26 }
27}
28exports.assert = assert;
29/**
30 * @name assertReturn
31 * @description Returns when the value is not undefined/null, otherwise throws assertion error
32 */
33function assertReturn(value, message) {
34 assert(value !== undefined && value !== null, message);
35 return value;
36}
37exports.assertReturn = assertReturn;
38/**
39 * @name assertUnreachable
40 * @description An assertion helper that ensures all codepaths are followed
41 */
42function assertUnreachable(x) {
43 throw new Error(`This codepath should be unreachable. Unhandled input: ${x}`);
44}
45exports.assertUnreachable = assertUnreachable;