{"path": "/posts/some-interesting-ideas-with-types-and-javascript/", "title": "some interesting ideas with types and 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=\"some interesting ideas with types and javascript\">\n  <title>some interesting ideas with types and javascript · Bruno Dias</title>\n  <link rel=\"canonical\" href=\"https://diasbruno.github.io/posts/some-interesting-ideas-with-types-and-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=\"some interesting ideas with types and javascript\" data-post-metadata>\n  <meta property=\"og:url\" content=\"https://diasbruno.github.io/posts/some-interesting-ideas-with-types-and-javascript/\" data-post-metadata>\n  <meta property=\"article:published_time\" content=\"2023-03-17T21:03:01Z\" 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/some-interesting-ideas-with-types-and-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>some interesting ideas with types and javascript</h1>\n\n      <p><time datetime=\"2023-03-17T21:03:01Z\">2023-03-17</time></p>\n    </header>\n    <div class=\"post-columns\">\n      <section class=\"post-body\" aria-label=\"Article\">\n\n<p>javascript has a weird type/object system, but we can make some interesting stuff with it...</p>\n<h4>pattern match or a nice switch/case</h4>\n<p>We don't need the most precise/robust implementation\nof pattern matching. It can be used on user-defined\ntypes to help spliting what can be on a class and\nwhat can be simple functions instead.</p>\n<pre><code class=\"language-js\">/**\n * Takes an object and a table\n * dispatch according to the constructor\n * of the object.\n * `object` must be something constructed with `new`.\n */\nfunction match(object, table) {\n  const name = object.constructor.name;\n  return (table[name] || table['_'])(object);\n}\n\nclass A {}\n\nfunction onA(object) {\n  return match(object, {\n    A: (a) =&gt; console.log(a),\n    '_': () =&gt; console.log(&quot;like default on a switch&quot;)\n  });\n}\n\nonA(new A);\n// A {}\n\nonA(null || 0 || 'string' || 1);\n// like default on a switch\n</code></pre>\n<p>This is a great tool when you need\nto return values depending on the context.</p>\n<p>We can imagine a case where if we have an\n<code>A</code>, we must return an string, or in another\ncase, it should be a number. So, instead of\nhaving a bigger or many interface(s), we use\nmatch to return accordingly.</p>\n<pre><code class=\"language-js\">function A(value) {\n  if (!(this instanceof A))\n    return new A(value);\n  this.value = value;\n}\n\n// Note that in this case\n// we are not using the value\nfunction asNumber(object) {\n  return match(object, {\n    A: () =&gt; 1,\n    '_': () =&gt; 0\n  });\n}\n\n// Note that in this case\n// we are expecting that `A`\n// holds a string.\n// (in fact, it can hold any value -\n// if we want)\nfunction asString(object) {\n  return match(object, {\n    A: (a) =&gt; a.value,\n    '_': () =&gt; ''\n  });\n}\n\nfunction stringSize(object) {\n  return match(object, {\n    A: (a) =&gt; a.value.length,\n    '_': () =&gt; 0\n  });\n}\n\nasNumber(new A);\n// 1\nasNumber(null || 0 || 'string' || 1);\n// 0\n\nasString(new A('ok'));\n// 'ok'\nasString(null || 0 || 'string' || 1);\n// ''\n\nstringSize(new A('ok'));\n// 2\nstringSize(null || 0 || 'string' || 1);\n// 0\n</code></pre>\n<h4>moving types as values</h4>\n<p>Imagine a json like:</p>\n<pre><code class=\"language-json\">{\n  &quot;type&quot;: &quot;empty&quot;\n}\n</code></pre>\n<p>This object has no information. It holds only\nthe property that tells which type it is.</p>\n<p>If we use this plain object,\neverywhere on the codebase we are going\nto access the <code>.type</code> property and the behavior\nwill be all over the place.</p>\n<p>Instead, we can create a type for it...</p>\n<pre><code class=\"language-js\">const Empty = new (function Empty() {});\n</code></pre>\n<p>Now that we have a proper type,\nwe can add behaviors on it.</p>\n<p>NOTE: there is no significant cost for doing this.</p>\n<p>NOTE: the prototype for this object will be\nhidden or you will need to do a little bit\nof gynastic to get it (Empty.constructor.prototype...).\nBut it's not necessary to use it.</p>\n<pre><code class=\"language-js\">Empty.asString = function() {\n  return '';\n};\n\nEmpty.asNumber = function() {\n  return 0;\n};\n\nEmpty.toJSON = function() {\n  return { &quot;type&quot;: &quot;empty&quot; };\n};\n</code></pre>\n<p>It's has no relation to the singleton pattern.</p>\n<h4>maybe monad</h4>\n<p>If you have heard about functors or monads,\nand haskell, maybe is an object in the <code>Hask</code> category\nthat has two constructors:</p>\n<ul>\n<li>Nothing</li>\n<li>Just a (where <code>a</code> is any other type - Just(a))</li>\n</ul>\n<p>The nothing constructor has no arguments. So\nwe can instantiate once and just pass it around.</p>\n<p>The other constructor is <code>Just</code> and it has a single argument.</p>\n<pre><code class=\"language-js\">const Nothing = new (function Nothing {});\n\nfunction Just(a) {\n  if (!(this instanceof Just)) {\n    return new Just(a);\n  }\n  this.value = a;\n}\n\nNothing.constructor.name;\n// 'Nothing'\nJust(1).constructor.name;\n// Just'\n</code></pre>\n<p>Here is how we can implement <code>functor</code> for our maybe type.</p>\n<p>It's out of scope for this article to explain\nfunctors, but there are a lot of content out there\nexplaining it.</p>\n<pre><code class=\"language-js\">const Nothing = new (function Nothing() {});\n\nfunction Just(a) {\n  if (!(this instanceof Just)) {\n    return new Just(a);\n  }\n  this.value = a;\n}\n\nNothing.map = function(_) {\n  return Nothing;\n};\n\nJust.prototype.map = function(f) {\n  return Just(f(this.value));\n};\n\nJust(1).map(v =&gt; v + 1).map(v =&gt; v * 2)\n// Just(4)\nNothing.map(v =&gt; v + 1).map(v =&gt; v * 2)\n// Nothing\n\n// our value needs to be between 0 and 10.\n//\n// don't do this!!! this is just an example.\n// (unless it makes sense...)\n\nfunction valueToMaybe(v) {\n  return v &lt; 0 || v &gt; 10 ? Nothing : Just(v);\n}\n\nvalueToMaybe(1).map(v =&gt; v + 1).map(v =&gt; v * 2)\n// Just(4)\nvalueToMaybe(11).map(v =&gt; v + 1).map(v =&gt; v * 2)\n// Nothing\n\n// giving a hint\n[1].map(v =&gt; v + 1).map(v =&gt; v * 2)\n// [4]\n</code></pre>\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<li><a href=\"/posts/even-more-ideas-with-types-and-javascript-equality-ordering-and-enumeration/\" data-site-navigation>even more ideas with types and javascript (equality, ordering and enumeration)</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"}
