assert-args
Validate and format function arguments ( handles types and optionals)
Installation
npm install --save assert-args
Examples
assertArgs(arguments, validator)
Assert argument types and format arguments into an object
function something (foo, bar, baz, qux, corge) {
var args = assertArgs(arguments, {
'foo': 'object',
'[bar]': SomeClass,
'baz' : someTest
'qux': ['string', 'number']
'...corge': 'function'
})
foo = args.foo
bar = args.bar
baz = args.baz
qux = args.qux
corge = args.corge
}
Check out the examples below.
Type validations
- Supports '*', 'string', 'number', 'object', 'function', and classes (Array, RegExp, etc)
var args = assertArgs(arguments, {
'foo': 'string'
})
var args = assertArgs(arguments, {
'foo': ['string', 'number']
})
var args = assertArgs(arguments, {
'foo': Array
})
Custom validations
var args = assertArgs(arguments, {
'foo': customValidation
})
function customValidation (value) {
if (!value.bar) {
throw new Error('"bar" is required')
}
}
Required arguments
var args = assertArgs(arguments, {
'foo': 'string'
})
Optional arguments
var args = assertArgs(arguments, {
'[foo]': 'string'
})
Spread arguments
var args = assertArgs(arguments, {
'...foo': 'string',
'cb': 'function'
})
Full examples
var args = assertArgs(['str', {}, function () {}], {
'foo': 'string',
'[bar]': 'object',
'qux': 'function'
})
var args = assertArgs(['str', function () {}], {
'foo': 'string',
'[bar]': 'object',
'qux': 'function'
})
var args = assertArgs([], {
'foo': 'string',
'[bar]': 'object',
'qux': 'function'
})
var args = assertArgs(['str'], {
'foo': 'string',
'[bar]': 'object',
'qux': 'function'
})
var args = assertArgs([10, {}], {
'foo': 'string',
'[bar]': 'object',
'qux': 'function'
})
var args = assertArgs(['str', 10], {
'foo': 'string',
'[bar]': 'object',
'qux': 'function'
})
var args = assertArgs(['str', {}], {
'foo': 'string',
'[bar]': 'object',
'qux': 'function'
})
var args = assertArgs(['one', 'two', 'three', function () {}], {
'...foo': 'string',
'bar': 'function'
})
var args = assertArgs([function () {}], {
'...foo': 'string',
'bar': 'function'
})
var args = assertArgs([null, function () {}], {
'...foo': 'string',
'bar': 'function'
})
License
MIT