SlideShare a Scribd company logo
1 of 20
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

仕事で使うF#
仕事で使うF#仕事で使うF#
仕事で使うF#bleis tift
 
C intro
C introC intro
C introKamran
 
Compiler Construction | Lecture 9 | Constraint Resolution
Compiler Construction | Lecture 9 | Constraint ResolutionCompiler Construction | Lecture 9 | Constraint Resolution
Compiler Construction | Lecture 9 | Constraint ResolutionEelco Visser
 
pointer, structure ,union and intro to file handling
pointer, structure ,union and intro to file handlingpointer, structure ,union and intro to file handling
pointer, structure ,union and intro to file handlingRai University
 
Esoft Metro Campus - Programming with C++
Esoft Metro Campus - Programming with C++Esoft Metro Campus - Programming with C++
Esoft Metro Campus - Programming with C++Rasan Samarasinghe
 
Python Functions 1
Python Functions 1Python Functions 1
Python Functions 1gsdhindsa
 
Functional Python Webinar from October 22nd, 2014
Functional Python Webinar from October 22nd, 2014Functional Python Webinar from October 22nd, 2014
Functional Python Webinar from October 22nd, 2014Reuven Lerner
 
pointer, structure ,union and intro to file handling
pointer, structure ,union and intro to file handlingpointer, structure ,union and intro to file handling
pointer, structure ,union and intro to file handlingRai University
 

What's hot (20)

Lecture 14 - Scope Rules
Lecture 14 - Scope RulesLecture 14 - Scope Rules
Lecture 14 - Scope Rules
 
Pointer in C
Pointer in CPointer in C
Pointer in C
 
Pointer basics
Pointer basicsPointer basics
Pointer basics
 
Function C programming
Function C programmingFunction C programming
Function C programming
 
Recursion in c
Recursion in cRecursion in c
Recursion in c
 
Lập trình C
Lập trình CLập trình C
Lập trình C
 
仕事で使うF#
仕事で使うF#仕事で使うF#
仕事で使うF#
 
Function in C Language
Function in C Language Function in C Language
Function in C Language
 
Function in C
Function in CFunction in C
Function in C
 
C++ programming
C++ programmingC++ programming
C++ programming
 
C intro
C introC intro
C intro
 
Ch3 repetition
Ch3 repetitionCh3 repetition
Ch3 repetition
 
Compiler Construction | Lecture 9 | Constraint Resolution
Compiler Construction | Lecture 9 | Constraint ResolutionCompiler Construction | Lecture 9 | Constraint Resolution
Compiler Construction | Lecture 9 | Constraint Resolution
 
C Programming - Refresher - Part II
C Programming - Refresher - Part II C Programming - Refresher - Part II
C Programming - Refresher - Part II
 
07. Virtual Functions
07. Virtual Functions07. Virtual Functions
07. Virtual Functions
 
pointer, structure ,union and intro to file handling
pointer, structure ,union and intro to file handlingpointer, structure ,union and intro to file handling
pointer, structure ,union and intro to file handling
 
Esoft Metro Campus - Programming with C++
Esoft Metro Campus - Programming with C++Esoft Metro Campus - Programming with C++
Esoft Metro Campus - Programming with C++
 
Python Functions 1
Python Functions 1Python Functions 1
Python Functions 1
 
Functional Python Webinar from October 22nd, 2014
Functional Python Webinar from October 22nd, 2014Functional Python Webinar from October 22nd, 2014
Functional Python Webinar from October 22nd, 2014
 
pointer, structure ,union and intro to file handling
pointer, structure ,union and intro to file handlingpointer, structure ,union and intro to file handling
pointer, structure ,union and intro to file handling
 

Similar to Interpreter Design Pattern in Javascript

#PDR15 Creating Pebble Apps for Aplite, Basalt, and Chalk
#PDR15 Creating Pebble Apps for Aplite, Basalt, and Chalk#PDR15 Creating Pebble Apps for Aplite, Basalt, and Chalk
#PDR15 Creating Pebble Apps for Aplite, Basalt, and ChalkPebble Technology
 
.NET 2015: Будущее рядом
.NET 2015: Будущее рядом.NET 2015: Будущее рядом
.NET 2015: Будущее рядомAndrey Akinshin
 
CS4200 2019 | Lecture 5 | Transformation by Term Rewriting
CS4200 2019 | Lecture 5 | Transformation by Term RewritingCS4200 2019 | Lecture 5 | Transformation by Term Rewriting
CS4200 2019 | Lecture 5 | Transformation by Term RewritingEelco Visser
 
Reflection in Go
Reflection in GoReflection in Go
Reflection in Gostrikr .
 
C++ STL (quickest way to learn, even for absolute beginners).pptx
C++ STL (quickest way to learn, even for absolute beginners).pptxC++ STL (quickest way to learn, even for absolute beginners).pptx
C++ STL (quickest way to learn, even for absolute beginners).pptxAbhishek Tirkey
 
C++ STL (quickest way to learn, even for absolute beginners).pptx
C++ STL (quickest way to learn, even for absolute beginners).pptxC++ STL (quickest way to learn, even for absolute beginners).pptx
C++ STL (quickest way to learn, even for absolute beginners).pptxGauravPandey43518
 
