{"path": "/posts/metaprogramming-in-javascript/", "title": "Metaprogramming in javascript · Bruno Dias", "html": "<!doctype html>\n<html lang=\"en\">\n<head>\n  <meta charset=\"utf-8\">\n  <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">\n  <meta name=\"description\" content=\"Metaprogramming in javascript\">\n  <title>Metaprogramming in javascript · Bruno Dias</title>\n  <link rel=\"canonical\" href=\"https://diasbruno.github.io/posts/metaprogramming-in-javascript/\" data-post-metadata>\n  <meta name=\"author\" content=\"Bruno Dias\" data-post-metadata>\n  <meta property=\"og:type\" content=\"article\" data-post-metadata>\n  <meta property=\"og:title\" content=\"Metaprogramming in javascript\" data-post-metadata>\n  <meta property=\"og:url\" content=\"https://diasbruno.github.io/posts/metaprogramming-in-javascript/\" data-post-metadata>\n  <meta property=\"article:published_time\" content=\"2020-03-20T15:00:00Z\" data-post-metadata>\n  <link rel=\"icon\" href=\"/assets/site/signature.svg\" type=\"image/svg+xml\">\n  <link rel=\"alternate\" type=\"application/atom+xml\" title=\"diasbruno\" href=\"/atom.xml\">\n  <link rel=\"alternate\" type=\"application/json\" href=\"/posts/metaprogramming-in-javascript/content.json\">\n  <link rel=\"stylesheet\" href=\"/assets/site/tokens.css\">\n  <link rel=\"stylesheet\" href=\"/assets/site/site.css\">\n  <link rel=\"stylesheet\" href=\"/assets/site/footer.css\">\n\n</head>\n<body class=\"light\">\n<div id=\"site-page\">\n<a class=\"skip-link\" href=\"#content\">Skip to content</a>\n<header class=\"site-header\">\n  <a class=\"brand\" href=\"/\" data-site-navigation aria-label=\"Bruno Dias, home\">\n    <img src=\"/assets/site/signature.svg\" width=\"24\" height=\"34\" alt=\"\">\n  </a>\n  <nav aria-label=\"Main navigation\">\n    <ul>\n<li><a class=\"nav-vrn\" href=\"/vrn/\" data-site-navigation><span class=\"nav-label\">vrn</span> <span class=\"nav-badge\">research</span></a></li>\n<li><a class=\"nav-posts\" href=\"/posts/\" data-site-navigation aria-current=\"location\">Posts</a></li>\n<li><a class=\"nav-projects\" href=\"/projects/\" data-site-navigation>Projects</a></li>\n<li><a class=\"nav-about\" href=\"/about/\" data-site-navigation>About</a></li>\n</ul>\n  </nav>\n</header>\n\n<main class=\"section\" id=\"content\" tabindex=\"-1\">\n  <article class=\"post-detail\">\n    <header class=\"section-header\">\n      <p class=\"post-category\">Post</p>\n      <h1>Metaprogramming in javascript</h1>\n\n      <p><time datetime=\"2020-03-20T15:00:00Z\">2020-03-20</time></p>\n    </header>\n    <div class=\"post-columns\">\n      <section class=\"post-body\" aria-label=\"Article\">\n\n<p>Sometimes it's tedious to write the same pattern\nor function.</p>\n<p>In some cases, we can get away with just a closure,\nbut in others, what we really need is to generate\na function with a couple tweaks or to generate it from\na template.</p>\n<p>Unfortunately, we can't do much with the language itself.\nIt would be nice if we had some way to work directly\nwith the AST (abstract syntax tree), or manipulate\nfragments - something like Elixir, or, like the most\nbeautiful language, in my opinion, Lisp.\nAt least, we can always manipulate strings...</p>\n<p>We also have <code>Reflect</code> and <code>Proxy</code>,\nthat are good tools for specific cases,\nbut we are not going to talk about them\nin this article (maybe on the next one).</p>\n<p>In this article, we are going to see some tricks\nto generate specialized functions in runtime.</p>\n<p>The examples we'll use are really simple,\nbut I hope you can understand and write\nmore interesting stuff with it.</p>\n<h2>The Function object</h2>\n<p>We can use the Function object constructor\nto generate new functions.</p>\n<p>Its specification says that the last argument\npassed will be rendered as body of the function, and,\nthe first ones will be the names of the arguments.\nIf only one argument is passed, the function\nhas no arguments.</p>\n<p>Example:</p>\n<pre><code class=\"language-js\">const fn = new Function(&quot;a&quot;, &quot;return a&quot;);\n\nfn(1);\n\n// 1\n\nfn.toString();\n// 'function anonymous(a\\n) {\\nreturn a\\n}'\n</code></pre>\n<h2>Generating operations</h2>\n<p>Let's generate functions for this operations: <code>+</code>, <code>-</code>, <code>*</code>, <code>/</code>.</p>\n<pre><code class=\"language-js\">const generateOperation =\n  op =&gt; new Function(&quot;a&quot;, &quot;b&quot;, `return a ${op} b`);\n\nconst add = generateOperation(&quot;+&quot;);\nconst sub = generateOperation(&quot;-&quot;);\nconst mul = generateOperation(&quot;*&quot;);\nconst div = generateOperation(&quot;/&quot;);\n\nadd(1, 1);\n// 2\nsub(2, 1);\n// 1\nmul(2, 2);\n// 4\ndiv(2, 2);\n// 1\n</code></pre>\n<p>Too easy...but we already can see\nwhere we are going next!</p>\n<h2>Generating functions from URI routes</h2>\n<p>Now we have a different task, to generate functions\nfrom URI routes.</p>\n<p>We are going to convert some route like,\n<code>get:/a/b/{c}/d/{e}</code>, into a function\n<code>function(c, e) { ... }</code>.</p>\n<p>First, we need to find all variables\nin the route. If we don't find any,\nthe function will have no arguments.</p>\n<pre><code class=\"language-js\">// don't trust this function,\n// it's incomplete...\nconst collectVars = route =&gt; {\n   const items = [];\n   for (\n     let str = route, open = -1, close = 0;\n     (\n       open = str.indexOf('{'),\n       close = str.indexOf('}'),\n       open &gt;= 0\n     );\n     str = str.slice(close + 1)\n     ) {\n     if (close &lt; 0) throw Error(&quot;Bad route&quot;);\n     items.push(str.slice(open + 1, close))\n   }\n  return items;\n}\n\ncollectVars(&quot;/a&quot;)\n// []\n\ncollectVars(&quot;/a/b/c/{d}/e/{f}/&quot;)\n// [ &quot;d&quot;, &quot;f&quot; ]\n\ncollectVars(&quot;/a/b/c/{d}/e/{f/&quot;)\n// Thrown:\n// Error: Bad route\n//    at collectVars (repl:12:27)\n</code></pre>\n<p>Now that we have all variables,\nwe can start writing the generator...</p>\n<p>All valid javascript statements are allowed,\nso you can also add a <code>debugger</code> inside of it.</p>\n<pre><code class=\"language-js\">// A simple response processor.\nconst processResponse = async (response) =&gt; {\n  const { status } = response;\n  const data = await response.json();\n  return {\n    'status': (status &gt;= 200 &amp;&amp; status &lt;= 299 ? 'success' :\n        (status &gt;= 400 ? 'error' : 'redirect')),\n    data\n  }\n}\n\nconst makeApi = scheme =&gt; {\n  // get the method and route :P\n  const [method, route] = scheme.split(':');\n\n  // convert to a template string style.\n  // template strings must be wrapped with `\\``\n  // otherwise, you will get compiler errors.\n  const routeTemplate = `\\`${route.replace(/\\{/g, '${')}\\``;\n\n  let vars = collectVars(route).concat(\n    method != 'get' ? [&quot;data=null&quot;] : []\n  ).concat(\n    [&quot;headers={}&quot;]\n  );\n\n  const fnBody = `\nreturn fetch(\n  ${routeTemplate},\n  {\n    method: &quot;${method}&quot;,\n    ...headers,\n    body: data\n  }\n).then(processResponse);\n`;\n\n  const fn = new Function(...vars, fnBody);\n\n  // to make it easy to debug...\n  if (process.env.NODE_ENV != 'production') {\n    fn.args = vars;\n  }\n\n  return fn;\n};\n\nconst getApi = makeApi(&quot;get:/a/b/c/{d}/e/{f}/&quot;);\ngetApi.toString();\n// 'function anonymous(d,f\\n' +\n//   ') {\\n' +\n//   '\\n' +\n//   'return fetch(\\n' +\n//   '  `/a/b/c/${d}/e/${f}/`,\\n' +\n//   '  {\\n' +\n//   '    method: &quot;get&quot;,\\n' +\n//   '  }\\n' +\n//   ').then(processResponse);\\n' +\n//   '\\n' +\n//   '}'\n</code></pre>\n<h3>Conclusion</h3>\n<p>Now you can start writing something\nmore sophisticated than this. You can\neven use any user-defined functions\nas base for your new functions\n(try it with any fn.toString()),\nyou can generate code from DSL\n(Domain Specific Language)...</p>\n<p>That are a lot more in this topic, and now,\nit's up to you to use your creativity!</p>\n<iframe title=\"Metaprogramming in JavaScript on Replit\" loading=\"lazy\" frameborder=\"0\" width=\"100%\" height=\"500px\" src=\"https://replit.com/@diasbruno/metaprogramming-in-js?embed=true\"></iframe>\n\n      </section>\n      <aside class=\"post-links\" aria-labelledby=\"post-links-heading\">\n        <h2 id=\"post-links-heading\">Links</h2>\n        <ul>\n<li><a href=\"/posts/\" data-site-navigation>All posts</a></li>\n        </ul>\n      </aside>\n    </div>\n  </article>\n</main>\n\n<footer class=\"site-footer\">\n  <div class=\"site-footer-inner\">\n    <a class=\"site-footer-home\" href=\"/\" data-site-navigation>Bruno Dias</a>\n    <ul aria-label=\"Footer links\">\n      <li><a href=\"https://github.com/diasbruno\">GitHub</a></li>\n      <li><a href=\"/atom.xml\">Atom feed</a></li>\n    </ul>\n  </div>\n</footer>\n\n</div>\n<script type=\"module\" src=\"/assets/site/navigation.js\"></script>\n</body>\n</html>\n"}
