SlideShare a Scribd company logo
Metaprogramming
with JavaScript
Timur Shemsedinov
Research Institute of System Technologies
What is Metaprogramming?
• Templates and macroses to generate source
code in compile-time
• Self-changing programs
• Programs that generate other programs
• other meanings ?
What is Metaprogramming?
1. This is not artificial intelligence.
2. Metaprogramming is not something new,
you've always used it.
3. In programming languages ​​of Von Neumann architecture
nothing happens without metadata (architecture in which
data and instructions are stored in shared memory and
computer needs to recognize numbers, strings, addresses,
executable instruction, etc.)
What is Metaprogramming?
Programming paradigm that implies program
structure and functionality modification
programmatically
How Metaprogramming works?
Programming paradigm that implies program
structure and functionality modification
programmatically
1. When changes occur?
2. What is changing?
3. Whereby changes occur?
How Metaprogramming works?
When changes occurs?
• Design-time
• Compile-time
• Run-time
• Just-in-Time (immediate when executing/processing)
• Lazy (between executing/processing)
• On Timer
• On Pull requests
• On Push notifications
How Metaprogramming works?
What is changing?
• data types and data structures
• identifiers (class names, type names, variable names)
• calls (method/function names, dynamic binding)
• algorithm parameters
• formula syntax, regular expression syntax, etc.
• dynamic code interpretation (eval)
• data serialization/deserialization
How Metaprogramming works?
Whereby changes occurs?
• Parsing and translation of syntactic structures
• Access to objects and functions by identification name
• Full introspection
• First-class objects individuation:
• functions, using closures
• classes, using inheritance (prototypes in js)
• objects, using mixins
The problem definition
Why do we need Metaprogramming?
• To raise functionality, universality and
abstraction level of software solutions
• Dynamic domains when changing functionality
and structure is a normal mode
• Intersystem/inter-module integration,
using introspection and dynamic binding
Example 1: data definition
var names = [
"Marcus Aurelius Antoninus Augustus",
"Darth Vader",
"Victor Michailovich Glushkov",
"Gottfried Wilhelm von Leibniz",
"Mao Zedong",
"Vladimir Sergeevich Soloviov",
"Ibn Arabi",
"Lev Nikolayevich Tolstoy",
"Muammar Muhammad Abu Minyar al-Gaddafi",
"Rene Descartes",
"Fyodor Mikhailovich Dostoyevsky",
"Benedito de Espinosa"
];
Example 1: solution (without metaprogramming)
function filter(names) {
var result = [], name;
for (var i=0; i<names.length; i++) {
name = names[i];
if ( name.length >= 10 && name.length <= 200 &&
name.indexOf("Mich") > -1 &&
name.indexOf("V") === 0 &&
name.slice(-2) == "ov" &&
!( name.length >= 50 && name.length <= 65 &&
name.indexOf("Abu") > -1 &&
name.indexOf("Lev") === 0 &&
name.slice(-3) == "iov")
) result.push(name);
}
return result;
}
Example 1: extracted metadata
var conditions = {
length: [10, 200],
contains: "Mich",
starts: "V",
ends: "ov",
not: {
length: [50, 65],
contains: "Abu",
starts: "Lev",
ends: "iov"
}
};
Example 1: metamodel
function filter(names, conditions) {
var operations = {
length: function(s,v) { return s.length>=v[0] && s.length<=v[1] },
contains: function(s,v) { return s.indexOf(v) > -1 },
starts: function(s,v) { return s.indexOf(v) === 0 },
ends: function(s,v) { return s.slice(-v.length) == v },
not: function(s,v) { return !check(s,v) }
};
function check(s, conditions) {
var valid = true;
for (var key in conditions)
valid &= operations[key](s, conditions[key]);
return valid;
}
return names.filter(function(s) { return check(s, conditions); });
}
Unified model for IS module
Example 2: task definition
var tasks = [
{ interval:5000, get:"http://127.0.0.1/api/method1.json",
expect:"OK", save:"file1.json" },
{ interval:"8s", get:"http://127.0.0.1/api/method2.json",
put:"http://127.0.0.1/api/method4.json", save:"file2.json" },
{ interval:"7s", get:"http://127.0.0.1/api/method3.json",
expect:"Done", post:"http://127.0.0.1/api/method5.json" },
{ interval:"4s", load:"file1.json",
expect:"OK", put:"http://127.0.0.1/api/method6.json" },
{ interval:"9s", load:"file2.json", save:"file1.json",
post:"http://127.0.0.1/api/method7.json" },
{ interval:"3s", load:"file1.json", save:"file3.json" },
];
Example 2: metamodel
function iterate(tasks) {
function closureTask(task) { return function () {
console.dir(task);
var source;
if (task.get) source = request.get(task.get);
if (task.load) source = fs.createReadStream(task.load);
if (task.save) source.pipe(fs.createWriteStream(task.save));
if (task.post) source.pipe(request.post(task.post));
if (task.put) source.pipe(request.put(task.put));
} };
for (var i=0; i<tasks.length; i++)
setInterval(closureTask(tasks[i]), duration(tasks[i].interval));
}
Example 2: metamodel (with internal configuration)
function iterate(tasks) {
var sources = { get: request.get,
load: fs.createReadStream };
var destinations = { save: fs.createWriteStream,
post: request.post,
put: request.put };
function closureTask(task) { return function () {
console.dir(task);
var verb, source, destination;
for (key in sources)
if (task[key]) source = sources[key](task[key]);
for (key in destinations)
if (task[key]) source.pipe(destinations[key](task[key]));
} };
for (var i=0; i<tasks.length; i++)
setInterval(closureTask(tasks[i]), duration(tasks[i].interval));
}
Example 3: interpretation
// Parse duration to seconds, example: duration("1d 10h 7m 13s")
function duration(s) {
var result = 0;
if (typeof(s) == 'string') {
var days = s.match(/(d+)s*d/),
hours = s.match(/(d+)s*h/),
minutes = s.match(/(d+)s*m/),
seconds = s.match(/(d+)s*s/);
if (days) result += parseInt(days[1])*86400;
if (hours) result += parseInt(hours[1])*3600;
if (minutes) result += parseInt(minutes[1])*60;
if (seconds) result += parseInt(seconds[1]);
result = result*1000;
} if (typeof(s) == 'number') result = s;
return result;
}
Example 3: interpretation (configurable)
function duration(s) {
if (typeof(s) == 'number') return s;
var units = {
days: { rx:/(d+)s*d/, mul:86400 },
hours: { rx:/(d+)s*h/, mul:3600 },
minutes: { rx:/(d+)s*m/, mul:60 },
seconds: { rx:/(d+)s*s/, mul:1 }
};
var result = 0, unit, match;
if (typeof(s) == 'string') for (var key in units) {
unit = units[key];
match = s.match(unit.rx);
if (match) result += parseInt(match[1])*unit.mul;
}
return result*1000;
}
Example 4: introspection in metaprogramming
Example 4: introspection
var ds = wcl.AjaxDataSource({
read: { get: "examples/person/read.json" },
insert: { post: "examples/person/insert.json" },
update: { post: "examples/person/update.json" },
delete: { post: "examples/person/delete.json" },
find: { post: "examples/person/find.json" },
metadata: { post: "examples/person/metadata.json" }
});
ds.read({ id:5 }, function(err, data) {
data.phone ="+0123456789";
ds.update(data, function(err) {
console.log('Data saved');
});
});
Example 4: introspection in metaprogramming
var ds = wcl.AjaxDataSource({
introspect: { post: "examples/person/introspect.json" }
});
ds.read({ id:3 }, function(err, data) {
data.phone ="+0123456789";
ds.update(data, function(err) {
console.log('Data saved');
});
});
Example 4: introspection in metaprogramming
var ds = wcl.MemoryDataSource({ data: [
{ id:1, name:"Person 1", phone:"+380501002011",
emails:[ "person1@domain.com" ], age: 25 },
{ id:2, name:"Person 2", phone:"+380501002022",
emails:[ "person2@domain.com", "person2@domain2.com" ],
address: { city: "Kiev", street:"Khreschatit", building: "26" } },
{ id:3, name:"Person 3", phone:"+380501002033",
emails:[ "person3@domain.com" ],
tags: [ {tag:"tag1", color:"red"}, {tag:"tag2", color:"green"} ] },
]});
ds.read({ id:3 }, function(err, data) {
data.phone ="+0123456789";
ds.update(data, function(err) {
console.log('Data saved');
});
});
Metaprogramming techniques
• Task definition style: declarative, using metadata,
imperative and functional elements
• Hashes (associative arrays)
beforehand unknown key: var a = {}; a[key] = value;
• String interpretation, inventing domain-specific syntactic
structures or using universal ones (json, js, regexp ...)
• Mixins: beforehand unknown targer object/class
function mixin(a) { a.fn=function(){ ... } }
• Closures: function individuations
fn = (function(a) { return function() { return a*2 } })(value)
The findings
• Code size: generally decrease a lot but may increases code size
in rare cases (compensated by code readability)
• Speed: slightly decreases but good implementation
may remain approximately the same speed
• Flexibility: solution becomes more abstract/universal
software application scope expands
• Integration: usually much simplified integration
and requires less code changes
• Working pleasure: metaprogramming is interesting
so we have more pleasure and motivation
• Working speed: increasing development time but modification and
support tasks take less time, so total time is less
Metaprogramming
with JavaScript
Github: https://github.com/tshemsedinov/metaprogramming
Article: http://habrahabr.ru/post/227753/
Metaprogramming
with JavaScript
Thank you!
Questions please
Timur Shemsedinov
Research Institute of System Technologies

