Skip to content

Commit

Permalink
Add option to allow coercion of array items
Browse files Browse the repository at this point in the history
Fixes #6
  • Loading branch information
iilei committed Aug 22, 2018
1 parent 82f4ea5 commit 22efc7b
Show file tree
Hide file tree
Showing 2 changed files with 42 additions and 1 deletion.
18 changes: 17 additions & 1 deletion index.js
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,23 @@ function parse (args, opts) {
var negative = /^-[0-9]+(\.[0-9]+)?/
var negatedBoolean = new RegExp('^--' + configuration['negation-prefix'] + '(.+)')

;[].concat(opts.array).filter(Boolean).forEach(function (key) {
;[].concat(opts.array).filter(Boolean).forEach(function (opt) {
var key = opt.key || opt

// assign to flags[bools|strings|numbers]
const assignment = Object.keys(opt).map(function (key) {
return ({
boolean: 'bools',
string: 'strings',
number: 'numbers'
})[key]
}).filter(Boolean).pop()

// assign key to be coerced
if (assignment) {
flags[assignment][key] = true
}

flags.arrays[key] = true
flags.keys.push(key)
})
Expand Down
25 changes: 25 additions & 0 deletions test/yargs-parser.js
Original file line number Diff line number Diff line change
Expand Up @@ -1529,6 +1529,31 @@ describe('yargs-parser', function () {
var result = parser(['-x', 'val1', '-x', 'val1'])
result.should.have.property('x').that.is.an('array').and.to.deep.equal(['val1', 'val1'])
})

// see https://github.com/yargs/yargs-parser/issues/6
it('should respect the type `boolean` option for arrays', function () {
var result = parser(['-x=true', 'false'], {
array: [{key: 'x', boolean: true}]
})
result.should.have.property('x').that.is.an('array').and.to.deep.equal([true, false])
})

it('should respect the type `number` option for arrays', function () {
var result = parser(['-x=5', '2'], {
array: [{key: 'x', number: true}]
})
result.should.have.property('x').that.is.an('array').and.to.deep.equal([5, 2])
})

it('should respect the type `string` option for arrays', function () {
var result = parser(['-x=5', '2'], {
configuration: {
'parse-numbers': true
},
array: [{key: 'x', string: true}]
})
result.should.have.property('x').that.is.an('array').and.to.deep.equal(['5', '2'])
})
})

describe('nargs', function () {
Expand Down

0 comments on commit 22efc7b

Please sign in to comment.