Make sure a function accepts expected parameters with correct amount and types
const checker = new ArgumentsChecker();
Get arguments
object or rest parameters
function foo(){
checker.get(arguments);
}
// or
let bar = (...args)=>{
checker.get(args);
};
Specify minimun amount of arguments
let bar = (...args)=>{
checker.get(args).amount(4); // At least 4 arguments
};
- Specify types of arguments.
- Argument of
types
must be a type string ornull
.- If a string, it must be a value returned by the method below, case
insensitive:
Like
Object.prototype.toString.call(checked).slice(8, -1)
'string'
,'Array'
or'OBJECT'
are all valid. - A
null
means it can accept any type of argument.
- If a string, it must be a value returned by the method below, case
insensitive:
- Number type does not include
NaN
let bar = (...args)=>{
// The first argument must be an array
// The second argument must be a string
// The third argument can be any type
// The fouth argument must be a number
checker.get(args).types(['array', 'String', null, 'NUMBER']);
// ...
};
bar([1], '1', {}, 1, false); // No error
bar([1], 1, '1') // TypeError
bar([1], '1', {}) // TypeError. The fouth argument is undefine.
bar([1], '1', {}, NaN); // TypeError
You can customize the types of parameters you expect, in the form below:
// Define a custom types object, whose method names are custom types.
// A method should return true if the given argument is expected.
const oCustomChecker = {
strArr(arg){ // argument must be an array whose items are all string.
if(!Array.isArray(arg) || arg.length===0){
return false;
}
return arg.every(item=>typeof item === 'string');
},
numArr(arg){ // argument must be an array whose items are all number.
if(!Array.isArray(arg) || arg.length===0){
return false;
}
return arg.every(item=>typeof item === 'number'
&& !Number.isNaN(item));
}
};
const checker = new ArgumentsChecker(oCustomChecker); // Pass into constructor
let bar = (...args)=>{
checker.get(args).types('string', 'strArr', 'numArr');
};
bar('1', ['1', '2'], [1, 2]); // No error
bar('1', [1, 2], ['1', '2']); // TypeError
bar('1', [], [1, 2]); // TypeError
You can alse use a type checker in another custom type checker function, like this:
const oCustomChecker = {
arrayHas3Items(arg){
return Array.isArray(arg) && arg.length===3;
},
arrayHas3NumberItems(arg){ // Nested type checker
try{
// Use 2 nested type checkers, these 2 checkers should not throw
// their own errors.
this.get([arg]).types(['arrayHas3Items']);
arg.forEach(item=>{
this.get([item]).types(['number']);
});
}
catch(err){
return false;
}
return true;
},
};
Like this:
checker.get(args).amount(5).types(['number', null, 'array', 'numArr']);