More Related Content

PDF
Metarhia: Node.js Macht Frei
PDF
Node.js for enterprise - JS Conference
PPTX
Mongoose and MongoDB 101
PDF
Original slides from Ryan Dahl's NodeJs intro talk
PDF
NodeJS for Beginner
PDF
NodeJS: an Introduction
PDF
Node.js Explained
KEY
node.js: Javascript's in your backend
Metarhia: Node.js Macht Frei
Node.js for enterprise - JS Conference
Mongoose and MongoDB 101
Original slides from Ryan Dahl's NodeJs intro talk
NodeJS for Beginner
NodeJS: an Introduction
Node.js Explained
node.js: Javascript's in your backend

What's hot (20)

PDF
NodeJS
PDF
Shared memory and multithreading in Node.js - Timur Shemsedinov - JSFest'19
KEY
A million connections and beyond - Node.js at scale
PDF
Node.js
PDF
Node.js and How JavaScript is Changing Server Programming
PDF
DEF CON 23 - amit ashbel and maty siman - game of hacks
PPT
Node js presentation
KEY
Node.js - Best practices
PPTX
introduction to node.js
PDF
PPTX
The Art of JVM Profiling
PDF
Индексируем базу: как делать хорошо и не делать плохо Winter saint p 2021 m...
PDF
Node.js - A Quick Tour
PPTX
03 standard class library
KEY
Building a real life application in node js
PDF
Multithreading in Node.js and JavaScript
PDF
MongoDB + node.js で作るソーシャルゲーム
PDF
MongoDB Performance Debugging
PDF
Everything you wanted to know about Stack Traces and Heap Dumps
ODP
Asynchronous I/O in NodeJS - new standard or challenges?
NodeJS
Shared memory and multithreading in Node.js - Timur Shemsedinov - JSFest'19
A million connections and beyond - Node.js at scale
Node.js
Node.js and How JavaScript is Changing Server Programming
DEF CON 23 - amit ashbel and maty siman - game of hacks
Node js presentation
Node.js - Best practices
introduction to node.js
The Art of JVM Profiling
Индексируем базу: как делать хорошо и не делать плохо Winter saint p 2021 m...
Node.js - A Quick Tour
03 standard class library
Building a real life application in node js
Multithreading in Node.js and JavaScript
MongoDB + node.js で作るソーシャルゲーム
MongoDB Performance Debugging
Everything you wanted to know about Stack Traces and Heap Dumps
Asynchronous I/O in NodeJS - new standard or challenges?
Ad

