Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
Browse files

add some tests for numbers with vows. fix issue #9

  • Loading branch information...
commit 976607ef3b707e0374a01277f031f3325adce7b9 1 parent 109ac30
@Floby authored
View
10 lib/JsonTokenizer.js
@@ -14,9 +14,15 @@ module.exports = function JsonTokenizer() {
t.addRule(/^"([^"]|\\")*$/, 'maybe-string');
t.addRule(/^null$/, 'null');
t.addRule(/^(true|false)$/, 'boolean');
- t.addRule(/^\d+(\.\d+)?$/, 'number');
- t.addRule(/^\d+\.$/, 'maybe-number');
+
+ t.addRule(/^-?\d+(\.\d+)?([eE]-?\d+)?$/, 'number');
+ t.addRule(/^-?\d+\.$/, 'maybe-decimal-number');
+ t.addRule(/^-$/, 'maybe-negative-number');
+ t.addRule(/^-?\d+(\.\d+)?([eE])?$/, 'maybe-exponential-number');
+ t.addRule(/^-?\d+(\.\d+)?([eE]-)?$/, 'maybe-exponential-number-negative');
+
t.addRule(/^\w+$/, 'symbol');
+
t.addRule(Tokenizer.whitespace);
t.ignore('whitespace');
// if we had comments tokens, we would ignore them as well
View
1  lib/ParseStream.js
@@ -76,6 +76,7 @@ ParseStream.prototype.native = function Native(set) {
break;
case 'number':
var int = (token.indexOf('.') === -1);
+ int &= (token.indexOf('e') === -1);
set(int ? parseInt(token) : parseFloat(token));
break;
case 'string':
View
50 vows/single-value.vow.js
@@ -0,0 +1,50 @@
+#!/usr/bin/env node
+
+var vows = require('vows');
+var assert = require('assert');
+var ParseStream = require('../lib/ParseStream');
+
+
+var suite = vows.describe('Single Values');
+
+function assertSameParsed(value) {
+ function parseValue (value) {
+ return function() {
+ var parser = new ParseStream();
+ var cb = this.callback;
+ parser.on('end', function(object) {
+ cb(null, object);
+ });
+ parser.on('error', function(err) {
+ cb(err);
+ });
+ parser.end(value);
+ }
+ }
+ return {
+ topic: parseValue(value),
+ 'it should be parsed correctly': function(parsed) {
+ parsed = JSON.stringify(parsed);
+ val = JSON.stringify(JSON.parse(value));
+ assert.equal(parsed, val,
+ 'The parsed value is not equal to the given value '+parsed+' != '+val);
+ }
+ }
+}
+
+suite.addBatch({
+ "When parsing a number": {
+ "positive integer": assertSameParsed('4'),
+ "negative integer": assertSameParsed('-31'),
+ "positive fraction": assertSameParsed('10.89'),
+ "negative fraction": assertSameParsed('-40.54'),
+ "exponential notation": assertSameParsed('4e3'),
+ "exponential notation with decimal part": assertSameParsed('80.5e3'),
+ "exponential notation negative": assertSameParsed('-4e3'),
+ "exponential notation negative with decimal part": assertSameParsed('-4.6e3'),
+ "exponential notation, negative exponent": assertSameParsed('4e-3'),
+ "exponential notation, negative exponent, negative value": assertSameParsed('-4e-3'),
+ "exponential notation, negative exponent, negative value, decimal part": assertSameParsed('-4.8e-3'),
+ }
+}).export(module);
+
Please sign in to comment.
Something went wrong with that request. Please try again.