Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
State machine
var GO = 'GO',
OK = 'OK',
SIGN = 'SIGN',
LZERO = 'LZERO',
INT = 'INT',
FRAC = 'FRAC',
FDIG = 'FDIG',
EXP = 'EXP',
XSIGN = 'XSIGN',
EDIG = 'EDIG',
__ = -1;
var VALUE_MAP = {
'+' : 0, '-' : 1, '.' : 2,
'e' : 3, 'E' : 3, '0' : 4,
'1' : 5, '2' : 5, '3' : 5,
'4' : 5, '5' : 5, '6' : 5,
'7' : 5, '8' : 5, '9' : 5,
' ' : 6, '\t' : 6, '\r' : 6,
'\n' : 6
};
var ETC = 7;
/**
* Transition table for
* JSON numbers
* http://json.org/
*/
var PTBL = {
/* | + | - | . |e-E| 0 |1-9 |SPACE| ETC */
GO : [__ ,SIGN ,__ ,__ ,LZERO,INT ,__ ,__],
SIGN : [__ ,__ ,__ ,__ ,LZERO,INT ,__ ,__],
LZERO : [__ ,__ ,FRAC,EXP,__ ,__ ,OK ,__],
INT : [__ ,__ ,FRAC,EXP,INT ,INT ,OK ,__],
FRAC : [__ ,__ ,__ ,__ ,FDIG ,FDIG,__ ,__],
FDIG : [__ ,__ ,__ ,EXP,FDIG ,FDIG,OK ,__],
EXP : [XSIGN,XSIGN,__ ,__ ,EDIG ,EDIG,__ ,__],
XSIGN : [__ ,__ ,__ ,__ ,EDIG ,EDIG,__ ,__],
EDIG : [__ ,__ ,__ ,__ ,EDIG ,EDIG,OK ,__]
};
function parse(source) {
var state = GO,
len = source.length,
col;
source += ' ';
for (var i = 0; i <= len && state != __; i++) {
col = VALUE_MAP[source.charAt(i)];
col = col >= 0 ? col : ETC;
state = PTBL[state][col];
}
if (state == __) {
throw 'Invalid token - ' + source.slice(0, i);
}
return source.slice(0, i - 1);
}
//Example inputs
parse('3.142857142857143');
parse('137');
parse('-1');
parse('6.67e-11');
parse('-1.127e20');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.