Similar to Metaprogramming with JavaScript (20)

PDF
"Applied Enterprise Metaprogramming in JavaScript", Vladyslav Dukhin
PPTX
Metaprogramming, Metaobject Protocols, Gradual Type Checks: Optimizing the "U...
PPT
Metaprogramming by brandon
PDF
TripCase Unit Testing with Jasmine
PPTX
Metaprogramming in ES6
PDF
Metarhia KievJS 22-Feb-2018
PDF
Rediscovering JavaScript: The Language Behind The Libraries
PPTX
Exploring metaprogramming using Ruby language
PDF
Refactoring
PDF
10 Ways To Improve Your Code( Neal Ford)
PDF
A Systematic Language Engineering Approach for Prototyping Domain Specific Mo...
PDF
ECMAScript 6 new features
PDF
Refactoring
PPT
Testing Model Transformations
PPTX
What’s new in ECMAScript 6.0
PPT
Rapid software evolution
KEY
JavaScript Growing Up
PDF
Monads and Monoids by Oleksiy Dyagilev
PDF
Semantic code transformations in MetaJS
PPTX
Awesomeness of JavaScript…almost
"Applied Enterprise Metaprogramming in JavaScript", Vladyslav Dukhin
Metaprogramming, Metaobject Protocols, Gradual Type Checks: Optimizing the "U...
Metaprogramming by brandon
TripCase Unit Testing with Jasmine
Metaprogramming in ES6
Metarhia KievJS 22-Feb-2018
Rediscovering JavaScript: The Language Behind The Libraries
Exploring metaprogramming using Ruby language
Refactoring
10 Ways To Improve Your Code( Neal Ford)
A Systematic Language Engineering Approach for Prototyping Domain Specific Mo...
ECMAScript 6 new features
Refactoring
Testing Model Transformations
What’s new in ECMAScript 6.0
Rapid software evolution
JavaScript Growing Up
Monads and Monoids by Oleksiy Dyagilev
Semantic code transformations in MetaJS
Awesomeness of JavaScript…almost
Ad

