1 | import { isFunction } from './is/function.js';
|
2 | /**
|
3 | * @name assert
|
4 | * @summary Checks for a valid test, if not Error is thrown.
|
5 | * @description
|
6 | * 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.
|
7 | * @example
|
8 | * <BR>
|
9 | *
|
10 | * ```javascript
|
11 | * const { assert } from '@polkadot/util';
|
12 | *
|
13 | * assert(true, 'True should be true'); // passes
|
14 | * assert(false, 'False should not be true'); // Error thrown
|
15 | * assert(false, () => 'message'); // Error with 'message'
|
16 | * ```
|
17 | */
|
18 | export function assert(condition, message) {
|
19 | if (!condition) {
|
20 | throw new Error(isFunction(message)
|
21 | ? message()
|
22 | : message);
|
23 | }
|
24 | }
|
25 | /**
|
26 | * @name assertReturn
|
27 | * @description Returns when the value is not undefined/null, otherwise throws assertion error
|
28 | */
|
29 | export function assertReturn(value, message) {
|
30 | assert(value !== undefined && value !== null, message);
|
31 | return value;
|
32 | }
|
33 | /**
|
34 | * @name assertUnreachable
|
35 | * @description An assertion helper that ensures all codepaths are followed
|
36 | */
|
37 | export function assertUnreachable(x) {
|
38 | throw new Error(`This codepath should be unreachable. Unhandled input: ${x}`);
|
39 | }
|