A Sexy DSL for JavaScript Arguments
Sep 12
I was working on one of my Node.js libraries and noticed I was doing something silly:
Karait (https://github.com/bcoe/karait)
There’s a lot of ritual around dealing with optional arguments and default parameters!
I did a little literature review, and found this problem was pretty widespread.
Other Examples
Node MongoDB Native (https://github.com/christkv/node-mongodb-native)
Express (https://github.com/visionmedia/express)
JSDom (https://github.com/tmpvar/jsdom)
The Solution? Sexy Arguments
sexy-args is a simple library and DSL for:
- Handling optional arguments.
- Enforcing types.
- Handling default values.
sexy-args enforces sane defaults:
- Arrays default to [].
- Objects default to {}.
- functions default to function() {}.
- Extend is used by default when assigning default values for an object.
- The common options (optional), callback, format is used by default:
So,
Becomes:
Examples After Applying Sexy-Args
Here’s what those prior examples would look like if they were using sexy-args:
Karait
Express
JSDom
I think this is much cleaner, which is the goal of sexy-args. Why repeat ourselves all the time when defining functions?
Rituals, like those surrounding handling optional arguments, help JavaScript get a bit of a reputation for being ugly. I feel it’s maleable enough language that steps can be taken to improve on things.
I’ve made the library available here:
https://github.com/bcoe/node-sexy-args
And here’s the Karait library, which I’ve updated to use Sexy-Args:
https://github.com/bcoe/karait
— Benjamin Coe (@benjamincoe)