More from Timur Shemsedinov (20)

PDF
How to use Chat GPT in JavaScript optimizations for Node.js
PDF
IT Revolution in 2023-2024: AI, GPT, business transformation, future professi...
PDF
Node.js threads for I/O-bound tasks
PDF
Node.js Меньше сложности, больше надежности Holy.js 2021
PDF
Rethinking low-code
PDF
Hat full of developers
PDF
FwDays 2021: Metarhia Technology Stack for Node.js
PDF
Node.js for enterprise 2021 - JavaScript Fwdays 3
PDF
Node.js in 2021
PDF
Node.js middleware: Never again!
PDF
Patterns and antipatterns
PDF
Race-conditions-web-locks-and-shared-memory
PDF
Asynchronous programming and mutlithreading
PDF
Node.js in 2020 - part 3
PDF
Node.js in 2020 - part 2
PDF
Information system structure and architecture
PDF
Node.js in 2020 - part 1
PDF
Web Locks API
PDF
Node.js in 2020
PDF
Введение в SQL
How to use Chat GPT in JavaScript optimizations for Node.js
IT Revolution in 2023-2024: AI, GPT, business transformation, future professi...
Node.js threads for I/O-bound tasks
Node.js Меньше сложности, больше надежности Holy.js 2021
Rethinking low-code
Hat full of developers
FwDays 2021: Metarhia Technology Stack for Node.js
Node.js for enterprise 2021 - JavaScript Fwdays 3
Node.js in 2021
Node.js middleware: Never again!
Patterns and antipatterns
Race-conditions-web-locks-and-shared-memory
Asynchronous programming and mutlithreading
Node.js in 2020 - part 3
Node.js in 2020 - part 2
Information system structure and architecture
Node.js in 2020 - part 1
Web Locks API
Node.js in 2020
Введение в SQL

Recently uploaded (20)

