Skip to content

Instantly share code, notes, and snippets.

@blrobin2
Created September 25, 2017 18:39
Show Gist options
  • Select an option

  • Save blrobin2/4c62dee3b73b4e00cccab33cbad806d9 to your computer and use it in GitHub Desktop.

Select an option

Save blrobin2/4c62dee3b73b4e00cccab33cbad806d9 to your computer and use it in GitHub Desktop.
A dumb way of checking if required parameter is passed
function missingRequired() {
const thisFunc = arguments.callee;
const caller = thisFunc.caller;
const passedArgs = caller.arguments;
const args = caller.toString()
.replace(/((\/\/.*$)|(\/\*[\s\S]*?\*\/)|(\s))/mg,'') // remove all spacing
.split(/function\s*\w+\(?/)[1] // remove 'function name ('
.split(/\)\s*\{/)[0] // remove everything after ){
.split(/,/); // break apart into comma separated list of arguments
args.forEach((arg, index) => {
const [param, paramDefault] = arg.split('=');
// If there is a default parameter, and it's name is the same as this
// function and for this index there was not a passed in value, then we
// enforce required
if (paramDefault
&& paramDefault.match(`${thisFunc.name}`)
&& !passedArgs[index]
) {
throw new Error(`Missing required argument: '${param}'`);
}
});
}
function args(required = missingRequired(), alsoRequired = missingRequired(), thing = 2) {
console.log(alsoRequired)
}
//args() // Error: missing required argument: required
args('test') // Error: missing required argument: alsoRequired
//args('test', 'also test') // 'also test'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment