SlideShare a Scribd company logo
eleks.com
Interpreter Pattern
Design Patterns Program
by Dmytro Verbovyi
Introduction
Given a language, define a
representation for its grammar along
with an interpreter that uses the
representation to interpret sentences
in the language. (GOF) ***
***The basic idea is to have a class for each
symbol(terminal or nonterminal) in a specialized computer
language.
● Frequent changing task
● Queries, terms and
expression
● Regular expressions
● Sentences in the language
represented as abstract syntax
trees (AST)
● Easy to extend and modify
grammar. (Classes
implementation that describes
abstract syntax nodes easily
coded)
● You can easily change the
method of calculating
expressions
Problem solving
Real world example - Barcode
How Barcode works - BNF notation
● <UPC>::=<Manufacture ID><Item Number><Check Digit>
● <Manufacture Id>::=<Digit><Digit><Digit><Digit><Digit><Digit>
● <Item Number>::=<Digit><Digit><Digit><Digit><Digit>
● <Check Digit>::=<Digit>
● <Digit>::= 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9
Scheme
Implemented example - BNF
● <TRAILER>::=<Goods><sPackage><Goods><bPackage><Goods><Goods>
● <sPackage>::=<Goods><Goods>
● <bPackage>::=<Goods><Goods><Goods><Goods>
● <Goods>::= <Table> | <Bed> | <TV> | <LapTop>
Language sentence
<script type="text/template" id="contextTpl">
<h1>{Table}{SPackage}{Bed}{BPackage}{TV}{LapTop}</h1>
</script>
Abstract Expression
//Abstract Expression
class Goods {
constructor(){
this.name = this.__proto__.constructor.name;
}
interpret(context) {
return this.name + ': ' + context.getPrice(this.name) + '<br>';
}
}
Terminal Expressions
//Terminal Expressions
class TV extends Goods {}
class LapTop extends Goods {}
class Table extends Goods {}
class Bed extends Goods {}
Nonterminal Expressions
//Non-Terminal Expresions
class SPackage extends Goods {
constructor() {
super();
this.itemsList = [].slice.call(arguments);
}
add(item) {
this.itemsList.push(item);
}
interpret(context) {
let output = '';
this.itemsList.forEach((exp)=> {
output += exp.interpret(context);
});
return output;
}
}
class BPackage extends SPackage {}
Context
class PriceContext {
constructor(bed, table, tv, laptop, sPackage, bPackage) {
this.bed = bed;
this.table = table;
this.tv = tv;
this.laptop = laptop;
this.spackage = sPackage;
this.bpackage = bPackage;
this.prices = {};
}
setPrice(prices) {
for(let key in prices) {
if(!prices.hasOwnProperty(key)) continue;
this.prices[key] = prices[key];
}
}
getPrice(name) {
return this.prices[name];
}
interpret(expName){
return
this[expName].interpret(this);
}
}
View - slide 1
class View {
constructor(el, tplId) {
this.el = el;
this._vars = {};
this.setTemplate(tplId);
}
setTemplate(tplId) {
this.template = document.getElementById(tplId).innerHTML.replace(/s/g, '');
}
getVars() {
let regex = /{(.*?)}/g,
matches, expressions = [];
while (matches = regex.exec(this.template)) {
expressions.push(matches[1]);
}
return expressions;
}
View - slide 2
render(priceContext) {
let output = this.template,
vars = this.getVars();
vars.forEach((variable)=> {
let expName = variable.toLowerCase(),
re = new RegExp("{" + variable + "}", 'g');
output = output.replace(re, priceContext.interpret(expName));
});
this.el.innerHTML = output;
return this;
}
}
Usage
const Main = () => {
let el = document.body;
let view = new View(el, 'contextTpl');
let smallPackage = new SPackage();
smallPackage.add(new TV());
smallPackage.add(new LapTop());
let bigPackage = new BPackage();
bigPackage.add(new Table());
bigPackage.add(new Bed());
bigPackage.add(new Bed());
bigPackage.add(new TV());
let priceContext = new PriceContext(
new Bed(),
new Table(),
new TV(),
new LapTop(),
smallPackage,
bigPackage
);
priceContext.setPrice({
'Bed': 400,
'TV': 200,
'LapTop': 500,
'Table': 50
});
view.render(priceContext);
};
Sentence and Output
Table: 50
TV: 200
LapTop: 500
Bed: 400
Table: 50
Bed: 400
Bed: 400
TV: 200
TV: 200
LapTop: 500
<script type="text/template" id="contextTpl">
<h1>{Table}{SPackage}{Bed}{BPackage}{TV}{LapTop}</h1>
</script>
Advantages Disadvantages
● You have a simple
language to interpret
● You can easily change
the method of
calculating expressions
● You can represent
sentences in the
language as abstract
syntax trees (AST).
● Difficult to support the
grammar with a large
number of rules
● Each class on each
expression
Related Patterns
● Composite for same proccessing terminal and non-terminal expressions
● Flyweight for sharing terminal expressions
● Iterator for traversing the nodes of non-terminals
Inspired by Technology.
Driven by Value.
Have a questions?

