Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix: number[] - maybeCoerceNumber(): processing of number typed arrays #187

Merged
merged 3 commits into from
Jul 13, 2019
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 4 additions & 2 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -470,7 +470,9 @@ function parse (args, opts) {
if (typeof val === 'string') val = val === 'true'
}

var value = maybeCoerceNumber(key, val)
var value = Array.isArray(val)
? val.map(function (v) { return maybeCoerceNumber(key, v) })
: maybeCoerceNumber(key, val)

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

function maybeCoerceNumber (key, value) {
if (!checkAllAliases(key, flags.strings)) {
if (!checkAllAliases(key, flags.strings) && !checkAllAliases(key, flags.bools) && !Array.isArray(value)) {
const shouldCoerceNumber = isNumber(value) && configuration['parse-numbers'] && (
Number.isSafeInteger(Math.floor(value))
)
Expand Down
17 changes: 15 additions & 2 deletions test/yargs-parser.js
Original file line number Diff line number Diff line change
Expand Up @@ -2160,6 +2160,19 @@ describe('yargs-parser', function () {
expect(parsed['bar']).to.equal(6)
expect(parsed['baz']).to.equal(7)
})

it('should coerce elements of number typed arrays to numbers', function () {
var parsed = parser(['--foo', '4', '--foo', '5', '2'], {
array: ['foo'],
configObjects: [{ foo: ['1', '2', '3'] }],
configuration: {
'combine-arrays': true,
'flatten-duplicate-arrays': false
}
})

expect(parsed['foo']).to.deep.equal([[4], [5, 2], [1, 2, 3]])
})
})

describe('boolean negation', function () {
Expand Down Expand Up @@ -2445,15 +2458,15 @@ describe('yargs-parser', function () {
})
describe('duplicate=true, flatten=false,', function () {
describe('type=array', function () {
it('[-x 1 -x 2 -x 3] => [1, 2, 3]', function () {
it('[-x 1 -x 2 -x 3] => [[1], [2], [3]]', function () {
var parsed = parser('-x 1 -x 2 -x 3', {
array: ['x'],
configuration: {
'duplicate-arguments-array': true,
'flatten-duplicate-arrays': false
}
})
parsed['x'].should.deep.equal([1, 2, 3])
parsed['x'].should.deep.equal([[1], [2], [3]])
})
it('[-x 1 2 3 -x 2 3 4] => [[1, 2, 3], [ 2, 3, 4]]', function () {
var parsed = parser('-x 1 2 3 -x 2 3 4', {
Expand Down