Interpreter pattern provides a way to evaluate language grammar or expression.
This pattern involves implementing an expression interface which tells to interpret a particular context.
This pattern is used in SQL parsing, symbol processing engine etc.
Interpreter contains the logic, which will convert the context to readable.
classTerminalExpression { private data;constructor(String data){this.data = data; }interpret(context) { if(context.contains(data)){returntrue; }returnfalse; }}classOrExpression { private expr1 =null;private expr2 =null;constructor(expr1, expr2) { this.expr1 = expr1;this.expr2 = expr2; }interpret(context) { returnexpr1.interpret(context) ||expr2.interpret(context); }}classAndExpression { private expr1 =null;private expr2 =null;constructor(expr1, expr2) { this.expr1 = expr1;this.expr2 = expr2; }interpret(String context) { returnexpr1.interpret(context) &&expr2.interpret(context); }}classInterpreterPatternDemo {//Rule: Robert and John are malestaticgetMaleExpression(){constrobert=newTerminalExpression("Robert");constjohn=newTerminalExpression("John");returnnewOrExpression(robert, john); }//Rule: Julie is a married womenstaticgetMarriedWomanExpression(){constjulie=newTerminalExpression("Julie"); married =newTerminalExpression("Married");constreturn new AndExpression(julie,married); }staticrun(args) {constisMale=getMaleExpression();constisMarriedWoman=getMarriedWomanExpression();console.log("John is male? "+isMale.interpret("John"));console.log("Julie is a married women? "+isMarriedWoman.interpret("Married Julie")); }}InterpreterPatternDemo.run();// John is male? true// Julie is a married women? true