Skip to content

Commit

Permalink
feat: don't coerce number from string with leading '0' or '+' (#158)
Browse files Browse the repository at this point in the history
BREAKING CHANGE: options with leading '+' or '0' now parse as strings
  • Loading branch information
bcoe committed Feb 2, 2019
1 parent ea6ce05 commit 18d0fd5
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 1 deletion.
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

0 comments on commit 18d0fd5

Please sign in to comment.