forked from catapult-project/catapult
-
Notifications
You must be signed in to change notification settings - Fork 0
/
assert.js
73 lines (68 loc) · 2.14 KB
/
assert.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
// Copyright (c) 2013 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
/**
* @fileoverview Assertion support.
*/
/**
* Verify |condition| is truthy and return |condition| if so.
* @template T
* @param {T} condition A condition to check for truthiness. Note that this
* may be used to test whether a value is defined or not, and we don't want
* to force a cast to Boolean.
* @param {string=} opt_message A message to show on failure.
* @return {T} A non-null |condition|.
*/
function assert(condition, opt_message) {
if (!condition) {
var message = 'Assertion failed';
if (opt_message)
message = message + ': ' + opt_message;
var error = new Error(message);
var global = function() { return this; }();
if (global.traceAssertionsForTesting)
console.warn(error.stack);
throw error;
}
return condition;
}
/**
* Call this from places in the code that should never be reached.
*
* For example, handling all the values of enum with a switch() like this:
*
* function getValueFromEnum(enum) {
* switch (enum) {
* case ENUM_FIRST_OF_TWO:
* return first
* case ENUM_LAST_OF_TWO:
* return last;
* }
* assertNotReached();
* return document;
* }
*
* This code should only be hit in the case of serious programmer error or
* unexpected input.
*
* @param {string=} opt_message A message to show when this is hit.
*/
function assertNotReached(opt_message) {
assert(false, opt_message || 'Unreachable code hit');
}
/**
* @param {*} value The value to check.
* @param {function(new: T, ...)} type A user-defined constructor.
* @param {string=} opt_message A message to show when this is hit.
* @return {T}
* @template T
*/
function assertInstanceof(value, type, opt_message) {
// We don't use assert immediately here so that we avoid constructing an error
// message if we don't have to.
if (!(value instanceof type)) {
assertNotReached(opt_message || 'Value ' + value +
' is not a[n] ' + (type.name || typeof type));
}
return value;
}