badargument
v0.0.2
Published
Minimalistic pure JavaScript function contracts.
Downloads
2
Maintainers
Readme
Bad Argument JS
Terse, pure JavaScript function argument type checker. Implements contract pre-conditions for functions. Built for speed.
var argsMustBe = require('badargument');
function importantFunction(veryImportant, notImportant, thisMustBeAFunction) {
argsMustBe('defined ignored function');
whooohooo.some(code);
}
importantFunction('anyNonNullGoes', null, 'thisInsteadShouldBeAFunction');
Throws:
BadArgumentError: arg 2 of myImportantFunction is not a function.
Call arguments will also be stored in the Error's .arguments
attribute.
Bad Argument uses Function.caller and will degrade gracefully if it is not available.
Default error conditions
function
orF
:typeof arg !== "function"
object
orO
:!(arg instanceof Object)
number
orN
:typeof arg !== "number"
string
orS
:typeof arg === "string" || arg instanceof String
array
orA
:!Array.isArray(arg)
truthy
ort
:!arg
defined
or*
:arg == null
ignored
or_
:false
As a guideline, single-char versions of conditions that test for type are uppercase letters.
Custom error conditions
var badargument = require('badargument');
function Banana(){}
var myArgsMustBe = badargument.factory(
badargument.defaultTests(),
{
// This is more powerful
B: {message: 'is not a banana', condition: function(arg) {return !(arg instanceof Banana)}},
// This is faster because it gets inlined
red: {message: 'is not red', condition: '!arg || arg.color !== "red"'}
}
);
function picnic(howMany, appleType, where, callback) {
myArgsMustBe('B red string function');
}
var apple = {color: 'blue'};
picnic(new Banana, apple, 'on the moon');
Will throw BadArgumentError: arg 1 of picnic is not red.