Debian Codegraph @

node/@xterm/xterm/src/vs/base/common/assert.ts

raw
1 /*---------------------------------------------------------------------------------------------
2 * Copyright (c) Microsoft Corporation. All rights reserved.
3 * Licensed under the MIT License. See License.txt in the project root for license information.
4 *--------------------------------------------------------------------------------------------*/
5
6 import { BugIndicatingError, onUnexpectedError } from 'vs/base/common/errors';
7
8 /**
9 * Throws an error with the provided message if the provided value does not evaluate to a true Javascript value.
10 *
11 * @deprecated Use `assert(...)` instead.
12 * This method is usually used like this:
13 * ```ts
14 * import * as assert from 'vs/base/common/assert';
15 * assert.ok(...);
16 * ```
17 *
18 * However, `assert` in that example is a user chosen name.
19 * There is no tooling for generating such an import statement.
20 * Thus, the `assert(...)` function should be used instead.
21 */
22 export function ok(value?: unknown, message?: string) {
23 if (!value) {
24 throw new Error(message ? `Assertion failed (${message})` : 'Assertion Failed');
25 }
26 }
27
28 export function assertNever(value: never, message = 'Unreachable'): never {
29 throw new Error(message);
30 }
31
32 export function assert(condition: boolean, message = 'unexpected state'): asserts condition {
33 if (!condition) {
34 throw new BugIndicatingError(`Assertion Failed: ${message}`);
35 }
36 }
37
38 /**
39 * Like assert, but doesn't throw.
40 */
41 export function softAssert(condition: boolean): void {
42 if (!condition) {
43 onUnexpectedError(new BugIndicatingError('Soft Assertion Failed'));
44 }
45 }
46
47 /**
48 * condition must be side-effect free!
49 */
50 export function assertFn(condition: () => boolean): void {
51 if (!condition()) {
52 // eslint-disable-next-line no-debugger
53 debugger;
54 // Reevaluate `condition` again to make debugging easier
55 condition();
56 onUnexpectedError(new BugIndicatingError('Assertion Failed'));
57 }
58 }
59
60 export function checkAdjacentItems<T>(items: readonly T[], predicate: (item1: T, item2: T) => boolean): boolean {
61 let i = 0;
62 while (i < items.length - 1) {
63 const a = items[i];
64 const b = items[i + 1];
65 if (!predicate(a, b)) {
66 return false;
67 }
68 i++;
69 }
70 return true;
71 }