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

feat: don't coerce number from string with leading '0' or '+' #158

Merged
merged 1 commit into from Feb 2, 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.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
7 changes: 6 additions & 1 deletion index.js
Expand Up @@ -786,9 +786,14 @@ function parse (args, opts) {
}

function isNumber (x) {
if (x === null || x === undefined) return false
// if loaded from config, may already be a number.
if (typeof x === 'number') return true
// hexadecimal.
if (/^0x[0-9a-f]+$/i.test(x)) return true
return /^[-+]?(?:\d+(?:\.\d*)?|\.\d+)(e[-+]?\d+)?$/.test(x)
// don't treat 0123 as a number; as it drops the leading '0'.
if (x.length > 1 && x[0] === '0') return false
return /^[-]?(?:\d+(?:\.\d*)?|\.\d+)(e[-+]?\d+)?$/.test(x)
}

function isUndefined (num) {
Expand Down
18 changes: 18 additions & 0 deletions test/yargs-parser.js
Expand Up @@ -2770,6 +2770,24 @@ describe('yargs-parser', function () {
argv.foo.should.equal(9.39404959509494e+22)
})

// see: https://github.com/yargs/yargs/issues/1099
it('does not magically convert options with leading + to number', () => {
const argv = parser(['--foo', '+5550100', '--bar', '+5550100'], {
number: 'bar'
})
argv.foo.should.equal('+5550100')
argv.bar.should.equal(5550100)
})

// see: https://github.com/yargs/yargs/issues/1099
it('does not magically convert options with leading 0 to number', () => {
const argv = parser(['--foo', '000000', '--bar', '000000'], {
number: 'bar'
})
argv.foo.should.equal('000000')
argv.bar.should.equal(0)
})

// see: https://github.com/yargs/yargs-parser/issues/101
describe('dot-notation array arguments combined with string arguments', function () {
it('parses correctly when dot-notation argument is first', function () {
Expand Down