UNPKG

1.31 kBJavaScriptView Raw
1// Copyright 2017-2022 @polkadot/util authors & contributors
2// SPDX-License-Identifier: Apache-2.0
3import { isFunction } from "./is/function.js";
4
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 */
21export function assert(condition, message) {
22 if (!condition) {
23 throw new Error(isFunction(message) ? message() : message);
24 }
25}
26/**
27 * @name assertReturn
28 * @description Returns when the value is not undefined/null, otherwise throws assertion error
29 */
30
31export function assertReturn(value, message) {
32 assert(value !== undefined && value !== null, message);
33 return value;
34}
35/**
36 * @name assertUnreachable
37 * @description An assertion helper that ensures all codepaths are followed
38 */
39
40export function assertUnreachable(x) {
41 throw new Error(`This codepath should be unreachable. Unhandled input: ${x}`);
42}
\No newline at end of file