assert.js 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  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. import { BugIndicatingError, onUnexpectedError } from './errors.js';
  6. /**
  7. * Throws an error with the provided message if the provided value does not evaluate to a true Javascript value.
  8. *
  9. * @deprecated Use `assert(...)` instead.
  10. * This method is usually used like this:
  11. * ```ts
  12. * import * as assert from 'vs/base/common/assert';
  13. * assert.ok(...);
  14. * ```
  15. *
  16. * However, `assert` in that example is a user chosen name.
  17. * There is no tooling for generating such an import statement.
  18. * Thus, the `assert(...)` function should be used instead.
  19. */
  20. export function ok(value, message) {
  21. if (!value) {
  22. throw new Error(message ? `Assertion failed (${message})` : 'Assertion Failed');
  23. }
  24. }
  25. export function assertNever(value, message = 'Unreachable') {
  26. throw new Error(message);
  27. }
  28. /**
  29. * condition must be side-effect free!
  30. */
  31. export function assertFn(condition) {
  32. if (!condition()) {
  33. // eslint-disable-next-line no-debugger
  34. debugger;
  35. // Reevaluate `condition` again to make debugging easier
  36. condition();
  37. onUnexpectedError(new BugIndicatingError('Assertion Failed'));
  38. }
  39. }
  40. export function checkAdjacentItems(items, predicate) {
  41. let i = 0;
  42. while (i < items.length - 1) {
  43. const a = items[i];
  44. const b = items[i + 1];
  45. if (!predicate(a, b)) {
  46. return false;
  47. }
  48. i++;
  49. }
  50. return true;
  51. }