Skip to content

Commit

Permalink
feat(parser): more correct number parsing
Browse files Browse the repository at this point in the history
This prevents strings with mixed numbers and strings to be parsed as numbers if
the string begins with a number. `123abc` will now evaluate to the string
instead of `123` with the previous parser.
  • Loading branch information
Hans Kristian Flaatten committed May 6, 2016
1 parent 11025e1 commit be64e07
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 1 deletion.
3 changes: 2 additions & 1 deletion index.js
Original file line number Diff line number Diff line change
Expand Up @@ -189,7 +189,8 @@ module.exports.prototype.parseStringVal = function(string) {
return true;
} else if (this.string.toBoolean && string.toLowerCase() === 'false') {
return false;
} else if (this.string.toNumber && !isNaN(parseFloat(string, 10))) {
} else if (this.string.toNumber && !isNaN(parseInt(string, 10)) &&
(+string - +string + 1) >= 0) {
return parseFloat(string, 10);
} else {
return string;
Expand Down
32 changes: 32 additions & 0 deletions test.js
Original file line number Diff line number Diff line change
Expand Up @@ -132,6 +132,14 @@ describe('parseStringVal()', function() {
assert.equal(qs.parseStringVal('000100'), 100);
});

it('returns number for positive parseable integer', function() {
assert.equal(qs.parseStringVal('+100'), 100);
});

it('returns number for negative parseable integer', function() {
assert.equal(qs.parseStringVal('-100'), -100);
});

it('returns number for parseable float', function() {
assert.equal(qs.parseStringVal('10.123'), 10.123);
});
Expand All @@ -140,9 +148,33 @@ describe('parseStringVal()', function() {
assert.equal(qs.parseStringVal('00010.123'), 10.123);
});

it('returns number for positive parseable float', function() {
assert.equal(qs.parseStringVal('+10.123'), 10.123);
});

it('returns number for negative parseable float', function() {
assert.equal(qs.parseStringVal('-10.123'), -10.123);
});

it('returns string for empty string', function() {
assert.equal(qs.parseStringVal(''), '');
});

it('returns string for space string', function() {
assert.equal(qs.parseStringVal(' '), ' ');
});

it('returns string for "number string number"', function() {
assert.equal(qs.parseStringVal('123abc123'), '123abc123');
});

it('returns string for "string number"', function() {
assert.equal(qs.parseStringVal('abc123'), 'abc123');
});

it('returns string for "number string"', function() {
assert.equal(qs.parseStringVal('123abc'), '123abc');
});
});

describe('parseString()', function() {
Expand Down

0 comments on commit be64e07

Please sign in to comment.