PPTX
Agentic AI Use Case- Contract Lifecycle Management (CLM).pptx
PDF
How to Migrate SBCGlobal Email to Yahoo Easily
PDF
Claude Code: Everyone is a 10x Developer - A Comprehensive AI-Powered CLI Tool
PPTX
Oracle E-Business Suite: A Comprehensive Guide for Modern Enterprises
PDF
Flood Susceptibility Mapping Using Image-Based 2D-CNN Deep Learnin. Overview ...
PDF
2025 Textile ERP Trends: SAP, Odoo & Oracle
PDF
Audit Checklist Design Aligning with ISO, IATF, and Industry Standards — Omne...
PPTX
Introduction to Artificial Intelligence
PPTX
Odoo POS Development Services by CandidRoot Solutions
PPTX
VVF-Customer-Presentation2025-Ver1.9.pptx
PDF
Design an Analysis of Algorithms I-SECS-1021-03
PDF
PTS Company Brochure 2025 (1).pdf.......
PPTX
Lecture 3: Operating Systems Introduction to Computer Hardware Systems
PDF
Internet Downloader Manager (IDM) Crack 6.42 Build 42 Updates Latest 2025
PPTX
ai tools demonstartion for schools and inter college
PPTX
L1 - Introduction to python Backend.pptx
PDF
Internet Downloader Manager (IDM) Crack 6.42 Build 41
PDF
Softaken Excel to vCard Converter Software.pdf
PPT
Introduction Database Management System for Course Database
PDF
medical staffing services at VALiNTRY
Agentic AI Use Case- Contract Lifecycle Management (CLM).pptx
How to Migrate SBCGlobal Email to Yahoo Easily
Claude Code: Everyone is a 10x Developer - A Comprehensive AI-Powered CLI Tool
Oracle E-Business Suite: A Comprehensive Guide for Modern Enterprises
Flood Susceptibility Mapping Using Image-Based 2D-CNN Deep Learnin. Overview ...
2025 Textile ERP Trends: SAP, Odoo & Oracle
Audit Checklist Design Aligning with ISO, IATF, and Industry Standards — Omne...
Introduction to Artificial Intelligence
Odoo POS Development Services by CandidRoot Solutions
VVF-Customer-Presentation2025-Ver1.9.pptx
Design an Analysis of Algorithms I-SECS-1021-03
PTS Company Brochure 2025 (1).pdf.......
Lecture 3: Operating Systems Introduction to Computer Hardware Systems
Internet Downloader Manager (IDM) Crack 6.42 Build 42 Updates Latest 2025
ai tools demonstartion for schools and inter college
L1 - Introduction to python Backend.pptx
Internet Downloader Manager (IDM) Crack 6.42 Build 41
Softaken Excel to vCard Converter Software.pdf
Introduction Database Management System for Course Database
medical staffing services at VALiNTRY

