From 52b67058e058f61c3730edaa44fe29c3d7bb1da9 Mon Sep 17 00:00:00 2001 From: ajlopez Date: Sun, 23 Aug 2015 13:05:11 -0300 Subject: [PATCH] Refactor to commands --- lib/commands.js | 32 ++++++++++++++++++++++++++++++++ lib/parsers.js | 33 ++++----------------------------- 2 files changed, 36 insertions(+), 29 deletions(-) create mode 100644 lib/commands.js diff --git a/lib/commands.js b/lib/commands.js new file mode 100644 index 0000000..33b9c1d --- /dev/null +++ b/lib/commands.js @@ -0,0 +1,32 @@ + +function ExpressionCommand(expr) { + this.execute = function (ctx) { + expr.evaluate(ctx); + }; +} + +function CompositeCommand(cmds) { + this.execute = function (ctx) { + cmds.forEach(function (cmd) { + cmd.execute(ctx); + }); + }; +} + +function ProgramCommand(cmds) { + this.execute = function (ctx) { + ctx.set('$program', new CompositeCommand(cmds)); + }; +} + +function ProcedureCommand(name, argnames, cmds) { + this.execute = function (ctx) { + ctx.set(name, new CompositeCommand(cmds)); + }; +} + +module.exports = { + expression: function (expr) { return new ExpressionCommand(expr); }, + program: function (cmds) { return new ProgramCommand(cmds); }, + procedure: function (name, argnames, cmds) { return new ProcedureCommand(name, argnames, cmds); } +}; \ No newline at end of file diff --git a/lib/parsers.js b/lib/parsers.js index 8d343ee..89c7ed0 100644 --- a/lib/parsers.js +++ b/lib/parsers.js @@ -2,32 +2,7 @@ var expressions = require('./expressions'); var lexers = require('./lexers'); var TokenType = lexers.TokenType; - -function ExpressionCommand(expr) { - this.execute = function (ctx) { - expr.evaluate(ctx); - }; -} - -function CompositeCommand(cmds) { - this.execute = function (ctx) { - cmds.forEach(function (cmd) { - cmd.execute(ctx); - }); - }; -} - -function ProgramCommand(cmds) { - this.execute = function (ctx) { - ctx.set('$program', new CompositeCommand(cmds)); - }; -} - -function ProcedureCommand(name, argnames, cmds) { - this.execute = function (ctx) { - ctx.set(name, new CompositeCommand(cmds)); - }; -} +var commands = require('./commands'); function Parser(text) { var lexer = lexers.lexer(text); @@ -54,7 +29,7 @@ function Parser(text) { tryGetToken(';', TokenType.Delimiter); - return new ExpressionCommand(expr); + return commands.expression(expr); }; this.parseExpression = function () { @@ -130,7 +105,7 @@ function Parser(text) { getToken('}', TokenType.Delimiter); - return new ProgramCommand(cmds); + return commands.program(cmds); } function parseProcedure() { @@ -155,7 +130,7 @@ function Parser(text) { getToken('}', TokenType.Delimiter); - return new ProcedureCommand(name, argnames, cmds); + return commands.procedure(name, argnames, cmds); } }