Unit testing en iOS @ MobileCon Galicia
Unit testing en iOS @ MobileCon GaliciaUnit testing en iOS @ MobileCon Galicia
Unit testing en iOS @ MobileCon GaliciaRobot Media
 
Groovy Introduction - JAX Germany - 2008
Groovy Introduction - JAX Germany - 2008Groovy Introduction - JAX Germany - 2008
Groovy Introduction - JAX Germany - 2008Guillaume Laforge
 
Introduction To Groovy 2005
Introduction To Groovy 2005Introduction To Groovy 2005
Introduction To Groovy 2005Tugdual Grall
 
Design patterns for fun and profit
Design patterns for fun and profitDesign patterns for fun and profit
Design patterns for fun and profitNikolas Vourlakis
 
Meetup C++ A brief overview of c++17
Meetup C++  A brief overview of c++17Meetup C++  A brief overview of c++17
Meetup C++ A brief overview of c++17Daniel Eriksson
 
Introduction to Griffon
Introduction to GriffonIntroduction to Griffon
Introduction to GriffonJames Williams
 

Similar to Interpreter Design Pattern in Javascript (20)

#PDR15 Creating Pebble Apps for Aplite, Basalt, and Chalk
#PDR15 Creating Pebble Apps for Aplite, Basalt, and Chalk#PDR15 Creating Pebble Apps for Aplite, Basalt, and Chalk
#PDR15 Creating Pebble Apps for Aplite, Basalt, and Chalk
 
.NET 2015: Будущее рядом
.NET 2015: Будущее рядом.NET 2015: Будущее рядом
.NET 2015: Будущее рядом
 
Qt Workshop
Qt WorkshopQt Workshop
Qt Workshop
 
CS4200 2019 | Lecture 5 | Transformation by Term Rewriting
CS4200 2019 | Lecture 5 | Transformation by Term RewritingCS4200 2019 | Lecture 5 | Transformation by Term Rewriting
CS4200 2019 | Lecture 5 | Transformation by Term Rewriting
 
Reflection in Go
Reflection in GoReflection in Go
Reflection in Go
 
C++ STL (quickest way to learn, even for absolute beginners).pptx
C++ STL (quickest way to learn, even for absolute beginners).pptxC++ STL (quickest way to learn, even for absolute beginners).pptx
C++ STL (quickest way to learn, even for absolute beginners).pptx
 
C++ STL (quickest way to learn, even for absolute beginners).pptx
C++ STL (quickest way to learn, even for absolute beginners).pptxC++ STL (quickest way to learn, even for absolute beginners).pptx
C++ STL (quickest way to learn, even for absolute beginners).pptx
 
Ch8a
Ch8aCh8a
Ch8a
 
Unit testing en iOS @ MobileCon Galicia
Unit testing en iOS @ MobileCon GaliciaUnit testing en iOS @ MobileCon Galicia
Unit testing en iOS @ MobileCon Galicia
 
Groovy
GroovyGroovy
Groovy
 
Groovy Introduction - JAX Germany - 2008
Groovy Introduction - JAX Germany - 2008Groovy Introduction - JAX Germany - 2008
Groovy Introduction - JAX Germany - 2008
 
Introduction To Groovy 2005
Introduction To Groovy 2005Introduction To Groovy 2005
Introduction To Groovy 2005
 
Python 3000
Python 3000Python 3000
Python 3000
 
Design patterns for fun and profit
Design patterns for fun and profitDesign patterns for fun and profit
Design patterns for fun and profit
 
Meetup C++ A brief overview of c++17
Meetup C++  A brief overview of c++17Meetup C++  A brief overview of c++17
Meetup C++ A brief overview of c++17
 
Python basic
Python basicPython basic
Python basic
 
Variables
VariablesVariables
Variables
 
Austen x talk
Austen x talkAusten x talk
Austen x talk
 
Introduction to Griffon
Introduction to GriffonIntroduction to Griffon
Introduction to Griffon
 
Managed Compiler
Managed CompilerManaged Compiler
Managed Compiler
 

Recently uploaded

Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...OnePlan Solutions
 
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️Delhi Call girls
 
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...Health
 
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...MyIntelliSource, Inc.
 
TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providermohitmore19
 
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️anilsa9823
 
Optimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVOptimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVshikhaohhpro
 
A Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxA Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxComplianceQuest1
 
5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdfWave PLM
 
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfLearn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfkalichargn70th171
 
How To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.jsHow To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.jsAndolasoft Inc
 
Unlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language ModelsUnlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language Modelsaagamshah0812
 
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...panagenda
 
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...ICS
 
HR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comHR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comFatema Valibhai
 
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...harshavardhanraghave
 
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...MyIntelliSource, Inc.
 
CALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female service
CALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female serviceCALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female service
CALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female serviceanilsa9823
 
Diamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with PrecisionDiamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with PrecisionSolGuruz
 

Recently uploaded (20)

Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
 
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
 
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
 
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
 
TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service provider
 
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️
 
Optimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVOptimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTV
 
A Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxA Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docx
 
5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf
 
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfLearn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
 
How To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.jsHow To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.js
 
Unlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language ModelsUnlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language Models
 
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
 
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
 
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS LiveVip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
 
HR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comHR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.com
 
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
 
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
 
CALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female service
CALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female serviceCALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female service
CALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female service
 
Diamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with PrecisionDiamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with Precision
 

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?