Metaprogramming with JavaScript

  • 2. What is Metaprogramming? • Templates and macroses to generate source code in compile-time • Self-changing programs • Programs that generate other programs • other meanings ?
  • 3. What is Metaprogramming? 1. This is not artificial intelligence. 2. Metaprogramming is not something new, you've always used it. 3. In programming languages ​​of Von Neumann architecture nothing happens without metadata (architecture in which data and instructions are stored in shared memory and computer needs to recognize numbers, strings, addresses, executable instruction, etc.)
  • 4. What is Metaprogramming? Programming paradigm that implies program structure and functionality modification programmatically
  • 5. How Metaprogramming works? Programming paradigm that implies program structure and functionality modification programmatically 1. When changes occur? 2. What is changing? 3. Whereby changes occur?
  • 6. How Metaprogramming works? When changes occurs? • Design-time • Compile-time • Run-time • Just-in-Time (immediate when executing/processing) • Lazy (between executing/processing) • On Timer • On Pull requests • On Push notifications
  • 7. How Metaprogramming works? What is changing? • data types and data structures • identifiers (class names, type names, variable names) • calls (method/function names, dynamic binding) • algorithm parameters • formula syntax, regular expression syntax, etc. • dynamic code interpretation (eval) • data serialization/deserialization
  • 8. How Metaprogramming works? Whereby changes occurs? • Parsing and translation of syntactic structures • Access to objects and functions by identification name • Full introspection • First-class objects individuation: • functions, using closures • classes, using inheritance (prototypes in js) • objects, using mixins
  • 9. The problem definition Why do we need Metaprogramming? • To raise functionality, universality and abstraction level of software solutions • Dynamic domains when changing functionality and structure is a normal mode • Intersystem/inter-module integration, using introspection and dynamic binding
  • 10. Example 1: data definition var names = [ "Marcus Aurelius Antoninus Augustus", "Darth Vader", "Victor Michailovich Glushkov", "Gottfried Wilhelm von Leibniz", "Mao Zedong", "Vladimir Sergeevich Soloviov", "Ibn Arabi", "Lev Nikolayevich Tolstoy", "Muammar Muhammad Abu Minyar al-Gaddafi", "Rene Descartes", "Fyodor Mikhailovich Dostoyevsky", "Benedito de Espinosa" ];
  • 11. Example 1: solution (without metaprogramming) function filter(names) { var result = [], name; for (var i=0; i<names.length; i++) { name = names[i]; if ( name.length >= 10 && name.length <= 200 && name.indexOf("Mich") > -1 && name.indexOf("V") === 0 && name.slice(-2) == "ov" && !( name.length >= 50 && name.length <= 65 && name.indexOf("Abu") > -1 && name.indexOf("Lev") === 0 && name.slice(-3) == "iov") ) result.push(name); } return result; }
  • 12. Example 1: extracted metadata var conditions = { length: [10, 200], contains: "Mich", starts: "V", ends: "ov", not: { length: [50, 65], contains: "Abu", starts: "Lev", ends: "iov" } };
  • 13. Example 1: metamodel function filter(names, conditions) { var operations = { length: function(s,v) { return s.length>=v[0] && s.length<=v[1] }, contains: function(s,v) { return s.indexOf(v) > -1 }, starts: function(s,v) { return s.indexOf(v) === 0 }, ends: function(s,v) { return s.slice(-v.length) == v }, not: function(s,v) { return !check(s,v) } }; function check(s, conditions) { var valid = true; for (var key in conditions) valid &= operations[key](s, conditions[key]); return valid; } return names.filter(function(s) { return check(s, conditions); }); }
  • 14. Unified model for IS module
  • 15. Example 2: task definition var tasks = [ { interval:5000, get:"http://127.0.0.1/api/method1.json", expect:"OK", save:"file1.json" }, { interval:"8s", get:"http://127.0.0.1/api/method2.json", put:"http://127.0.0.1/api/method4.json", save:"file2.json" }, { interval:"7s", get:"http://127.0.0.1/api/method3.json", expect:"Done", post:"http://127.0.0.1/api/method5.json" }, { interval:"4s", load:"file1.json", expect:"OK", put:"http://127.0.0.1/api/method6.json" }, { interval:"9s", load:"file2.json", save:"file1.json", post:"http://127.0.0.1/api/method7.json" }, { interval:"3s", load:"file1.json", save:"file3.json" }, ];
  • 16. Example 2: metamodel function iterate(tasks) { function closureTask(task) { return function () { console.dir(task); var source; if (task.get) source = request.get(task.get); if (task.load) source = fs.createReadStream(task.load); if (task.save) source.pipe(fs.createWriteStream(task.save)); if (task.post) source.pipe(request.post(task.post)); if (task.put) source.pipe(request.put(task.put)); } }; for (var i=0; i<tasks.length; i++) setInterval(closureTask(tasks[i]), duration(tasks[i].interval)); }
  • 17. Example 2: metamodel (with internal configuration) function iterate(tasks) { var sources = { get: request.get, load: fs.createReadStream }; var destinations = { save: fs.createWriteStream, post: request.post, put: request.put }; function closureTask(task) { return function () { console.dir(task); var verb, source, destination; for (key in sources) if (task[key]) source = sources[key](task[key]); for (key in destinations) if (task[key]) source.pipe(destinations[key](task[key])); } }; for (var i=0; i<tasks.length; i++) setInterval(closureTask(tasks[i]), duration(tasks[i].interval)); }
  • 18. Example 3: interpretation // Parse duration to seconds, example: duration("1d 10h 7m 13s") function duration(s) { var result = 0; if (typeof(s) == 'string') { var days = s.match(/(d+)s*d/), hours = s.match(/(d+)s*h/), minutes = s.match(/(d+)s*m/), seconds = s.match(/(d+)s*s/); if (days) result += parseInt(days[1])*86400; if (hours) result += parseInt(hours[1])*3600; if (minutes) result += parseInt(minutes[1])*60; if (seconds) result += parseInt(seconds[1]); result = result*1000; } if (typeof(s) == 'number') result = s; return result; }
  • 19. Example 3: interpretation (configurable) function duration(s) { if (typeof(s) == 'number') return s; var units = { days: { rx:/(d+)s*d/, mul:86400 }, hours: { rx:/(d+)s*h/, mul:3600 }, minutes: { rx:/(d+)s*m/, mul:60 }, seconds: { rx:/(d+)s*s/, mul:1 } }; var result = 0, unit, match; if (typeof(s) == 'string') for (var key in units) { unit = units[key]; match = s.match(unit.rx); if (match) result += parseInt(match[1])*unit.mul; } return result*1000; }
  • 20. Example 4: introspection in metaprogramming
  • 21. Example 4: introspection var ds = wcl.AjaxDataSource({ read: { get: "examples/person/read.json" }, insert: { post: "examples/person/insert.json" }, update: { post: "examples/person/update.json" }, delete: { post: "examples/person/delete.json" }, find: { post: "examples/person/find.json" }, metadata: { post: "examples/person/metadata.json" } }); ds.read({ id:5 }, function(err, data) { data.phone ="+0123456789"; ds.update(data, function(err) { console.log('Data saved'); }); });
  • 22. Example 4: introspection in metaprogramming var ds = wcl.AjaxDataSource({ introspect: { post: "examples/person/introspect.json" } }); ds.read({ id:3 }, function(err, data) { data.phone ="+0123456789"; ds.update(data, function(err) { console.log('Data saved'); }); });
  • 23. Example 4: introspection in metaprogramming var ds = wcl.MemoryDataSource({ data: [ { id:1, name:"Person 1", phone:"+380501002011", emails:[ "person1@domain.com" ], age: 25 }, { id:2, name:"Person 2", phone:"+380501002022", emails:[ "person2@domain.com", "person2@domain2.com" ], address: { city: "Kiev", street:"Khreschatit", building: "26" } }, { id:3, name:"Person 3", phone:"+380501002033", emails:[ "person3@domain.com" ], tags: [ {tag:"tag1", color:"red"}, {tag:"tag2", color:"green"} ] }, ]}); ds.read({ id:3 }, function(err, data) { data.phone ="+0123456789"; ds.update(data, function(err) { console.log('Data saved'); }); });
  • 24. Metaprogramming techniques • Task definition style: declarative, using metadata, imperative and functional elements • Hashes (associative arrays) beforehand unknown key: var a = {}; a[key] = value; • String interpretation, inventing domain-specific syntactic structures or using universal ones (json, js, regexp ...) • Mixins: beforehand unknown targer object/class function mixin(a) { a.fn=function(){ ... } } • Closures: function individuations fn = (function(a) { return function() { return a*2 } })(value)
  • 25. The findings • Code size: generally decrease a lot but may increases code size in rare cases (compensated by code readability) • Speed: slightly decreases but good implementation may remain approximately the same speed • Flexibility: solution becomes more abstract/universal software application scope expands • Integration: usually much simplified integration and requires less code changes • Working pleasure: metaprogramming is interesting so we have more pleasure and motivation • Working speed: increasing development time but modification and support tasks take less time, so total time is less
  • 27. Metaprogramming with JavaScript Thank you! Questions please Timur Shemsedinov Research Institute of System Technologies