Last active
March 22, 2018 06:23
-
-
Save Floofies/8594db95fbc391080fe65212e537379c to your computer and use it in GitHub Desktop.
Basic JavaScript Asserts for Type-Checking
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* assert - Logs or throws an Error if `boolean` is false, | |
* If `boolean` is `true`, nothing happens. | |
* If `errorType` is set, throws a new Error of type `errorType` instead of logging to console. | |
* @param {Boolean} boolean The activation Boolean. | |
* @param {String} message The message to log, or include in the Error. | |
* @param {Error} errorType = null If not `null`, throws a new error of `errorType`. | |
*/ | |
function assert(boolean, message, errorType = null) { | |
if (boolean) return; | |
if (errorType !== null && (errorType === Error || Error.isPrototypeOf(errorType))) { | |
throw new errorType(message); | |
} else { | |
console.error(message); | |
} | |
} | |
// Thunks to `assert` for method argument type checking. | |
assert.props = function (input, props, argName) { | |
for (var prop of props[Symbol.iterator]()) { | |
assert(prop in input, "Argument " + argName + " must have a \"" + prop + "\" property.", TypeError); | |
} | |
}; | |
assert.argType = (boolean, typeString, argName) => | |
assert(boolean, "Argument " + argName + " must be " + typeString, TypeError); | |
assert.string = (input, argName) => | |
assert.argType(typeof input === "string", "a String", argName); | |
assert.number = (input, argName) => | |
assert.argType(typeof input === "number", "a Number", argName); | |
assert.boolean = (input, argName) => | |
assert.argType(typeof input === "boolean", "a Boolean", argName); | |
assert.function = (input, argName) => | |
assert.argType(typeof input === "function", "a Function", argName); | |
assert.object = (input, argName) => | |
assert.argType(typeof (input) === "object", "an Object", argName); | |
assert.array = (input, argName) => | |
assert.argType(Array.isArray(input), "an Array", argName); | |
assert.container = (input, argName) => | |
assert.argType(input !== null && (Array.isArray(input) || typeof input === "object"), "an Object or Array", argName); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment