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