More Related Content

What's hot (20)

PPT
Lecture 14 - Scope Rules
Md. Imran Hossain Showrov
 
PPT
Pointer in C
Sonya Akter Rupa
 
PPTX
Pointer basics
Mohammed Sikander
 
PPTX
Function C programming
Appili Vamsi Krishna
 
PPT
Recursion in c
Saket Pathak
 
PPT
Láș­p trĂŹnh C
Viet NguyenHoang
 
PDF
仕äș‹ă§äœżă†F#
bleis tift
 
PPT
Function in C Language
programmings guru
 
PDF
Function in C
Dr. Abhineet Anand
 
PPT
C++ programming
viancagerone
 
PPT
C intro
Kamran
 
PPT
Ch3 repetition
Hattori Sidek
 
PDF
Compiler Construction | Lecture 9 | Constraint Resolution
Eelco Visser
 
PDF
C Programming - Refresher - Part II
Emertxe Information Technologies Pvt Ltd
 
PPTX
07. Virtual Functions
Haresh Jaiswal
 
PPT
pointer, structure ,union and intro to file handling
Rai University
 
PPSX
Esoft Metro Campus - Programming with C++
Rasan Samarasinghe
 
PPTX
Python Functions 1
gsdhindsa
 
PDF
Functional Python Webinar from October 22nd, 2014
Reuven Lerner
 
PPT
pointer, structure ,union and intro to file handling
Rai University
 
Lecture 14 - Scope Rules
Md. Imran Hossain Showrov
 
Pointer in C
Sonya Akter Rupa
 
Pointer basics
Mohammed Sikander
 
Function C programming
Appili Vamsi Krishna
 
Recursion in c
Saket Pathak
 
Láș­p trĂŹnh C
Viet NguyenHoang
 
仕äș‹ă§äœżă†F#
bleis tift
 
Function in C Language
programmings guru
 
Function in C
Dr. Abhineet Anand
 
C++ programming
viancagerone
 
C intro
Kamran
 
Ch3 repetition
Hattori Sidek
 
Compiler Construction | Lecture 9 | Constraint Resolution
Eelco Visser
 
C Programming - Refresher - Part II
Emertxe Information Technologies Pvt Ltd
 
07. Virtual Functions
Haresh Jaiswal
 
pointer, structure ,union and intro to file handling
Rai University
 
Esoft Metro Campus - Programming with C++
Rasan Samarasinghe
 
Python Functions 1
gsdhindsa
 
Functional Python Webinar from October 22nd, 2014
Reuven Lerner
 
pointer, structure ,union and intro to file handling
Rai University
 

Similar to Interpreter Design Pattern in Javascript (20)

PDF
ReasonML: Strict, Powerful, and Forgiving
hari
 
PPTX
Trends in programming languages
Antya Dev
 
PDF
ES6 patterns in the wild
Joe Morgan
 
