typeh
Version:
A lightweight JS utility for advanced type detection, validation, and enforcement.
2 lines • 2.19 kB
JavaScript
/* typeh JavaScript Library v1.0.1 */
!function(e,t){"use strict";!function(e){var t,n={},i={},o=i.toString,r="int|float|string|bool|array|object|callable|iterable|mixed|null|false|true".split("|");function u(e){return null==e?e+"":"object"==typeof e||"function"==typeof e?i[o.call(e)]||"object":typeof e}function l(e){var t,n,i=/^-?\d*\.\d+$/;return null==e?e+"":("number"===(t=((n=e.constructor)&&n.name||Object.prototype.toString.call(e).slice(8,-1)).toLowerCase())&&(t="int"),"int"!==t||!isFinite(e)||!i.test(e)&&Number.isInteger(e)||(t="float"),t)}function s(e,t){var n,i,o="?"===e.slice(0,1),r=!1;for(e of(o&&(e=e.slice(1),null==t&&(r=!0)),n=e.split("|"),i=l(t),n)){if(e=e.toLowerCase(),t&&1===t.nodeType&&"htmlelement"===e&&t instanceof HTMLElement){r=!0;break}if("callable"===e&&"function"===i){r=!0;break}if("iterable"===e){r=null!=t&&"function"==typeof t[Symbol.iterator];break}if("boolean"==typeof t&&e===t+""||e===i.slice(0,4)){r=!0;break}if(e===i||e===u(t)||"mixed"===e){r=!0;break}}return r}function f(e,t){for(var n=0;n<e.length;n++)t(e[n],n)}n.setType=function(e){var n;for(n in e)t(n,e[n])},t=n.define=function(e,t){if(!s(e,t))throw new Error("The value must be of type ["+e+"], ["+l(t)+"] given.");return t},n.isCountable=function(e){return isArray(e)||e instanceof Map||e instanceof Set||null!=e&&isObject(e)&&isInteger(e.length)},n.isInteger=function(e){return isInt(e)},n.isDouble=function(e){return isFloat(e)},n.isNumeric=function(e){return(isInt(e)||isString(e))&&!isNaN(e-parseFloat(e))},n.isLong=function(e){return isInteger(e)&&Number.isInteger(e)},n.isScalar=function(e){return s("string|bool",e)||"number"==typeof e&&isFinite(e)},n.isInfinite=function(e){return e===1/0||e===-1/0},f("Boolean Number String Function Array Date RegExp Object Error Symbol".split(" "),(function(e){i["[object "+e+"]"]=e.toLowerCase()})),f(r,(function(e){n["_"+e]=function(n){return t("?"+e,n)},n[e]=function(n){return t(e,n)},"mixed"!==e&&(n["is"+e[0].toUpperCase()+e.slice(1)]=function(t){return s(e,t)})})),n.toType=l,n.isType=u,Object.assign(e,n),"undefined"!=typeof module&&module.exports?module.exports=n:window.typeh=n}(e)}("undefined"!=typeof globalThis?globalThis:this);