UNPKG

avocado-type-checker

Version:

A javascript type checker. Also a tasty fruit with megafauna dispersal syndrome, leading to an evolutionary anachronism.

1 lines 2.03 kB
!function(t,r){"object"==typeof exports&&"undefined"!=typeof module?module.exports=r():"function"==typeof define&&define.amd?define(r):t.avocado=r()}(this,function(){"use strict";var t=function(t,r){if(!Array.isArray(t))throw new Error("arr needs to be an array");if("string"!=typeof r)throw new Error("typeName needs to be string");for(var e=0;e<t.length;e++)if(t[e].typeName===r)return e;return-1},r=[],e=function(t,r){if(1===arguments.length)return e.type(t);var n,o=function(t){if(!arguments.length){if("object"==typeof n){var e={};for(var i in n)e[i]=n[i]();return e}return n}if("object"==typeof(n=r(t)))for(var f in n)o[f]=n[f]};return o(t),o};e.type=function(){var n,o,i;if(0===arguments.length)throw new Error("av.type requires at least one argument.");if(o=arguments[0],n=t(r,o),1===arguments.length){if(-1===n)throw new Error("type not found");return r[n].type}if(2===arguments.length){if(i=arguments[1],-1!==n)throw new Error("type specification already exists.");if("function"==typeof i)r.push({typeName:o,type:function(t){return e(t,i)}});else{if("object"!=typeof i)throw new Error("argument 2 typeData must be either a function or object.");r.push({typeName:o,type:function(t){return e(t,function(t){if("object"==typeof t){var r={};for(var n in i)r[n]=e.type(i[n])(t[n]);return r}throw"not a valid object"})}})}return e}throw new Error("invalid amount of arguments for av.type()")},e.isValid=function(t,r){try{return t(r),!0}catch(t){return!1}},e.type("boolean",function(t){if("boolean"==typeof t)return t;throw new Error("d is not boolean")});var n=function(t){return"number"==typeof t&&isFinite(t)&&t>-9007199254740992&&t<9007199254740992&&Math.floor(t)===t};return e.type("int",function(t){if(!n(t))throw new Error("d is not an integer");return t}),e.type("float",function(t){if("number"!=typeof t)throw"d is not a number";return t}),e.type("string",function(t){if("string"==typeof t)return t;throw"d is not a string"}),e.type("collection",function(t){if(t&&t.constructor===Array)return t;throw"not an array"}),e});