typeof-arguments
Advanced tools
Comparing version 3.0.3 to 3.1.0
142
index.js
@@ -0,53 +1,20 @@ | ||
/* global Function */ | ||
const ofType = require('of-type'); | ||
const cliColor = require('cli-color'); | ||
const error = cliColor.red; | ||
const warn = cliColor.bgYellow.blue; | ||
module.exports = function(a,o,c){ | ||
const errArguments = warn('typeof-arguments')+': '+error('Invalid module argument. The first argument must indicate [Object Arguments] object.'); | ||
const errTypes = warn('typeof-arguments')+': '+error('Invalid module argument. The second argument must be of type [Array].'); | ||
const errItems = warn('typeof-arguments')+': '+error('Invalid module argument. Each item of the second [Array] argument must be of type [String|RegExp].'); | ||
const isO = ofType(a,'arguments'); | ||
const isA = ofType(o,'array'); | ||
if(!isO){ | ||
var err = new Error(errArguments); | ||
throw err; | ||
} | ||
if(!isA){ | ||
var err = new Error(errTypes); | ||
throw err; | ||
} | ||
if(!isO||!isA) return; | ||
const clb = ofType(c,'function'); | ||
var r = true; | ||
for(var x in o){ | ||
var t = o[x]; | ||
if(!ofType(o[x],'string|regexp')){ | ||
var err = new Error(errItems); | ||
throw err; | ||
} | ||
var isStr = ofType(t,'string'); | ||
var res = ofType(a[x],t); | ||
if(!res){ | ||
r = false; | ||
var act = ofType(a[x],'undefined') ? 'undefined':ofType(a[x],'null') ? 'null':ofType(a[x],'arguments') ? 'object Arguments':a[x].constructor.name; | ||
var truthyFalsy = ''; | ||
var exp = isStr ? | ||
t.split('|').map((i)=>{ | ||
const truthy = i==='truthy'; | ||
const falsy = i==='falsy'; | ||
const args = i==='arguments'; | ||
const nullOrUnd = i==='null'||i==='undefined'; | ||
truthyFalsy = truthy ? '<<falsy>> ':falsy ? '<<truthy>> ':truthyFalsy; | ||
return nullOrUnd||truthy||falsy||args ? i.toLowerCase():i[0].toUpperCase()+i.slice(1).toLowerCase(); | ||
}).join('|'): | ||
(()=>{ | ||
var r = t.toString(); | ||
truthyFalsy = r.match(/truthy/) ? '<<falsy>> ':r.match(/falsy/) ? '<<truthy>> ':''; | ||
return r; | ||
})(); | ||
var msg = `Invalid argument [${x}]. The [${act}] ${truthyFalsy}argument has been passed, while the ${isStr ? `[${exp}] one`:`argument of the type matching the regular expression: ${exp}`} is expected.`; | ||
const warn = cliColor.blue.bgYellow; | ||
module.exports = function(getArgumentsObject,getExpectedArray,callbackFunction){ | ||
const clb = ofType(callbackFunction,'function'); | ||
validateArguments(getArgumentsObject,getExpectedArray); | ||
for(let item in getExpectedArray){ | ||
if(!ofType(getArgumentsObject[item],getExpectedArray[item])){ | ||
var actual = getActualType(getArgumentsObject[item]); | ||
var types = getExpectedTypes(getExpectedArray[item]); | ||
var message = `Invalid argument [${item}]. The [${actual}] ${types.truthness}argument has been passed, while the ${types.message} is expected.`; | ||
if(clb){ | ||
c({actual:act,expected:exp,message:msg,index:Number(x)}); | ||
callbackFunction({actual:actual,expected:types.expected,message:message,index:Number(item)}); | ||
return false; | ||
} else { | ||
var err = new TypeError(error(msg)); | ||
var err = new TypeError(message); | ||
throw err; | ||
@@ -57,3 +24,80 @@ } | ||
} | ||
return r; | ||
}; | ||
return true; | ||
}; | ||
function validateArguments(a,o){ | ||
const errActual = warn('typeof-arguments')+': '+error('Invalid module argument. The first argument must be [arguments] Object.'); | ||
const errExpected = warn('typeof-arguments')+': '+error('Invalid module argument. The second argument must be of type [Array].'); | ||
const isActualArguments = ofType(a,'arguments'); | ||
const isExpectedArray = ofType(o,Array); | ||
if(!isActualArguments){ | ||
var err = new TypeError(errActual); | ||
throw err; | ||
} | ||
if(!isExpectedArray){ | ||
var err = new TypeError(errExpected); | ||
throw err; | ||
} | ||
} | ||
function getActualType(actualValue){ | ||
if(ofType(actualValue,null)) return "null"; | ||
if(ofType(actualValue,undefined)) return "undefined"; | ||
if(ofType(actualValue,'arguments')) return "arguments"; | ||
return actualValue.constructor.name; | ||
} | ||
function getExpectedTypes(expectedType){ | ||
var types = [whenString,whenRegExp,whenObject,whenArray]; | ||
for(var i in types){ | ||
var check = types[i](expectedType); | ||
if(check) return check; | ||
} | ||
const err = warn('typeof-arguments')+': '+error(`The expected type is not callable.`); | ||
throw new TypeError(err); | ||
} | ||
function whenString(stringType){ | ||
if(!ofType(stringType,String)) return null; | ||
var msg = `argument of type matching string expression "${stringType}"`; | ||
var truthness = ''; | ||
stringType.split('|').forEach((i)=>{ | ||
if(i.toLowerCase()==='truthy') truthness = '<<falsy>> '; | ||
if(i.toLowerCase()==='falsy') truthness = '<<truthy>> '; | ||
}); | ||
return {message:msg,truthness:truthness,expected:stringType}; | ||
} | ||
function whenRegExp(regType){ | ||
if(!ofType(regType,RegExp)) return null; | ||
var msg = `argument of type matching regular expression ${regType}`; | ||
return {message:msg,truthness:truthness(regType),expected:regType.toString()}; | ||
function truthness(regType){ | ||
var isCaseInsensitive = regType.flags.match(/i/); | ||
var str = regType.toString(); | ||
str = isCaseInsensitive ? str.toLowerCase():str; | ||
if(str.match(/truthy/)) return '<<falsy>> '; | ||
if(str.match(/falsy/)) return '<<truthy>> '; | ||
return ''; | ||
}; | ||
} | ||
function whenObject(objectType){ | ||
if(ofType(objectType,null)) return {message:`argument of type [null]`,truthness:'',expected:'null'}; | ||
if(ofType(objectType,undefined)) return {message:`argument of type [undefined]`,truthness:'',expected:'undefined'}; | ||
if(ofType(objectType,Function)) return {message:`argument of type [${objectType.name}]`,truthness:'',expected:objectType.name}; | ||
return null; | ||
} | ||
function whenArray(arrayTypes){ | ||
if(!ofType(arrayTypes,Array)) return null; | ||
var types = {}; | ||
for(var i in arrayTypes){ | ||
var exp = whenObject(arrayTypes[i]); | ||
if(ofType(exp,null)) return null; | ||
types[exp.expected] = exp.expected; | ||
} | ||
var expected = Object.getOwnPropertyNames(types).join('|'); | ||
return {message:`argument of type [${expected}]`,truthness:'',expected:expected}; | ||
} |
{ | ||
"name": "typeof-arguments", | ||
"version": "3.0.3", | ||
"version": "3.1.0", | ||
"description": "Validate the types of arguments passed to the function.", | ||
"main": "index.js", | ||
"scripts": { | ||
"test": "echo \"Error: no test specified\" && exit 1" | ||
"test": "node tests/jasmine.conf.js" | ||
}, | ||
@@ -20,4 +20,4 @@ "keywords": [ | ||
"dependencies": { | ||
"of-type": "^1.0.6", | ||
"cli-color": "^1.2.0" | ||
"cli-color": "^1.2.0", | ||
"of-type": "^2.1.0" | ||
}, | ||
@@ -31,3 +31,7 @@ "homepage": "https://github.com/devrafalko/typeof-arguments#readme", | ||
"url": "git+https://github.com/devrafalko/typeof-arguments.git" | ||
}, | ||
"devDependencies": { | ||
"jasmine": "^2.8.0", | ||
"jasmine-spec-reporter": "^4.2.1" | ||
} | ||
} |
217
readme.md
@@ -5,2 +5,3 @@ # Description | ||
* Also check out [**`of-type`**](https://www.npmjs.com/package/of-type) package that checks whether the given value is of particular type *(`typeof-arguments` is based on `of-type` package)*. | ||
* Also check out [**`typeof-properties`**](https://www.npmjs.com/package/typeof-properties) to validate value types of the properties of objects. | ||
@@ -11,37 +12,75 @@ # Installation | ||
```javascript | ||
var args = require('typeof-arguments'); | ||
var argType = require('typeof-arguments'); | ||
``` | ||
# Usage | ||
### `args(arguments,types[,callback])` | ||
##### `arguments` **[Object]** | ||
### `argType(actual,expected[,callback])` | ||
##### `actual` **[Object]** | ||
* It should always indicate the enclosing function **`arguments`** object | ||
##### `types` **[Array]** of **[String|RegExp]** items. | ||
* It should contain the list of **expected types** for each *(or chosen)* enclosing function parameter. The **`types[2]`** specifies the expected type(s) of **`arguments[2]`**, etc. | ||
* Possible values: `'null'`, `'undefined'`, or any value equal to `constructor.name`, eg. `'string'`, `'number'`, `'regexp'`, `'array'`, `'object'`, `'boolean'`,`'buffer'`, etc. | ||
* The **`types`** [String] is case insensitive: `'String'`, `'string'`, `'StRiNg'` checks if the **`arguments`** item is of type [String]. For **`types`** [RegExp] case insensitivity use `i` flag, eg.: `/String/`, `/string/i`, `/sTrInG/i` | ||
* The **`types`** [String] can contain multiple allowed types, separated with `|`, eg: `'array|object'`, `'boolean|number|null|undefined'`, `'string|number'`. For **`types`** [RegExp] multiple values use `(x|y)` expression, eg: `/(string|number)/i` | ||
##### Extra types: | ||
* The **`types`** can contain the value: `'arguments'`. It returns `true` for the `arguments` Object | ||
* The **`types`** can contain the value: `'truthy'`. It returns `true` for the **`arguments`** item's values like: `"abc"`, `true`, `1`, `{}`, `[]`,`function(){}`, etc. | ||
* The **`types`** can contain the value: `'falsy'`. It returns `true` for the **`arguments`** item's values like: `""`, `false`, `0`, `null`, `undefined`, etc. | ||
* The **`types`** can contain the value: `''` or `'any'`, then it returns `true` for the **`arguments`** item of **any type**. Use it if you do not want to check the type of the particular **`arguments`** item, eg. `['string','any','object|array']` | ||
##### `expected` **[Array]** | ||
* It should contain the [Array] list of **expected types** for each subsequent argument passed through the enclosing function. | ||
* The [Array] `expected` item's index coheres with the index of `actual` argument item passed through the enclosing function. | ||
* The values of [Array] `expected` items indicate the expected types of the coherent `actual` arguments passed through the enclosing function. | ||
##### The `expected` Types | ||
There are three ways to check the type of the arguments: | ||
* by **string expression** values | ||
* by **regular expression** values | ||
* by **constructor functions**, `null` or `undefined` values | ||
##### [Object:String] | ||
* Possible values: `'null'`, `'undefined'`, or any value equal to `constructor.name`, eg: `'string'`, `'number'`, `'regexp'`, `'array'`, `'object'`, `'boolean'`,`'buffer'`, etc. | ||
* The [String] value is case insensitive: `'String'`, `'string'`, `'StRiNg'` checks if the argument is of type [String]. | ||
* The [String] value can contain multiple allowed types, separated with `|`. eg: `'array|object'` checks if the argument is of type [Array] **`OR`** of type [Object]. | ||
```javascript | ||
var args = require('typeof-arguments'); | ||
test('Paul',26); | ||
hello('hello', "world!"); | ||
function test(){ | ||
argType(arguments,['string', 'number|string|null']); | ||
} | ||
``` | ||
function hello(paramA,paramB){ | ||
args(arguments,['string','string']); | ||
##### [Object:RegExp] | ||
* Possible values: `/null/`, `/undefined/`, or any value matching the `constructor.name`, eg: `/String/`, `/Number/`, `/RegExp/`, `/Array/`, `/Object/`, `/Boolean/`,`/Buffer/`, `/Promise/`, etc. | ||
* For the case insensitivity use `i` flag, eg: `/string/i`, `/regexp/i`, `/typeerror/i` | ||
* For multiple values use regexp `(x|y)` expression, eg: `/String|Number/`, `/TypeError|Error/` | ||
* Use another regexp features: | ||
* eg. `/(Type|Range|Syntax)Error/` will match `TypeError`, `RangeError` and `SyntaxError` | ||
* eg. `/[A-Z].+/` will match `String`, `Array`, but will not match `undefined`, `null`, etc. | ||
```javascript | ||
test('Paul',26); | ||
function test(){ | ||
argType(arguments,[/string/i, /num|string|null/i]); | ||
} | ||
``` | ||
##### [Object:null|undefined|Function|Array] | ||
* Possible values: `null`, `undefined` or any **constructor** object, eg: `String`, `TypeError`, `Promise`, `Array`, etc. | ||
* For multiple values use array, eg: `[String,Object,Array,null]` | ||
```javascript | ||
test('Paul',26); | ||
function test(){ | ||
argType(arguments,[String, [Number,String,null]]); | ||
} | ||
``` | ||
##### Extra types: | ||
* The value can be: `'arguments'` or `/arguments/`. It returns `true` if the argument is defined as the `arguments` Object | ||
* The value can be: `'truthy'` or `/truthy/`. It returns `true` if the argument has the value like: `"abc"`, `true`, `1`, `{}`, `[]`,`function(){}`, etc. | ||
* The value can be: `'falsy'` or `/falsy/`. It returns `true` if the argument has the value like: `""`, `false`, `0`, `null`, `undefined`, etc. | ||
* The value can be: `''` or `'any'` or `/any/` or `[]`, It returns `true` if the argument is of **any type**. | ||
##### `callback` **[Function]** *(optional)* | ||
* if **not passed**, the **TypeError** with **default message** will be **thrown** to the console, if the argument passed to the function is invalid. | ||
* The TypeError default message is eg.: | ||
* `Invalid argument [0]. The [String] argument has been passed, while the [Number] one is expected.` | ||
* `Invalid argument [2]. The [undefined] argument has been passed, while the argument of the type matching the regular expression: /array|object/i is expected.` | ||
* `Invalid argument [1]. The [Number] <<truthy>> argument has been passed, while the [falsy|String] one is expected.` | ||
* `Invalid argument [0]. The [Number] argument has been passed, while the argument of type [String] is expected.` | ||
* `Invalid argument [2]. The [null] argument has been passed, while the argument of type matching string expression "boolean" is expected.` | ||
* `Invalid argument [1]. The [null] <<falsy>> argument has been passed, while the argument of type matching string expression "truthy|undefined" is expected.` | ||
* `Invalid argument [0]. The [undefined] argument has been passed, while the argument of type matching regular expression /string/i is expected.` | ||
* if **passed**, the default TypeError **will not be thrown** to the console and the user can decide what to do inside the `callback` function. | ||
@@ -54,16 +93,15 @@ * Use callback function if you don't want to stop your code execution by default *(no callback)* **`throw`** statement! | ||
* **`actual`** | ||
indicates the actual type of the argument passed through the enclosing function, eg. `'[String]'` | ||
indicates the actual type of the argument passed through the enclosing function, eg. `"String"` | ||
* **`expected`** | ||
indicates the type(s) expected by the user, eg. `'[Array]'`, `'[Boolean|Number]'`, `/array|object/i` | ||
indicates the type(s) expected by the user, eg. `"Array"`, `"Boolean|Number"`, `"/array|object/i"` | ||
* **`message`** | ||
is the default error [String] message, that you can use for example to throw an error in the callback function | ||
is the default error [String] message, that you can use eg. to log in the console | ||
```javascript | ||
var args = require('typeof-arguments'); | ||
var argType = require('typeof-arguments'); | ||
hello(10, "hello!"); | ||
hello("Paul", 26); | ||
function hello(paramA,paramB){ | ||
args(arguments,['any','string|number'],(o)=>{ | ||
function hello(name,age){ | ||
argType(arguments,[String,'string|number'],(o)=>{ | ||
console.error(o.message); | ||
@@ -77,7 +115,7 @@ //console.error('Not good! Use ' + o.expected + ' instead of ' + o.actual + ' for argument ' + o.index); | ||
#### Return value | ||
The function `args()` returns `true` when all arguments passed through the enclosing function are of **valid** types. | ||
The function `args()` returns `false` when at least **one** of the arguments passed through the enclosing function is of **invalid** type. | ||
The function `argType()` returns `true` when all arguments passed through the enclosing function are of **valid** types. | ||
The function `argType()` returns `false` when at least **one** of the arguments passed through the enclosing function is of **invalid** type. | ||
```javascript | ||
var args = require('typeof-arguments'); | ||
var argType = require('typeof-arguments'); | ||
@@ -87,3 +125,3 @@ hello("hello","world!"); | ||
function hello(paramA,paramB){ | ||
var areValid = args(arguments,['string','string']); | ||
var areValid = argType(arguments,['string','string']); | ||
if(!areValid) return; //stop executing code if at least one argument is of invalid type | ||
@@ -94,28 +132,37 @@ //your code here... | ||
# Tests | ||
``` | ||
> git clone https://github.com/devrafalko/typeof-arguments.git | ||
> cd typeof-arguments | ||
> npm install | ||
> npm test | ||
> npm test deep //displays error messages | ||
``` | ||
# Samples | ||
```javascript | ||
var args = require('typeof-arguments'); | ||
var argType = require('typeof-arguments'); | ||
function hello(paramA,paramB,paramC){ | ||
args(arguments,['number|string','any','null|array']); | ||
function test(paramA,paramB,paramC){ | ||
argType(arguments,['number|string','any','null|array']); | ||
} | ||
hello("hello", "it's me!", null); | ||
test("hello", "it's me!", null); | ||
//no errors | ||
hello(10, 20, [1,2,3]); | ||
test(10, 20, [1,2,3]); | ||
//no errors | ||
hello(true,20,null); | ||
//Invalid argument [0]. The [Boolean] argument has been passed, while the [Number|String] one is expected. | ||
test(true,20,null); | ||
//Invalid argument [0]. The [Boolean] argument has been passed, while the argument of type matching string expression "number|string" is expected. | ||
hello({name:'Paul'},false,/test/); | ||
//Invalid argument [0]. The [Object] argument has been passed, while the [Number|String] one is expected. | ||
//Invalid argument [2]. The [RegExp] argument has been passed, while the [null|Array] one is expected. | ||
test({name:'Paul'},false,/test/); | ||
//Invalid argument [0]. The [Object] argument has been passed, while the argument of type matching string expression "number|string" is expected. | ||
//Invalid argument [2]. The [RegExp] argument has been passed, while the argument of type matching string expression "null|array" is expected. | ||
hello(10,20,null,30,40,50,60,70); | ||
test(10,20,null,30,40,50,60,70); | ||
//no errors | ||
hello(10); | ||
//Invalid argument [2]. The [undefined] argument has been passed, while the [null|Array] one is expected. | ||
test(10); | ||
//Invalid argument [2]. The [undefined] argument has been passed, while the argument of type matching string expression "null|array" is expected. | ||
``` | ||
@@ -125,25 +172,25 @@ | ||
```javascript | ||
var args = require('typeof-arguments'); | ||
var argType = require('typeof-arguments'); | ||
function hello(paramA,paramB){ | ||
args(arguments,['truthy|string',/(regexp|falsy)/i]); | ||
function test(paramA,paramB){ | ||
argType(arguments,['truthy|string',/(regexp|falsy)/i]); | ||
} | ||
hello(); | ||
//Invalid argument [0]. The [undefined] <<falsy>> argument has been passed, while the [truthy|String] one is expected. | ||
test(); | ||
//Invalid argument [0]. The [undefined] <<falsy>> argument has been passed, while the argument of type matching string expression "truthy" is expected. | ||
hello('',''); | ||
//Invalid argument [0]. The [String] <<falsy>> argument has been passed, while the [truthy|String] one is expected. | ||
test('',''); | ||
//Invalid argument [0]. The [String] <<falsy>> argument has been passed, while the argument of type matching string expression "truthy" is expected. | ||
hello(1,0); | ||
test(1,0); | ||
//no errors | ||
hello(0,1); | ||
//Invalid argument [0]. The [Number] <<falsy>> argument has been passed, while the [truthy|String] one is expected. | ||
//Invalid argument [1]. The [Number] <<truthy>> argument has been passed, while the argument of the type matching the regular expression: /(regexp|falsy)/i is expected. | ||
test(0,1); | ||
//Invalid argument [0]. The [Number] <<falsy>> argument has been passed, while the argument of type matching string expression "truthy" is expected. | ||
//Invalid argument [1]. The [Number] <<truthy>> argument has been passed, while the argument of type matching regular expression /(regexp|falsy)/i is expected. | ||
hello([1,2,3],/test/); | ||
test([1,2,3],/test/); | ||
//no errors | ||
hello('hello',null); | ||
test('hello',null); | ||
//no errors | ||
@@ -154,55 +201,25 @@ ``` | ||
```javascript | ||
var args = require('typeof-arguments'); | ||
var argType = require('typeof-arguments'); | ||
function hello(paramA,paramB,paramC){ | ||
args(arguments,[/date|object|array/i,/^html.*element$/i,/^html(ul|li)element/i]); | ||
function test(paramA,paramB){ | ||
type(arguments,[String,'any','any',Number,/((syntax|type)error)|falsy/i]); | ||
} | ||
var div = document.createElement('DIV'); | ||
var ul = document.createElement('UL'); | ||
var li = document.createElement('LI'); | ||
var a = document.createElement('A'); | ||
test(); | ||
//Invalid argument [0]. The [undefined] argument has been passed, while the argument of type [String] is expected. | ||
hello([1,2,3],null); | ||
//Invalid argument [1]. The [null] argument has been passed, while the argument of the type matching the regular expression: /^html.*element$/i is expected. | ||
hello([1,2,3],div,ol); | ||
test('Paul',null,false,10); | ||
//no errors | ||
hello([1,2,3],div,ul); | ||
test('Paul',null,false,10,new TypeError('error')); | ||
//no errors | ||
hello(new Date(),a,div); | ||
//Invalid argument [2]. The [HTMLDivElement] argument has been passed, while the argument of the type matching the regular expression: /^html[uo]listelement/i is expected. | ||
``` | ||
### more samples | ||
```javascript | ||
var args = require('typeof-arguments'); | ||
function hello(paramA,paramB){ | ||
args(arguments,['arguments|falsy',/((syntax|type)error)|falsy/i]); | ||
} | ||
function returnArguments(){ | ||
return arguments; | ||
} | ||
hello(null,new TypeError()); | ||
test('Paul',null,false,10,false); | ||
//no errors | ||
hello(false,new SyntaxError()); | ||
//no errors | ||
test('Paul'); | ||
//Invalid argument [3]. The [undefined] argument has been passed, while the argument of type [Number] is expected. | ||
hello(0,new Error()); | ||
//Invalid argument [1]. The [Error] argument has been passed, while the argument of the type matching the regular expression: /((syntax|type)error)|boolean/i is expected. | ||
hello(1,false); | ||
//Invalid argument [0]. The [Number] <<truthy>> argument has been passed, while the [arguments|falsy] one is expected. | ||
hello(returnArguments,new TypeError()); | ||
//Invalid argument [0]. The [Function] <<truthy>> argument has been passed, while the [arguments|falsy] one is expected. | ||
hello(returnArguments(),new TypeError()); | ||
//no errors | ||
test('Paul',true,true,10,new Error('error')); | ||
//Invalid argument [4]. The [Error] <<truthy>> argument has been passed, while the argument of type matching regular expression /((syntax|type)error)|falsy/i is expected. | ||
``` |
License Policy Violation
LicenseThis package is not allowed per your license policy. Review the package's license to ensure compliance.
Found 1 instance in 1 package
Major refactor
Supply chain riskPackage has recently undergone a major refactor. It may be unstable or indicate significant internal changes. Use caution when updating to versions that include significant changes.
Found 1 instance in 1 package
Dynamic require
Supply chain riskDynamic require can indicate the package is performing dangerous or unsafe dynamic code execution.
Found 1 instance in 1 package
License Policy Violation
LicenseThis package is not allowed per your license policy. Review the package's license to ensure compliance.
Found 1 instance in 1 package
No tests
QualityPackage does not have any tests. This is a strong signal of a poorly maintained or low quality package.
Found 1 instance in 1 package
30438
12
512
0
217
2
3
1
+ Addedof-type@2.2.0(transitive)
- Removedof-type@1.0.7(transitive)
Updatedof-type@^2.1.0