Skip to content

Commit 31c204b

Browse files
juergbaBenjamin E. Coe
authored andcommitted
feat!: maybeCoerceNumber() now takes into account arrays (#187)
BREAKING CHANGE: unless "parse-numbers" is set to "false", arrays of numeric strings are now parsed as numbers, rather than strings.
1 parent 17ca3bd commit 31c204b

File tree

2 files changed

+19
-4
lines changed

2 files changed

+19
-4
lines changed

‎index.js‎

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -470,7 +470,9 @@ function parse (args, opts){
470470
if(typeofval==='string')val=val==='true'
471471
}
472472

473-
varvalue=maybeCoerceNumber(key,val)
473+
varvalue=Array.isArray(val)
474+
? val.map(function(v){returnmaybeCoerceNumber(key,v)})
475+
: maybeCoerceNumber(key,val)
474476

475477
// increment a count given as arg (either no value or value parsed as boolean)
476478
if(checkAllAliases(key,flags.counts)&&(isUndefined(value)||typeofvalue==='boolean')){
@@ -486,7 +488,7 @@ function parse (args, opts){
486488
}
487489

488490
functionmaybeCoerceNumber(key,value){
489-
if(!checkAllAliases(key,flags.strings)){
491+
if(!checkAllAliases(key,flags.strings)&&!checkAllAliases(key,flags.bools)&&!Array.isArray(value)){
490492
constshouldCoerceNumber=isNumber(value)&&configuration['parse-numbers']&&(
491493
Number.isSafeInteger(Math.floor(value))
492494
)

‎test/yargs-parser.js‎

Lines changed: 15 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2160,6 +2160,19 @@ describe('yargs-parser', function (){
21602160
expect(parsed['bar']).to.equal(6)
21612161
expect(parsed['baz']).to.equal(7)
21622162
})
2163+
2164+
it('should coerce elements of number typed arrays to numbers',function(){
2165+
varparsed=parser(['--foo','4','--foo','5','2'],{
2166+
array: ['foo'],
2167+
configObjects: [{foo: ['1','2','3']}],
2168+
configuration: {
2169+
'combine-arrays': true,
2170+
'flatten-duplicate-arrays': false
2171+
}
2172+
})
2173+
2174+
expect(parsed['foo']).to.deep.equal([[4],[5,2],[1,2,3]])
2175+
})
21632176
})
21642177

21652178
describe('boolean negation',function(){
@@ -2445,15 +2458,15 @@ describe('yargs-parser', function (){
24452458
})
24462459
describe('duplicate=true, flatten=false,',function(){
24472460
describe('type=array',function(){
2448-
it('[-x 1 -x 2 -x 3] => [1, 2, 3]',function(){
2461+
it('[-x 1 -x 2 -x 3] => [[1], [2], [3]]',function(){
24492462
varparsed=parser('-x 1 -x 2 -x 3',{
24502463
array: ['x'],
24512464
configuration: {
24522465
'duplicate-arguments-array': true,
24532466
'flatten-duplicate-arrays': false
24542467
}
24552468
})
2456-
parsed['x'].should.deep.equal([1,2,3])
2469+
parsed['x'].should.deep.equal([[1],[2],[3]])
24572470
})
24582471
it('[-x 1 2 3 -x 2 3 4] => [[1, 2, 3], [ 2, 3, 4]]',function(){
24592472
varparsed=parser('-x 1 2 3 -x 2 3 4',{

0 commit comments

Comments
(0)