What’s In A Name?
- Named arguments
- Default argument values
- Argument type enforcement
Default argument values is actually a feature proposed in ES6 but as we aren’t quite there yet with ES6 I decided to patch the functionality myself in the best way I could. I’ve made a little library and it’s called Names.js. Please fork it and help me improve it!
Function object adding a couple of instance methods to the prototype and a static method to the main object. The static method is this:
1 2 3 4 5 6 7 8 9
It’s a bit more verbose than simply
1 2 3
however it offers the following benefits:
- You don’t need to provide an argument each time if you’re happy with the default value:
- You know what each argument means (this advantage is a lot clearer when the arguments are named well and the values you are assigning them are all booleans and integers).
- You can provide the arguments in whichever order you like:
1 2 3 4
- The function will throw an error if you pass it an incorrectly typed value:
apply method, taking the scope as the first argument and the arguments to apply as the second.
In many languages, type checking is mandatory but at the end of the day it’s just a form of validation. In an effort to reduce the usual argument-checking clutter at the beginning of a function I thought it was worth extending the validation functionality to allow for custom validations.
You can either use a regex or a function:
1 2 3 4 5 6 7 8 9 10 11
required option on
arg2’s validation object means that
arg2 is required. Ordinarily if the argument is omitted when calling
applyNamed then that validation will not be run. If the argument is omitted but the validation for that argument states that it is
required then it will fail instantly.
Names.js eats its own dogfood wherever possible and practical. There are only 3 public functions:
applyNamedwouldn’t make sense to be able to
createNamedwould be an even more verbose way of creating a function if you used it with
applyNamed. However it does use an
applyNamed-style syntax and goes on to use
applyNamedinternally to create the new function.
addValidationis not only created with
createNamedbut also its own validation rules are added using
addValidation. Talk about meta!
…that’s pretty much it really. I also wrote a release script for the library that I’m pretty pleased with but maybe that’s for another blog post :)