UNPKG

js-draw

Version:

Draw pictures using a pen, touchscreen, or mouse! JS-draw is a drawing library for JavaScript and TypeScript.

87 lines (86 loc) 2.6 kB
"use strict"; // Note: Arrow functions cannot be used for type assertions. See // https://github.com/microsoft/TypeScript/issues/34523 Object.defineProperty(exports, "__esModule", { value: true }); exports.assertUnreachable = assertUnreachable; exports.assertIsNumber = assertIsNumber; exports.assertIsString = assertIsString; exports.assertIsArray = assertIsArray; exports.assertIsNumberArray = assertIsNumberArray; exports.assertIsStringArray = assertIsStringArray; exports.assertIsBoolean = assertIsBoolean; exports.assertTruthy = assertTruthy; exports.assertIsObject = assertIsObject; /** * Compile-time assertion that a branch of code is unreachable. * @internal */ function assertUnreachable(key) { // See https://stackoverflow.com/a/39419171/17055750 throw new Error(`Should be unreachable. Key: ${key}.`); } /** * Throws an exception if the typeof given value is not a number or `value` is NaN. * * @example * ```ts * const foo: unknown = 3; * assertIsNumber(foo); * * assertIsNumber('hello, world'); // throws an Error. * ``` */ function assertIsNumber(value, allowNaN = false) { if (typeof value !== 'number' || (!allowNaN && isNaN(value))) { throw new Error('Given value is not a number'); } } /** Throws an `Error` if the given `value` is not a `string`. */ function assertIsString(value) { if (typeof value !== 'string') { throw new Error('Given value is not a string'); } } function assertIsArray(values) { if (!Array.isArray(values)) { throw new Error('Asserting isArray: Given entity is not an array'); } } /** * Throws if any of `values` is not of type number. */ function assertIsNumberArray(values, allowNaN = false) { assertIsArray(values); assertIsNumber(values.length); for (const value of values) { assertIsNumber(value, allowNaN); } } /** * Throws if any of `values` is not of type `string`. */ function assertIsStringArray(values) { assertIsArray(values); assertIsNumber(values.length); for (const value of values) { assertIsString(value); } } /** * Throws an exception if `typeof value` is not a boolean. */ function assertIsBoolean(value) { if (typeof value !== 'boolean') { throw new Error('Given value is not a boolean'); } } function assertTruthy(value) { if (!value) { throw new Error(`${JSON.stringify(value)} is not truthy`); } } function assertIsObject(value) { if (typeof value !== 'object') { throw new Error(`AssertIsObject: Given entity is not an object (type = ${typeof value})`); } }