Skip to content

Commit 31c204b

Browse files
juergbabcoe
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

+4-2
Original file line numberDiff line numberDiff line change
@@ -470,7 +470,9 @@ function parse (args, opts) {
470470
if (typeof val === 'string') val = val === 'true'
471471
}
472472

473-
var value = maybeCoerceNumber(key, val)
473+
var value = Array.isArray(val)
474+
? val.map(function (v) { return maybeCoerceNumber(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) || typeof value === 'boolean')) {
@@ -486,7 +488,7 @@ function parse (args, opts) {
486488
}
487489

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

test/yargs-parser.js

+15-2
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+
var parsed = 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
var parsed = 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
var parsed = parser('-x 1 2 3 -x 2 3 4', {

0 commit comments

Comments
 (0)