abolish
Version:
A javascript object validator.
63 lines (62 loc) • 1.68 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.assertType = assertType;
exports.isType = isType;
exports.arrayIsTypeOf = arrayIsTypeOf;
/**
* Check if a variable is type of the given types.
* Throw an error if it is not.
* @param option
* @param type
* @param name
*/
function assertType(option, type, name = "Options") {
const valid = isType(option, type);
if (!valid)
throw new TypeError(`${name} must be typeof [${type}], but [${typeof option}] was given.`);
return true;
}
/**
* Check if a variable is type of the given types.
* @param option
* @param type
*/
function isType(option, type) {
if (typeof type === "string") {
if (type === "array" && Array.isArray(option))
return true;
else
return typeof option === type;
}
else {
const hasArrayInTypes = type.includes("array");
if (!hasArrayInTypes && type.includes(typeof option)) {
return true;
}
else
return hasArrayInTypes && (type.includes(typeof option) || Array.isArray(option));
}
}
/**
* Function that checks if an array values is of the given types.
*/
function arrayIsTypeOf(arr, types) {
if (typeof types === "string")
types = [types];
if (!arr.length)
return true;
/**
* Check if the array values is of the given types.
*/
return !arr.some((value) => {
try {
assertType(value, types);
return false;
}
catch (e) {
// Stop on first error.
// This reduces the amount of checks.
return true;
}
});
}