Jakarta Metaprogramming with Javascript Ahmad Rizqi Meydiarso
Jakarta What is Metaprogramming is the writing of computer programs that write or manipulate other program (or themselves) as
 their data, or that do part of the work at compile time that otherwise be done at runtime “ writing code that writes code
Jakarta The Purpose To have super power! • More elegant code • Less boilerplate code • Hide the how, focus on what • Essential in framework building
Jakarta Background • My first encounter: Prototype.js, jQuery • Experimenting with my own parsing (zparse) and angular like framework foo.js (2007) • Then created chain.js batik etc. (2008-2010) • Now maintaining Merapi and its plugins (for YesBoss / Kata.ai) I love Metaprogramming
Jakarta Uses in Real World • Almost every framework uses Meta Programming in some way • Domain Specific Languages • Add functionalities without littering main logic (logging, measurement, etc.)
Jakarta Two Flavours Dynamic Language Features Program can inspect itself using built-in features of the language. Code Generation Translate meta features into generated code in target language. examples: jquery spring (java) rails (ruby) merapi ;) examples: QT (C++) CoffeeScript React Babel / Typescript
Jakarta Code Generation Examples
Jakarta Code Generation Examples
Jakarta Code Generation Examples
Jakarta Dynamic Language Features • Reflection • Getter Setter • Proxy • Decorator • Generator • DOM Manipulation • Eval
Jakarta Reflection • for (let i in object); • .prototype, getPrototypeOf() • getOwnPropertyNames(), defineProperties() • typeof etc…
Jakarta Reflection Example
Jakarta Reflection Example
Jakarta Getter Setter • {set prop() {}, get prop() {}} • Object.defineProperty() • Object.defineProperties()
Jakarta Getter Setter Example
Jakarta Getter Setter Example
Jakarta Proxy • it’s a trap! • replace object access by function invocation • create truly dynamic object • warning: slow performance • handlers: • get(), set(), has(), ownKeys(), …
Jakarta Proxy Example
Jakarta Proxy Example
Jakarta Generator • Function that stops on “yield” • Returns an Iterator
Jakarta Generator Example
Jakarta Generator Example
Jakarta Decorator • @Decorator • Annotating method / property • manipulate / give context
Jakarta Decorator Example
Jakarta Performance • Code Generation (compile/transpile): • No impact performance (however depends on implementation) • Runtime (processed during initialization only) • Could lead to slower initialization (still ok in most cases) • Runtime (heavy use) • Be careful!
Jakarta Conclusion • It is like doing black magic: • know what you are doing • can have side effects if not used properly • Performance Trade-Off • Unclear Program Flow • Devs not familiar with the core can get confused
rizqi@kata.ai

Metaprogramming with javascript