named-positional-args
Version:
API support for args as both named and positional.
97 lines (63 loc) • 2.73 kB
Markdown
[](https://travis-ci.org/crazy4groovy/named-positional-args)
API support for arguments as both named and positional.
Depends on [__named-parameters__](https://www.npmjs.com/package/named-parameters) lib for implementing the very helpful `default`, `coerce`, and `require` features to manage API `arguments` data types and values.
`npm install --save named-positional-args`
```js
makeIntoGold({c:3, a:1}); //1. named
makeIntoGold(1, undefined, 3); //2. positional
```
```js
var namedPositionalArgs = require('named-positional-args');
function makeIntoGold(a, b, c) {
arguments = namedPositionalArgs.apply(makeIntoGold, arguments).args();
a = arguments[0]; b = arguments[1]; c = arguments[2];
//rest of code...
}
```
```js
function makeIntoGold(a, b, c) {
[] =
namedPositionalArgs.apply(makeIntoGold, arguments).args();
//rest of code...
}
```
```js
function makeIntoGold(a, b, c) {
[] =
namedPositionalArgs
.apply(makeIntoGold, arguments)
.default('a', 999)
.coerce('b', 'boolean')
.require('c', 'positive integer')
.args();
//rest of code...
}
```
__Note:__ This is obviously silly to use for functions which only take a single `{}` object param anyways! ;)
__Warning:__ If you compress/mangle your code, this way might break it!! (since the function arg names might no longer align internally as expected). To avoid this limitation, you can instead use a `csvArgs` string:
```js
function makeIntoGold(a, b, c) { // these can get mangled now!
[] =
namedPositionalArgs
.apply('a, b, c', arguments) // these are the cannonical arg names
.args();
//rest of code...
}
```
- `.apply(funcName:Function, arguments)` : Starts the argument parsing chain.
-or-
- `.apply(csvArgs:String, arguments)` : Starts the argument parsing chain.
`.default()` : see [default](https://www.npmjs.com/package/named-parameters#specifying-default-values)
`.coerce()` : see [coerce](https://www.npmjs.com/package/named-parameters#coercing-types)
`.require()` : see [require](https://www.npmjs.com/package/named-parameters#validating-parameters) (alias: `.demand()`)
`.args()` : Returns an `Array` akin to `arguments`.
`.opts()` : Returns an `Object` with `arguments` as `name: value` pairs.
`npm test`