PDF
Software Language Design & Engineering
Eelco Visser
 
PPTX
Academy PRO: ES2015
Binary Studio
 
PDF
The Future of JavaScript (Ajax Exp '07)
jeresig
 
PDF
Introduction to ECMAScript 2015
Tomasz Dziuda
 
PDF
Architecture for scalable Angular applications
PaweƂ Ć»urowski
 
PPTX
Functional DDD
Alessandro Melchiori
 
PPTX
Building DSLs with Scala
Alon Muchnick
 
PDF
Software Language Design & Engineering: Mobl & Spoofax
Eelco Visser
 
PDF
Functional Web Development using Elm
đŸ’» Spencer Schneidenbach
 
PDF
ESCMAScript 6: Get Ready For The Future. Now
Krzysztof Szafranek
 
PDF
The Epsilon Pattern Language
Dimitris Kolovos
 
PDF
Javascript
Vlad Ifrim
 
PDF
Half way to clean architecture - Dmytro Voronkevych - Droidcon Berlin
Badoo
 
PPTX
ES6: Features + Rails
Santosh Wadghule
 
PPTX
unified modelling language(UML) diagrams
pratyashi satapathy
 
PDF
Epic.NET: Processes, patterns and architectures
Giacomo Tesio
 
PPT
A Unified View of Modeling and Programming
Ed Seidewitz
 
ReasonML: Strict, Powerful, and Forgiving
hari
 
Trends in programming languages
Antya Dev
 
ES6 patterns in the wild
Joe Morgan
 
Software Language Design & Engineering
Eelco Visser
 
Academy PRO: ES2015
Binary Studio
 
The Future of JavaScript (Ajax Exp '07)
jeresig
 
Introduction to ECMAScript 2015
Tomasz Dziuda
 
Architecture for scalable Angular applications
PaweƂ Ć»urowski
 
Functional DDD
Alessandro Melchiori
 
Building DSLs with Scala
Alon Muchnick
 
Software Language Design & Engineering: Mobl & Spoofax
Eelco Visser
 
Functional Web Development using Elm
đŸ’» Spencer Schneidenbach
 
ESCMAScript 6: Get Ready For The Future. Now
Krzysztof Szafranek
 
The Epsilon Pattern Language
Dimitris Kolovos
 
Javascript
Vlad Ifrim
 
Half way to clean architecture - Dmytro Voronkevych - Droidcon Berlin
Badoo
 
ES6: Features + Rails
Santosh Wadghule
 
unified modelling language(UML) diagrams
pratyashi satapathy
 
Epic.NET: Processes, patterns and architectures
Giacomo Tesio
 
A Unified View of Modeling and Programming
Ed Seidewitz
 
Ad

Recently uploaded (20)

PPTX
Change Common Properties in IBM SPSS Statistics Version 31.pptx
Version 1 Analytics
 
PPTX
Tally software_Introduction_Presentation
AditiBansal54083
 
PDF
HiHelloHR – Simplify HR Operations for Modern Workplaces
HiHelloHR
 
PPTX
Agentic Automation Journey Series Day 2 – Prompt Engineering for UiPath Agents
klpathrudu
 
PDF
Thread In Android-Mastering Concurrency for Responsive Apps.pdf
Nabin Dhakal
 
PPTX
Migrating Millions of Users with Debezium, Apache Kafka, and an Acyclic Synch...
MD Sayem Ahmed
 
PPTX
Transforming Mining & Engineering Operations with Odoo ERP | Streamline Proje...
SatishKumar2651
 
PPTX
Java Native Memory Leaks: The Hidden Villain Behind JVM Performance Issues
Tier1 app
 
PDF
Alarm in Android-Scheduling Timed Tasks Using AlarmManager in Android.pdf
Nabin Dhakal
 
PDF
Revenue streams of the Wazirx clone script.pdf
aaronjeffray
 
PDF
Beyond Binaries: Understanding Diversity and Allyship in a Global Workplace -...
Imma Valls Bernaus
 
PDF
Digger Solo: Semantic search and maps for your local files
seanpedersen96
 
PDF
Build It, Buy It, or Already Got It? Make Smarter Martech Decisions
bbedford2
 
PDF
GetOnCRM Speeds Up Agentforce 3 Deployment for Enterprise AI Wins.pdf
GetOnCRM Solutions
 
PDF
Mobile CMMS Solutions Empowering the Frontline Workforce
CryotosCMMSSoftware
 
PPTX
Human Resources Information System (HRIS)
Amity University, Patna
 
PDF
The 5 Reasons for IT Maintenance - Arna Softech
Arna Softech
 
PDF
SciPy 2025 - Packaging a Scientific Python Project
Henry Schreiner
 
PPTX
Writing Better Code - Helping Developers make Decisions.pptx
Lorraine Steyn
 
PPTX
Agentic Automation Journey Session 1/5: Context Grounding and Autopilot for E...
klpathrudu
 
Change Common Properties in IBM SPSS Statistics Version 31.pptx
Version 1 Analytics
 
Tally software_Introduction_Presentation
AditiBansal54083
 
HiHelloHR – Simplify HR Operations for Modern Workplaces
HiHelloHR
 
Agentic Automation Journey Series Day 2 – Prompt Engineering for UiPath Agents
klpathrudu
 
Thread In Android-Mastering Concurrency for Responsive Apps.pdf
Nabin Dhakal
 
Migrating Millions of Users with Debezium, Apache Kafka, and an Acyclic Synch...
MD Sayem Ahmed
 
Transforming Mining & Engineering Operations with Odoo ERP | Streamline Proje...
SatishKumar2651
 
Java Native Memory Leaks: The Hidden Villain Behind JVM Performance Issues
Tier1 app
 
Alarm in Android-Scheduling Timed Tasks Using AlarmManager in Android.pdf
Nabin Dhakal
 
Revenue streams of the Wazirx clone script.pdf
aaronjeffray
 
Beyond Binaries: Understanding Diversity and Allyship in a Global Workplace -...
Imma Valls Bernaus
 
Digger Solo: Semantic search and maps for your local files
seanpedersen96
 
Build It, Buy It, or Already Got It? Make Smarter Martech Decisions
bbedford2
 
GetOnCRM Speeds Up Agentforce 3 Deployment for Enterprise AI Wins.pdf
GetOnCRM Solutions
 
Mobile CMMS Solutions Empowering the Frontline Workforce
CryotosCMMSSoftware
 
Human Resources Information System (HRIS)
Amity University, Patna
 
The 5 Reasons for IT Maintenance - Arna Softech
Arna Softech
 
SciPy 2025 - Packaging a Scientific Python Project
Henry Schreiner
 
Writing Better Code - Helping Developers make Decisions.pptx
Lorraine Steyn
 
Agentic Automation Journey Session 1/5: Context Grounding and Autopilot for E...
klpathrudu
 
Ad

Interpreter Design Pattern in Javascript

  • 2. Introduction Given a language, define a representation for its grammar along with an interpreter that uses the representation to interpret sentences in the language. (GOF) *** ***The basic idea is to have a class for each symbol(terminal or nonterminal) in a specialized computer language.
  • 3. ● Frequent changing task ● Queries, terms and expression ● Regular expressions
  • 4. ● Sentences in the language represented as abstract syntax trees (AST) ● Easy to extend and modify grammar. (Classes implementation that describes abstract syntax nodes easily coded) ● You can easily change the method of calculating expressions Problem solving
  • 5. Real world example - Barcode
  • 6. How Barcode works - BNF notation ● <UPC>::=<Manufacture ID><Item Number><Check Digit> ● <Manufacture Id>::=<Digit><Digit><Digit><Digit><Digit><Digit> ● <Item Number>::=<Digit><Digit><Digit><Digit><Digit> ● <Check Digit>::=<Digit> ● <Digit>::= 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9
  • 8. Implemented example - BNF ● <TRAILER>::=<Goods><sPackage><Goods><bPackage><Goods><Goods> ● <sPackage>::=<Goods><Goods> ● <bPackage>::=<Goods><Goods><Goods><Goods> ● <Goods>::= <Table> | <Bed> | <TV> | <LapTop>
  • 9. Language sentence <script type="text/template" id="contextTpl"> <h1>{Table}{SPackage}{Bed}{BPackage}{TV}{LapTop}</h1> </script>
  • 10. Abstract Expression //Abstract Expression class Goods { constructor(){ this.name = this.__proto__.constructor.name; } interpret(context) { return this.name + ': ' + context.getPrice(this.name) + '<br>'; } }
  • 11. Terminal Expressions //Terminal Expressions class TV extends Goods {} class LapTop extends Goods {} class Table extends Goods {} class Bed extends Goods {}
  • 12. Nonterminal Expressions //Non-Terminal Expresions class SPackage extends Goods { constructor() { super(); this.itemsList = [].slice.call(arguments); } add(item) { this.itemsList.push(item); } interpret(context) { let output = ''; this.itemsList.forEach((exp)=> { output += exp.interpret(context); }); return output; } } class BPackage extends SPackage {}
  • 13. Context class PriceContext { constructor(bed, table, tv, laptop, sPackage, bPackage) { this.bed = bed; this.table = table; this.tv = tv; this.laptop = laptop; this.spackage = sPackage; this.bpackage = bPackage; this.prices = {}; } setPrice(prices) { for(let key in prices) { if(!prices.hasOwnProperty(key)) continue; this.prices[key] = prices[key]; } } getPrice(name) { return this.prices[name]; } interpret(expName){ return this[expName].interpret(this); } }
  • 14. View - slide 1 class View { constructor(el, tplId) { this.el = el; this._vars = {}; this.setTemplate(tplId); } setTemplate(tplId) { this.template = document.getElementById(tplId).innerHTML.replace(/s/g, ''); } getVars() { let regex = /{(.*?)}/g, matches, expressions = []; while (matches = regex.exec(this.template)) { expressions.push(matches[1]); } return expressions; }
  • 15. View - slide 2 render(priceContext) { let output = this.template, vars = this.getVars(); vars.forEach((variable)=> { let expName = variable.toLowerCase(), re = new RegExp("{" + variable + "}", 'g'); output = output.replace(re, priceContext.interpret(expName)); }); this.el.innerHTML = output; return this; } }
  • 16. Usage const Main = () => { let el = document.body; let view = new View(el, 'contextTpl'); let smallPackage = new SPackage(); smallPackage.add(new TV()); smallPackage.add(new LapTop()); let bigPackage = new BPackage(); bigPackage.add(new Table()); bigPackage.add(new Bed()); bigPackage.add(new Bed()); bigPackage.add(new TV()); let priceContext = new PriceContext( new Bed(), new Table(), new TV(), new LapTop(), smallPackage, bigPackage ); priceContext.setPrice({ 'Bed': 400, 'TV': 200, 'LapTop': 500, 'Table': 50 }); view.render(priceContext); };
  • 17. Sentence and Output Table: 50 TV: 200 LapTop: 500 Bed: 400 Table: 50 Bed: 400 Bed: 400 TV: 200 TV: 200 LapTop: 500 <script type="text/template" id="contextTpl"> <h1>{Table}{SPackage}{Bed}{BPackage}{TV}{LapTop}</h1> </script>
  • 18. Advantages Disadvantages ● You have a simple language to interpret ● You can easily change the method of calculating expressions ● You can represent sentences in the language as abstract syntax trees (AST). ● Difficult to support the grammar with a large number of rules ● Each class on each expression
  • 19. Related Patterns ● Composite for same proccessing terminal and non-terminal expressions ● Flyweight for sharing terminal expressions ● Iterator for traversing the nodes of non-terminals
  • 20. Inspired by Technology. Driven by Value. Have a questions?