Skip to content

Instantly share code, notes, and snippets.

@KOBA789
Created August 5, 2014 15:19
Show Gist options
  • Save KOBA789/bd5cc8e484d6bf654db9 to your computer and use it in GitHub Desktop.
Save KOBA789/bd5cc8e484d6bf654db9 to your computer and use it in GitHub Desktop.
function EOF () {}
function State (list) {
this._pos = 0;
this._list = Array.prototype.slice.call(list).concat([EOF]);
}
State.prototype.getList = function () {
return this._list.slice(this._pos);
};
State.prototype.consume = function (i) {
if (i === -1) {
throw new Error('parse error');
}
this._pos += i;
};
function eof(s) {
if (s.getList()[0] === EOF) {
s.consume(1);
return null;
} else {
s.consume(-1);
return null;
}
}
function chr(c) {
return function (s) {
if (s.getList()[0] === c) {
s.consume(1);
return c;
} else {
s.consume(-1);
return null;
}
};
}
function join(ps) {
return function (s) {
var rs = [];
for (var i = 0; i < ps.length; ++i) {
var p = ps[i],
r = p(s);
if (r !== null) {
rs.push(r);
}
}
return rs;
};
}
(function test () {
var a = chr('a'),
b = chr('b');
var p = join([a, b, a, eof]);
var ps = new State('aba');
var r = p(ps);
console.log(r);
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment