<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Esbjörn Blomquist on Medium]]></title>
        <description><![CDATA[Stories by Esbjörn Blomquist on Medium]]></description>
        <link>https://medium.com/@realworldjs?source=rss-a4c3a2bd191f------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/2*9s_w_eGJHCTQkxmiZPqPig.jpeg</url>
            <title>Stories by Esbjörn Blomquist on Medium</title>
            <link>https://medium.com/@realworldjs?source=rss-a4c3a2bd191f------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 22 Nov 2026 04:00:19 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@realworldjs/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Rethinking the Dot operator in JavaScript]]></title>
            <link>https://realworldjs.medium.com/never-use-the-dot-operator-in-javascript-ee0339d85fb?source=rss-a4c3a2bd191f------2</link>
            <guid isPermaLink="false">https://medium.com/p/ee0339d85fb</guid>
            <category><![CDATA[optional-chaining]]></category>
            <category><![CDATA[nullish-coalescing]]></category>
            <category><![CDATA[destructuring]]></category>
            <category><![CDATA[default-value]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Esbjörn Blomquist]]></dc:creator>
            <pubDate>Sat, 28 Aug 2021 15:59:35 GMT</pubDate>
            <atom:updated>2024-09-09T09:25:36.385Z</atom:updated>
            <content:encoded><![CDATA[<h3>Never use the Dot operator in JavaScript, for Data</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*NqT2IwNhO7yIH4NN" /><figcaption>Photo by <a href="https://unsplash.com/@divazus?utm_source=medium&amp;utm_medium=referral">Divazus Fabric Store</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>The <strong>Dot operator</strong> is dangerous because if, at run-time, the value of the identifier before it is not what was intended, the program will likely <em>throw an error</em> and probably <strong>crash</strong>.</p><p>Firstly, there are of course cases where the dot operator is perfectly fine. Knowing <strong>where</strong>, and <strong>why</strong>, is what this article is about. But mostly it is about <strong>destructuring </strong>which I believe is the <em>undervalued &amp; underused</em> solution.</p><blockquote>Destructuring is undervalued &amp; underused.</blockquote><p>Secondly, let’s from the start acknowledge that with ES2019 two <strong>new operators</strong> were introduced to JavaScript:</p><ul><li>Optional chaining: ?.</li><li>Nullish coalescing: ??</li></ul><p>These make it possible to write user?.name ?? &#39;Noname&#39; and <em>not crash</em> for non-existent user, and have a <em>fallback </em>for if any one of user or name does not exist.</p><p><strong>These are fine, but not as great as destructuring.</strong></p><p><em>But hey…</em></p><h3>Let’s start from the beginning</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*BPKlyTBhSdC-TOL7" /><figcaption>Photo by <a href="https://unsplash.com/@mikaela_stenstrom?utm_source=medium&amp;utm_medium=referral">Mikaela Stenström</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Perhaps you’re playing with some home automation script, and you type out a helper function for some data structure, like below. You know that celsius is not always there so you throw in a fallback.</p><pre>const getTemperature = (atticData) =&gt; atticData.celsius || 15;</pre><p>This function will have <strong>two serious problems</strong>:</p><ul><li>What if the object you give the function is <strong>uninitialized</strong> at some point, undefined? Then it will crash.</li><li>What if the Celsius temperature is <strong>0</strong>? The function will return 15!</li></ul><p>With the two new operators mentioned in the beginning, you fix the function:</p><pre>const getTemperature = (atticData) =&gt; atticData?.celsius ?? 15;</pre><p>The two problems are solved. This is great.</p><blockquote>Should we use optional chaining operator everywhere now?</blockquote><p>No. For two reasons:</p><ul><li>It would just be in the way of readability for any <strong>known</strong> <strong>static</strong> structure, like an API. E.g. JSON.parse, window.localStorage.getItem or identifiers inside imported libraries.</li><li>Destructuring might be a better alternative in most <strong>other</strong> cases, where we handle any <strong>data</strong>.</li></ul><p>Continuing with our example function above — it would, written with <strong>destructuring</strong>, look like this:</p><pre>const getTemperature = ({ celsius = 15 } = {}) =&gt; celsius;</pre><p>It is slightly <strong>cleaner</strong>, and it actually got more <strong>general</strong> in that it doesn’t necessarily lie about what it operates on. We avoid naming that. Any potential object could be given to this function, and it would attempt to safely extract a celsius.</p><p>Another way to think about it is that inside our function we never need to reference the data object, only stuff inside it. So we dig that out <strong>as early as possible</strong>. The function body can also <em>not do anything with anything else</em> than celsius, it could not for instance get the crazy idea to mutate the data object — it is not available.</p><blockquote>Destructure as early as possible.</blockquote><p><em>(The destructuring version is not strictly the same. See section about </em><em>null last in the article.)</em></p><h3>Changing habits</h3><blockquote>Whenever you type a dot, stop and think about if you could <strong>already</strong> have destructured out the value you’re after.</blockquote><p>It often makes for shorter code with higher <strong>control</strong>. Mainly due to the ability to set defaults, but also because we can control what is <strong>available</strong> in the scope and how it’s available. We also have the possibility of destructuring in multiple levels, “<strong>nested</strong> destructuring”, and then set <strong>safe defaults</strong> along the way in.</p><p>As mentioned — destructuring is not necessary for known static APIs. But, any <strong>data,</strong> even some config that you <em>think of as static</em>, is worth destructuring, with defaults.</p><h4>Using destructuring</h4><p>Let’s see what we can do with destructuring:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8901d664940ec2ee1dd206cf83077f07/href">https://medium.com/media/8901d664940ec2ee1dd206cf83077f07/href</a></iframe><p>This function utilizes destructuring features in different ways. Let’s analyze:</p><ul><li>Setting defaults at the first/<strong>highest level</strong> (argument list) makes sure we can’t crash for empty arguments: func(). <em>(This is “default parameters” that nicely work the </em><strong><em>same way</em></strong><em> as destructuring defaults).</em></li><li>Rename long key names for more readable logic when <em>using</em> the value (msg).</li><li>Use <strong>nested</strong> destructuring if you only need what’s <strong>inside</strong> a member value. But again, remember to also <strong>add a default</strong> to make the destructuring safe from crashing should the member value not exist.<br>(E.g. line 5 above)</li><li>It is powerful to also use the <strong>rest operator</strong> to be able to handle everything that was not explicitly destructured.</li><li>If we <strong>both</strong> need to use the <strong>whole</strong> structure <em>and</em> values inside, we destructure in the function scope (otherwise in the function header — as early as possible). <br>(As with data above)</li><li>Both <em>destructuring &amp; the rest operator</em> can be used for <strong>arrays</strong> as well.</li><li>We don’t have to repeat a long expression options.pos.x for a value if it’s used multiple times in the scope. Instead, just x. Cleaner, safer and also more performant in that JS doesn’t have to dig out the value each time.</li></ul><p>This was an example of preparing for…</p><h4>A function body</h4><p>Consider that you in some function body need:</p><pre>profile.user.address.street.name<br>profile.user.address.city</pre><p>Say that this is highly <strong>dynamic</strong> data, and you want to do something with them, concatenate perhaps. Without destructuring you’d type:</p><pre>`${profile?.user?.address?.street?.name ?? “Unknown street”} ${profile?.user?.address?.city ?? “Unknown city”}`</pre><p>Not very pleasant(?) It is a mix of:</p><ul><li>What we operate on</li><li>How we operate on it</li></ul><p><strong>With destructuring</strong>, made as early as possible in a suitable way for the situation:</p><ul><li>You have <strong>declaratively</strong> made the unpacking of the stuff that is <em>important to the logic</em> in a <strong>separate</strong> step.</li><li>If you did the destructuring in the function argument list, <strong>only</strong> the values that is <strong>needed</strong> for the logic is available, <strong>nothing else</strong>. This also <em>adds</em> to why destructuring could be considered <em>safer</em>. You’re <strong>controlling</strong> what’s in the scope.</li><li>You know that you have <strong>safe</strong>,<strong> short</strong> values to work with, also easily usable <strong>multiple times</strong> in the scope. This is positive for the <strong>clarity</strong> of the logic.</li></ul><p>So in your function body you now type:</p><pre>`${streetName} ${city}`</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/556/1*3jWdzIr8oBNkkqdZsUyiyQ.png" /></figure><h3>Conclusion</h3><p>What this article suggests as a habit:</p><ul><li><strong>Every time</strong> you type a dot . — <strong>stop</strong> and think about if this is <strong>data</strong> that you’re operating on. If so — <strong>use destructuring</strong> instead.</li><li>Destructure as <strong>early</strong> as possible.</li><li>Remember to include <strong>default</strong> values, especially in nested destructuring.</li></ul><p><em>I know... We have to address the </em><strong><em>elephant in the room</em></strong><em>:</em></p><h3>Null in JavaScript</h3><p>The <em>destructuring</em> version of the small example function is <strong>not strictly</strong> the same as with <em>optional chaining</em> &amp; <em>nullish coalescing</em>. <strong>null</strong> is the value that will behave differently.</p><p>But it is not strictly <em>destructuring</em> that makes the example throw an error, it is <strong>default parameters</strong> (introduced in ES2015/ES6). Some put it this way:</p><blockquote>null breaks default parameters.</blockquote><p>However, <em>destructuring defaults</em> work the same way, which means they also only fall back to the defaults for undefined — <strong>not</strong> for null.</p><h4>This is actually because it is the correct way</h4><ul><li>undefined in JavaScript means that the value is not yet set, it is <strong>not defined</strong>. All uninitialized values get the value undefined at run time, or a specified default value.</li><li>null is an identifier that means that the value<strong> is actually set</strong>, but for some reason it could not get a proper value. Historically, null was included in the language for when one wanted to clear a variable containing (referencing) an object and let garbage collection destroy it. That’s why its type is &quot;object&quot;. null is different from undefined and does not mean the same thing (and should not in your code).</li></ul><blockquote>undefined and null does not <strong>mean</strong> the same thing.</blockquote><p>Acknowledging the <em>meanings &amp; differences</em> <em>between</em> these two, both default parameters &amp; destructuring <strong>work as intended</strong>.</p><p>I, along with <a href="https://www.youtube.com/watch?v=PSGEjv3Tqo0&amp;feature=youtu.be&amp;t=9m21s">Douglas Crockford</a>, <a href="https://github.com/Microsoft/TypeScript/wiki/Coding-guidelines#null-and-undefined">the Typescript team</a>, <a href="https://medium.com/javascript-scene/handling-null-and-undefined-in-javascript-1500c65d51ae">Eric Elliot</a> &amp; many others, <strong>recommend</strong> that null should simply <strong>not be used</strong> in JavaScript (always use undefined instead, and use ESLint to help avoid it: <a href="https://www.npmjs.com/package/eslint-plugin-no-null">https://www.npmjs.com/package/eslint-plugin-no-null</a>).</p><blockquote>null should not be used in JavaScript.</blockquote><p>But that is subject for another article.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ee0339d85fb" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Automatic Documentation For JavaScript Projects — README, JSDoc & Mermaid]]></title>
            <link>https://realworldjs.medium.com/automatic-documentation-for-javascript-projects-readme-jsdoc-mermaid-86b86be9b28d?source=rss-a4c3a2bd191f------2</link>
            <guid isPermaLink="false">https://medium.com/p/86b86be9b28d</guid>
            <category><![CDATA[automatic]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[jsdoc]]></category>
            <category><![CDATA[mermaid]]></category>
            <category><![CDATA[documentation]]></category>
            <dc:creator><![CDATA[Esbjörn Blomquist]]></dc:creator>
            <pubDate>Mon, 22 Feb 2021 10:12:11 GMT</pubDate>
            <atom:updated>2024-07-04T08:23:09.662Z</atom:updated>
            <content:encoded><![CDATA[<h3>Automatic Documentation For JavaScript Projects — README, JSDoc &amp; Mermaid</h3><figure><img alt="Misty Autumn Forest" src="https://cdn-images-1.medium.com/max/1024/1*lZoIuRT3neghvt4r43AENQ.jpeg" /></figure><blockquote>This article is a result of some research I did around generating documentation for NodeJS/JavaScript based projects, back in 2021. Partly updated 2024–06.</blockquote><p>When using <strong>JSDoc</strong> to document JavaScript code with <strong>doc-strings</strong>, a next step is to get this information extracted and presented in a nice, friendly way. In any project, we also always have a README.md file with introductory descriptions and information. Imagine an automatically generated documentation UI where the README would become the front page, and the whole API structured behind it, visually describing the interface of the project, all extracted from the JSDoc.</p><p>Inside our README.md we could have made informative drawings to explain some control flow or architecture, written in the nowadays commonly seen <strong>mermaid</strong> language. We certainly want these drawings to become rendered graphically in our documentation webpage. Our README.md, needs to otherwise be rendered nicely with bullet lists, tables, and other expected output from <strong>markdown</strong> syntax.</p><p>JSDoc has many <strong>tags</strong> to describe a JavaScript construct. It would be nice to have <strong>support</strong> for a great set of these in our generated rendering. Basic stuff like optional arguments and default values are not always supported by JSDoc parsers. Ability to use some markdown in JSDoc descriptions can also be really nice.</p><p>Personally nowadays I really like dark <strong>theme</strong> pretty much everywhere on a screen. It would thus be nice to get this possibility for our documentation. Another feature that would be highly desired is a <strong>search field</strong> with ability to search or filter among all our documented constructs.</p><p>A documentation website needs to be set up once, and then generated again with new updates from the code and README with just one npm run docs command.</p><p>There are many <strong>frameworks </strong>and<strong> libraries</strong> out there that promises to do the job. What they produce does however vary a lot. Which ones are easy to install, easy to configure, support enough JSDoc tags, possible to style or change theme, and have enough features?</p><p>A summary of my set of requirements goes something like below.</p><ul><li>Get the README.md document as <strong>landing page</strong>.</li><li>Get a well structured and <strong>easily navigated</strong> site of extracted documentation from the JSDoc <strong>doc strings</strong> found around the code.</li><li>Good support for different JSDoc <strong>tags</strong> and clear default styling of each documented construct from the code (@param , @returns , @static , @async , etc).</li><li>A global <strong>search</strong> field.</li><li>Some markdown support for the JSDoc description fields (at least support for <strong>multi-line</strong> text in the main description as well as for the @returns).</li><li>Automatic rendering of possible <strong>mermaid</strong> diagrams in the README.</li></ul><p><em>A note to those not running Linux is that some scripts herein will contain </em><strong><em>Linux commands</em></strong><em> and will not work in other operating systems. It is left as an exercise to translate these into platform independent (nodejs based) equivalents.</em></p><h3>Documentation.js</h3><p><strong>Docs</strong>: <a href="https://github.com/documentationjs/documentation">https://github.com/documentationjs/documentation</a><br><strong>Repository</strong>: <a href="https://github.com/documentationjs/documentation">https://github.com/documentationjs/documentation</a><br><strong>npm package</strong>: <a href="https://www.npmjs.com/package/documentation">https://www.npmjs.com/package/documentation</a><br><strong>GitHub stars</strong>: 5k<br><strong>npm downloads</strong>: 150k</p><p>This library is in a way closely related to jsdoc-to-markdown (used in the setup of many other strategies below) in that it can just be a markdown generator with JS files as input, parsing doc strings. But it can also instead build HTML from the JSDoc, and glue the output together with markdown files.</p><p>That makes up the minimum of what we want. But let’s see how we set it up and how the result behaves.</p><p>npm i -D documentation</p><p>Add to package.json scripts:</p><pre>&quot;docs-show&quot;: &quot;firefox -new-tab ./docs/index.html -foreground&quot;,<br>&quot;docs-gen&quot;: &quot;npx documentation build {​​​​​​​src/utils/*.js,src/logic/*.js}​​​​​​​ --config documentation.yml -f html -o docs&quot;,<br>&quot;docs&quot;: &quot;npm run docs-gen &amp;&amp; npm run docs-show&quot;</pre><p>Create a new file documentation.yml:</p><pre>toc:<br>  - name: README<br>    file: README.md</pre><p>Add to .gitignore:</p><pre>/docs</pre><p>Now run:<br>npm run docs</p><h4>Pros:</h4><ul><li>Minimalistic &amp; clean output.</li><li>Very simple setup.</li></ul><h4>Cons:</h4><ul><li>Not the best documentation (of <em>documentation.js</em>).</li><li>No automatic file or @module scoping.<br>- This makes every function and construct end up in just a big pool.</li><li>No simple way to get dark theme, except starting to build one by copying and modifying their default theme as HTML generation templates.</li><li>Bad (no?) support for code blocks.</li><li>Not found any mermaid support.</li><li>Hard to web search things related to this library (the name is so generic!).</li></ul><p>The ability to generate markdown from JSDoc was tested as a way to get module scoping. However, it made a much worse job, with missing information and formatting, compared to its HTML output.</p><h3>Docusaurus (v3)</h3><p><strong>Docs</strong>: <a href="https://v2.docusaurus.io/">https://docusaurus.io/</a><br><strong>Repository</strong>: <a href="https://github.com/facebook/docusaurus">https://github.com/facebook/docusaurus</a><br><strong>npm package</strong>: <a href="https://www.npmjs.com/package/@docusaurus/core">https://www.npmjs.com/package/@docusaurus/core</a><br><strong>GitHub stars</strong>: 50k<br><strong>npm downloads</strong>: 300k</p><p>This is <strong>facebook’s</strong> popular and very actively developed static site generator. In combination with jsdoc-to-markdown it is able to provide the solution we&#39;re looking for. First prepare our current project:</p><p>npm i -D jsdoc-to-markdown mermaid</p><p>Then create the docusaurus sub-app:</p><pre>npx create-docusaurus@latest docs classic</pre><p>Now we have a docs app inside our app (in /docs). We need to go there and add some things.<br>cd docs &amp; follow the Docusaurus <a href="https://docusaurus.io/docs/markdown-features/diagrams">mermaid guide</a>.</p><p>Continue editing docusaurus.config.js with all your project meta-data.</p><p>We can configure the sidebar insidebars.js (still in /docs):</p><pre>{<br>  &quot;someSidebar&quot;: {<br>    &quot;Site Docs&quot;: [&quot;README&quot;, &quot;api&quot;]<br>  }<br>}</pre><p>There are endless possibilities in configuring and modifying this docs app now, since it is a front-end project in it self. One might want to remove the landing page and make the site land on the README, but this is left out of this article.</p><p>We will be checking in the /docs folder into version control (git), but not the target for the generated files, /docs/docs.</p><p>Add to .gitignore:<br>/docs/docs</p><p>The &quot;scripts&quot; we need to add in our package.json (not the one in /docs!) are:</p><pre>&quot;postinstall&quot;: &quot;cd docs &amp;&amp; npm i &amp;&amp; mkdir docs &amp;&amp; cd ..&quot;,<br>&quot;docs:md&quot;: &quot;cp *.md docs/docs/&quot;,<br>&quot;docs:api&quot;: &quot;npx jsdoc2md src/**/*.js &gt; docs/docs/api.md&quot;,<br>&quot;docs&quot;: &quot;npm run docs:md &amp;&amp; npm run docs:api &amp;&amp; cd docs &amp;&amp; npm start&quot;</pre><ul><li>The docs:md script copies e.g. README.md to /docs/docs.</li><li>docs:api runs the cli tool in jsdoc-to-markdown on a glob and outputs to /docs/docs. You can modify the glob here to fit your code-base.</li></ul><p>Now, by running:<br>npm run docs<br>we can browse to localhost:3000 to see our result.</p><h4>Pros:</h4><ul><li>Very good structure of the site, with page ToC &amp; file/module separation.</li><li>Great default theme with both light &amp; dark mode.<br>- Great markdown rendering.</li><li>Well supported &amp; used framework.</li></ul><h4>Cons:</h4><ul><li>Complex setup.<br>- Lots of configuration.</li><li>Not the best search feature.<br>- Added through plugin, might exist better ones.</li></ul><h3>Docsify</h3><p><strong>Docs</strong>: <a href="https://docsify.js.org/">https://docsify.js.org/</a><br><strong>Repository</strong>: <a href="https://github.com/docsifyjs/docsify/">https://github.com/docsifyjs/docsify/</a><br><strong>npm package</strong>: <a href="https://www.npmjs.com/package/docsify">https://www.npmjs.com/package/docsify</a><br><strong>GitHub stars</strong>: 16k<br><strong>npm downloads</strong>: 25k</p><p>This versatile and popular documentation framework is an interesting candidate. However, it can not parse JSDoc so we need to combine this solution with jsdoc-to-markdown.</p><p>npm i -D docsify-cli jsdoc-to-markdown docsify-fulltextsearch</p><p>docsify init ./docs</p><p>Now that you got a /docs folder, we will modify index.html and add a file _navbar.md inside it.</p><p>First open index.html and replace its content with the code below (In case this article has gotten a bit dated, you might want to check the standard generated index.html and just add chosen bits from below).</p><pre>&lt;!DOCTYPE html&gt;<br>&lt;html lang=&quot;en&quot;&gt;<br>  &lt;head&gt;<br>    &lt;meta charset=&quot;UTF-8&quot; /&gt;<br>    &lt;title&gt;Documentation&lt;/title&gt;<br>    &lt;meta http-equiv=&quot;X-UA-Compatible&quot; content=&quot;IE=edge,chrome=1&quot; /&gt;<br>    &lt;meta name=&quot;description&quot; content=&quot;Description&quot; /&gt;<br>    &lt;meta<br>      name=&quot;viewport&quot;<br>      content=&quot;width=device-width, initial-scale=1.0, minimum-scale=1.0&quot;<br>    /&gt;<br>    &lt;link<br>      rel=&quot;stylesheet&quot;<br>      href=&quot;https://cdn.jsdelivr.net/npm/docsify-themeable@0/dist/css/theme-simple-dark.css&quot;<br>    /&gt;<br>    &lt;style&gt;<br>      /* style the nav-bar to be much more visible */<br>      .app-nav {<br>        text-align: center;<br>        font-size: 1.5rem;<br>        position: relative;<br>        background-color: rgba(0, 0, 0, 0.3);<br>        margin-left: 0 !important;<br>        right: 0 !important;<br>        left: 0;<br>        top: 0;<br>        z-index: 1;<br>      }<br>      .app-nav &gt; ul &gt; li {<br>        padding: 16px;<br>        border-bottom: 4px solid var(--mono-tint2);<br>      }<br>    &lt;/style&gt;<br>  &lt;/head&gt;<br>  &lt;body&gt;<br>    &lt;div id=&quot;app&quot;&gt;&lt;/div&gt;<br>    &lt;script&gt;<br>      window.$docsify = {<br>        name: &quot;Documentation&quot;,<br>        loadNavbar: true,<br>        mergeNavbar: true, // Is this needed ?????????????<br>        auto2top: true,<br>        subMaxLevel: 3,<br>        formatUpdated: &quot;{MM}/{DD} {HH}:{mm}&quot;,<br>        // logo: &#39;logo.png&#39;, // Add a logo if you wish<br>        search: [&quot;/&quot;, &quot;/api&quot;],<br>        executeScript: true<br>      };<br>    &lt;/script&gt;<br>    &lt;script src=&quot;//cdn.jsdelivr.net/npm/docsify@4&quot;&gt;&lt;/script&gt;</pre><pre>    &lt;!-- plugins --&gt;<br>    &lt;script src=&quot;https://cdn.jsdelivr.net/npm/docsify-themeable@0/dist/js/docsify-themeable.min.js&quot;&gt;&lt;/script&gt;<br>    &lt;script src=&quot;https://cdn.jsdelivr.net/npm/docsify@4/lib/plugins/search.js&quot;&gt;&lt;/script&gt;<br>    &lt;!-- mermaid --&gt;<br>    &lt;script src=&quot;//unpkg.com/mermaid/dist/mermaid.js&quot;&gt;&lt;/script&gt;<br>    &lt;script src=&quot;//unpkg.com/docsify-mermaid@latest/dist/docsify-mermaid.js&quot;&gt;<br>      &lt;script&gt;<br>          mermaid.initialize({ startOnLoad: true });<br>    &lt;/script&gt;<br>    &lt;style&gt;<br>      /* activate full width for content, for mermaid graphs benefit */<br>      .markdown-section {<br>        max-width: none;<br>      }<br>    &lt;/style&gt;<br>  &lt;/body&gt;<br>&lt;/html&gt;</pre><p>Then add the file _navbar.md in the docs folder with this content:</p><pre>* [README](/)<br>* [API](/api)</pre><p>Add our re-generated doc files to .gitignore:</p><pre>/docs/README.md<br>/docs/api.md</pre><p>Lastly we need some &quot;scripts&quot; in package.json:</p><pre>&quot;docs-show&quot;: &quot;npx docsify serve ./docs&quot;,<br>&quot;docs-gen&quot;: &quot;cp -u README.md docs/ &amp;&amp; npx jsdoc2md {src/**/*.js} &gt; docs/api.md&quot;,<br>&quot;docs&quot;: &quot;npm run docs-gen &amp;&amp; npm run docs-show&quot;</pre><p>Now we are ready to run:</p><p>npm run docs</p><h4>Pros:</h4><ul><li>Easy adding of mermaid support.<br>- Simple possibility to get full width for mermaid graphs.</li><li>Dark theme.</li></ul><h4>Cons:</h4><ul><li>Section nav-bar is a bit too hidden and needs custom styling.</li><li>Search results could be prettier.</li><li>Somewhat complex setup/configuration.<br>- But at least most conf is in one file.</li></ul><h3>JSDoc + docdash</h3><h4>JSDoc3</h4><p><strong>Docs</strong>: <a href="https://jsdoc.app/">https://jsdoc.app/</a><br><strong>Repository</strong>: <a href="https://github.com/jsdoc/jsdoc">https://github.com/jsdoc/jsdoc</a><br><strong>npm package</strong>: <a href="https://www.npmjs.com/package/jsdoc">https://www.npmjs.com/package/jsdoc</a><br><strong>GitHub stars</strong>: 11k<br><strong>npm downloads</strong>: 500k</p><h4>docdash</h4><p><strong>Docs</strong>: <a href="http://clenemt.github.io/docdash/">http://clenemt.github.io/docdash/</a><br><strong>Repository</strong>: <a href="https://github.com/clenemt/docdash">https://github.com/clenemt/docdash</a><br><strong>npm package</strong>: <a href="https://www.npmjs.com/package/docdash">https://www.npmjs.com/package/docdash</a><br><strong>GitHub stars</strong>: 600<br><strong>npm downloads</strong>: 90k</p><p>This is what anyone would first encounter searching for a JSDoc syntax documentation site generator. It is very old in the game, but still highly used (also behind the scenes in other documentation frameworks). It is based on so called <em>templates</em> that are modules of both theming/styling and features &amp; settings for the site generation. There are many available templates. We add perhaps the most popular one that is great looking and has a well built set of features and settings.</p><p>npm i -D jsdoc docdash replace</p><p>The following is a somewhat standard JSON config file .jsdoc.json with template docdash activated and tweaked for our needs.</p><pre>{<br>  &quot;plugins&quot;: [&quot;plugins/markdown&quot;],<br>  &quot;source&quot;: {<br>    &quot;include&quot;: [&quot;src&quot;, &quot;README.md&quot;],<br>    &quot;includePattern&quot;: &quot;.+\\.js$&quot;,<br>    &quot;excludePattern&quot;: &quot;(node_modules/|docs)&quot;<br>  },<br>  &quot;tags&quot;: {<br>    &quot;allowUnknownTags&quot;: true,<br>    &quot;dictionaries&quot;: [&quot;jsdoc&quot;, &quot;closure&quot;]<br>  },<br>  &quot;opts&quot;: {<br>    &quot;destination&quot;: &quot;./docs/&quot;,<br>    &quot;readme&quot;: &quot;./README.md&quot;,<br>    &quot;encoding&quot;: &quot;utf8&quot;,<br>    &quot;private&quot;: true,<br>    &quot;recurse&quot;: true,<br>    &quot;template&quot;: &quot;./node_modules/docdash&quot;<br>  },<br>  &quot;docdash&quot;: {<br>    &quot;search&quot;: true,<br>    &quot;scripts&quot;: [&quot;https://unpkg.com/mermaid/dist/mermaid.js&quot;, &quot;docs-init.js&quot;]<br>  }<br>}</pre><p>For enabling mermaid graphs we added a couple of scripts above in the &quot;docdash&quot; section, where the second one is a local custom docs-init.js that needs the following lines.</p><pre>/* eslint-disable */<br>window.addEventListener(&quot;load&quot;, () =&gt;<br>  mermaid.initialize({ startOnLoad: true })<br>);</pre><p>These are suggested &quot;scripts&quot; to add in package.json:</p><pre>&quot;docs-show&quot;: &quot;firefox -new-tab ./docs/index.html -foreground&quot;,<br>&quot;docs-mermaid&quot;: &quot;npx replace &#39;&lt;pre class=\&quot;prettyprint source lang-mermaid\&quot;&gt;&lt;code&gt;(((?!(&lt;\\/code&gt;))(\\s|\\S))+)&lt;\\/code&gt;&lt;\\/pre&gt;&#39; &#39;&lt;div class=\&quot;mermaid\&quot;&gt;$1&lt;/div&gt;&#39; -r --include=\&quot;index.html\&quot; ./docs/&quot;,<br>&quot;docs-gen&quot;: &quot;npx jsdoc -c .jsdoc.json &amp;&amp; cp -u docs-init.js docs/&quot;,<br>&quot;docs&quot;: &quot;npm run docs-gen &amp;&amp; npm run docs-mermaid &amp;&amp; npm run docs-show&quot;</pre><p>The &quot;docs-mermaid&quot; script became a beast so feel free to make some node script file instead that replaces mermaid code tags. (<em>Even better if you make some module on npm for this as a JSDoc plugin! Yes, there is a </em><em>jsdoc-mermaid plugin already, but that one only converts mermaid code inside doc-strings</em>). The reason I made this as an inline script is to keep everything together a bit more, for simplicity.</p><p>We update our .gitignore to not include our generated bundle in /docs:</p><pre>/docs</pre><p><em>An alternative:</em> If we include &quot;package.json&quot; in our &quot;source&quot;.&quot;include&quot; list in .jsdoc.json above, JSDoc will produce <strong>versioned bundles</strong> in /docs instead of putting the docs site bundle directly in /docs. It can in that case be nice to push these to source control.</p><p>(The mermaid parts can of course be <strong>removed</strong> if that support is really not needed: The line &quot;docdash&quot;.&quot;scripts&quot; in the config, the docs-init.js file, and &amp;&amp; cp -u docs-init.js docs/ in &quot;docs-gen&quot; npm script.)</p><h4>Pros:</h4><ul><li>Most popular solution with long time in the game.</li><li>High versatility through templates.</li><li>Selecting a good template can give many settings &amp; features.<br>- Great markdown &amp; doc strings rendering can be achieved.</li><li>Multiple well built and actively maintained templates available.</li><li>Straightforward setup &amp; configuration.<br>- At least without mermaid additions, but even with the mermaid hack it’s not that complex.</li></ul><h4>Cons:</h4><ul><li>No plugin for adding mermaid support.<br>- Template settings, a minor script, and a substitution/replace command can however enable it.</li></ul><h3>Docma</h3><p><strong>Docs</strong>: <a href="https://onury.io/docma/">https://onury.io/docma/</a><br><strong>Repository</strong>: <a href="https://github.com/onury/docma">https://github.com/onury/docma</a><br><strong>npm package</strong>: <a href="https://www.npmjs.com/package/docma">https://www.npmjs.com/package/docma</a><br><strong>GitHub stars</strong>: 280<br><strong>npm downloads</strong>: 2k</p><p>This framework tryout did not get as much time and effort as others because of it being unpupular, and also because of too many thumbs down for the initial result.</p><p>npm i -D docma</p><p>One short line needed in package.json -&gt; &quot;scripts&quot;:</p><pre>&quot;docs&quot;: &quot;docma &amp;&amp; docma serve ./docs&quot;</pre><h4>Pros:</h4><ul><li>Good markdown styling.</li><li>Interesting feature of automatic categorization of documented constructs.<br>- Colors &amp; filters</li></ul><h4>Cons:</h4><ul><li>Markdown pages &amp; code docs are split into completely separate pages.<br>- This should be easy to solve given that the Docma docs themselves combine them.</li><li>Bad JSDoc styling.<br>- No markdown support in doc strings.</li><li>JSDoc tag support is not great.</li><li>The automatic categorization lowers control &amp; adds lots of unwanted entities.</li><li>It would need a hack to enable mermaid.</li></ul><h3>DocumentJS</h3><p><strong>Docs</strong>: <a href="https://documentjs.com/">https://documentjs.com/</a><br><strong>Repository</strong>: <a href="https://github.com/bitovi/documentjs">https://github.com/bitovi/documentjs</a><br><strong>npm package</strong>: <a href="https://www.npmjs.com/package/documentjs">https://www.npmjs.com/package/documentjs</a><br><strong>GitHub stars</strong>: 590<br><strong>npm downloads</strong>: 180</p><p>This framework tryout did not get as much time and effort as others because of it being unpupular, and also because of too many thumbs down for the initial result.</p><p>npm i -D documentjs</p><p>We need a small configuration file documentjs.json:</p><pre>{<br>  &quot;sites&quot;: {<br>    &quot;docs&quot;: {<br>      &quot;glob&quot;: &quot;{src/**/*.js,README.md}&quot;<br>    }<br>  }<br>}</pre><p>Lines to add in package.json -&gt; &quot;scripts&quot;:</p><pre>&quot;docs-show&quot;: &quot;firefox -new-tab ./docs/index.html -foreground&quot;,<br>&quot;docs&quot;: &quot;npx documentjs &amp;&amp; rm -rf docs &amp;&amp; mv ../docs . &amp;&amp; npm run docs-show&quot;</pre><p>It is not nice that the default behavior is for it to put the docs outside our project folder. It might be that the idea is that documentjs should be run from inside /src, but my effort to try it that way was not easily successful.</p><p>As with the others, we add to our .gitignore:</p><pre>/docs</pre><h4>Pros:</h4><ul><li>Simple setup &amp; configuration.</li></ul><h4>Cons:</h4><ul><li>Bad JSDoc support.</li><li>Theme customization seems possible, but no ready ready made alternative themes to be found.</li><li>Not a very generic default design.</li><li>Site structure is very split up.</li><li>No search.</li><li>No mermaid support.</li><li>Very low usage/popularity.</li></ul><h3>EsDoc</h3><p><strong>Docs</strong>: <a href="https://esdoc.org/">https://esdoc.org/</a><br><strong>Repository</strong>: <a href="https://github.com/esdoc/esdoc">https://github.com/esdoc/esdoc</a><br><strong>npm package</strong>: <a href="https://www.npmjs.com/package/esdoc">https://www.npmjs.com/package/esdoc</a><br><strong>GitHub stars</strong>: 2.6k<br><strong>npm downloads</strong>: 65k</p><p>EsDoc has an extended feature set compared to the others, in that it parses all code and not just the doc strings. It will try to produce some documentation for all your constructs, regardless of doc strings (but of course much better documentation for identifiers with good doc strings). It is then also able to produce documentation coverage data.</p><p>The minimum set of dependencies are these 2:</p><p>npm i -D esdoc esdoc-standard-plugin</p><p>Some additional plugins can be nice to add:</p><p>npm i -D esdoc-ecmascript-proposal-plugin esdoc-brand-plugin esdoc-undocumented-identifier-plugin</p><p>Then we need a configuration file .esdoc.json:</p><pre>{<br>  &quot;source&quot;: &quot;./src&quot;,<br>  &quot;destination&quot;: &quot;./docs&quot;,<br>  &quot;plugins&quot;: [<br>    { &quot;name&quot;: &quot;esdoc-standard-plugin&quot; },<br>    {<br>      &quot;name&quot;: &quot;esdoc-ecmascript-proposal-plugin&quot;,<br>      &quot;option&quot;: { &quot;all&quot;: true }<br>    },<br>    {<br>      &quot;name&quot;: &quot;esdoc-brand-plugin&quot;,<br>      &quot;option&quot;: {<br>        &quot;title&quot;: &quot;Comparator UI&quot;,<br>        &quot;description&quot;: &quot;The app for the testcase comparator feature&quot;,<br>        &quot;repository&quot;: &quot;https://github.com/foo/bar&quot;,<br>        &quot;site&quot;: &quot;http://my-library.org&quot;,<br>        &quot;image&quot;: &quot;http://my-library.org/logo.png&quot;<br>      }<br>    },<br>    {<br>      &quot;name&quot;: &quot;esdoc-undocumented-identifier-plugin&quot;,<br>      &quot;option&quot;: { &quot;enable&quot;: true }<br>    }<br>  ]<br>}</pre><p>If you want the minimal configuration, just remove all plugins except esdoc-standard-plugin.</p><p>Lines to add in package.json -&gt; &quot;scripts&quot;:</p><pre>&quot;docs-show&quot;: &quot;firefox -new-tab ./docs/index.html -foreground&quot;,<br>&quot;docs&quot;: &quot;npx esdoc &amp;&amp; npm docs-show&quot;</pre><h4>Pros:</h4><ul><li>Great way for configuration, and nice plugin system.</li><li>Might be the solution you want if you rather go for automatic parsing for everything and skip manual doc strings.</li></ul><h4>Cons:</h4><ul><li>Bad default scoping / No module scopes.</li><li>Last commit: Spring of 2018.</li><li>Even with esdoc-ecmascript-proposal-plugin it errored a lot parsing my code.</li></ul><h3>EsDoc2</h3><p>There’s also a separate library that is a sort of community version of EsDoc. It is very similar to EsDoc, perhaps a bit more modern and maintained, but my experience was <strong>not</strong> any better than EsDoc.</p><p><strong>Docs</strong>: <a href="http://esdoc2.org/">http://esdoc2.org/</a><br><strong>Repository</strong>: <a href="https://github.com/esdoc2/esdoc2">https://github.com/esdoc2/esdoc2</a><br><strong>npm package</strong>: <a href="https://www.npmjs.com/package/esdoc2">https://www.npmjs.com/package/esdoc2</a><br><strong>GitHub stars</strong>: 30<br><strong>npm downloads</strong>: 14k</p><h3>Conclusion</h3><blockquote>JSDoc with docdash is the winner.</blockquote><p><strong>JSDoc with docdash</strong> is the winner. But given a slightly changed set of requirements, or depending on personal taste, one could favor <strong>docusaurus v2 </strong>or <strong>docsify</strong>, because they are not far behind and you can customize a great lot. I also liked <strong>documentation.js</strong> because of it being clean &amp; minimalistic.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=86b86be9b28d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A JavaScript Pattern Progression — From OOP to Functional Style (FP)]]></title>
            <link>https://realworldjs.medium.com/a-javascript-pattern-progression-from-oop-to-functional-style-fp-79b5717e9345?source=rss-a4c3a2bd191f------2</link>
            <guid isPermaLink="false">https://medium.com/p/79b5717e9345</guid>
            <category><![CDATA[object-oriented]]></category>
            <category><![CDATA[patterns]]></category>
            <category><![CDATA[factory]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[functional-programming]]></category>
            <dc:creator><![CDATA[Esbjörn Blomquist]]></dc:creator>
            <pubDate>Sun, 22 Dec 2019 16:34:44 GMT</pubDate>
            <atom:updated>2020-06-17T18:32:50.374Z</atom:updated>
            <content:encoded><![CDATA[<h3>From OOP to Functional Style (FP) — A JavaScript Pattern Progression</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3zQ_FD8uX4bVN1IR80IIMA.jpeg" /><figcaption>Mushrooms</figcaption></figure><p>JavaScript is under the hood a rather different language than many other common programming languages, but it is perhaps not obvious at a first glance. With roots in the Lisp-like language Scheme — <strong>functions</strong> stand in the very center of how JavaScript operates. The function is in JS what is called a <em>“first-rate citizen”</em>, which means it can be assigned, returned and passed around like any other value.</p><blockquote>All functions has always been “lambda functions” in JavaScript.</blockquote><p>With the upgrades of the language that started in 2015, with ES6 and succeeding versions, the <strong>class</strong> syntax was added. Since it took some time for all JS engines to implement native support for the class syntax, such code could simply be <em>transpiled</em> into old ES5 JavaScript — because the language already had the <strong>constructor</strong> pattern. Some argued that adding the class syntax was bad rather than good because it would only widen the gap between programmers and the actual language.</p><p>Classes was added because <strong>OOP</strong>, <em>Object Oriented Programming</em>, still is the predominant programming paradigm. With its 3 pillars — <em>inheritance</em>, <em>encapsulation</em> and <em>polymorphism</em> — one could divide and conquer every system or problem, it seemed. But OOP has big intrinsic issues and has gotten more and more criticized lately, where at the same time there has been a noticeable swing towards <em>functional programming, </em><strong>FP</strong>. But how do we <em>transition</em> from thinking object oriented into thinking pure functions, immutability and separation of functionality &amp; data?</p><p><strong>In this article I will evolve a simple class with both private, public, and read-only variables (OOP), through a few other object patterns and finally over to the world of functional programming — with pure functions and immutability. This is a JavaScript guide, but also a much more general guide for understanding how OOP and FP relates to each other and how to transition our thinking — and JavaScript will be the perfect vehicle to show such a transition, since it now has the class syntax <em>and</em> is great for FP.</strong></p><p>For every programming pattern shown, between OOP and FP, we’ll discuss the differences to the previous ones and relate it to a few important programming/developmental measurements (sometimes called “non-functional requirements”):</p><ul><li><strong>Reuseability</strong>: How easy it is to keep things <a href="https://en.wikipedia.org/wiki/Don%27t_repeat_yourself"><em>DRY</em></a> and generic, in order to reuse good functionality.</li><li><strong>Extendability</strong>: How easy it is to add functionality to the code.</li><li><strong>Testability</strong>: How easy it is to write tests for the code.</li></ul><p>One of the most common examples to use when teaching patterns or frameworks in the realm of the web is the “TODO app”. However, I want to use something that is more general, has some computational parts and a simple data model including read-only members as well as writable.</p><h3>Circle Objects</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qcGj0fZsi1gQH-IBPnfJpw.jpeg" /><figcaption>Big metal cylinder in the woods</figcaption></figure><p>Let’s imagine that we want to handle round 2D objects that we call <em>Circles</em>. Let’s define a couple of properties and operations that fit the concept of such objects:</p><ul><li><strong>r</strong>: Radius of the circle. This can never be changed (because then it is not the same circle anymore!).</li><li><strong>pos</strong>: Position in a 2D world — an array with 2 elements/coordinates. Freely changeable.</li><li><strong>hits</strong>: How many times this circle has been calculated to intersect another circle. This is internal state, not freely changeable.</li><li><strong>area()</strong>: Get the area of a circle.</li><li><strong>intersect()</strong>: Calculate if a circle intersects another, and update both hits if they do.</li></ul><h3>Class</h3><p>We start in OOP land by implementing this circle concept as a class:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5149144e20d41afb24e2d8514dcf3a6b/href">https://medium.com/media/5149144e20d41afb24e2d8514dcf3a6b/href</a></iframe><p>First, in the constructor, we need to transfer the incoming arguments over to the class variables using <strong>this</strong>. Since we want to control the access of the different members in the class, we can use so called <strong>getters</strong> and <strong>setters</strong>. The <strong>intersect</strong> method is the most intricate one where a distance is calculated, compared to circle radii and then the <strong>hits</strong> of the two objects are increased.</p><p>Now, we need some test that uses the above class, and see if everything we hoped for holds true:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0d72c4d9d6e1d36e71eabfac05e49b19/href">https://medium.com/media/0d72c4d9d6e1d36e71eabfac05e49b19/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*40XYAYuasdu6poru6-Yo4Q.png" /><figcaption>The 2 circles in the example</figcaption></figure><p>It seems to work as intended. Trying to set hits or r will throw errors. Thus we have contained and protected the data inside the objects created through this class so that unintended behaviors are avoided in surrounding code.</p><p>What can be said about the class pattern?</p><blockquote>The <em>best</em> way to work with classes is to recognize the better alternatives and use those instead, like objects or factories.</blockquote><ul><li><strong>Reuseability</strong>: The whole class can be used in different contexts, if it perfectly fits the purpose. The reuseability will mainly be determined by how generic of a component we made as a class. If the class is not generic and versatile, the reuseability is very limited. If there are interesting general functionality inside our class, that is not easily reused either. For instance, to reuse the mathematical function of calculating the area of a circle without having to create a class instance, we would have to <strong>import the whole Circle</strong> and then do: Circle.prototype.area.bind({ r: 4 })() Not nice.</li><li><strong>Extendability</strong>: One common way of course is to grow the class. This might break the rule of <a href="https://en.wikipedia.org/wiki/Single_responsibility_principle"><strong>doing only one thing</strong></a>. It will almost by definition worsen the previous point above, but also the next way that a class can be extended: by inheritance. When inheriting you can’t pick and choose, so large non-generic classes are very clumsy to work with. With <a href="https://medium.com/@brianwill/object-oriented-programming-a-personal-disaster-1b044c2383ab">class hierarchies</a> we also risk ending up in the <a href="https://medium.com/@cscalfani/goodbye-object-oriented-programming-a59cda4c0e53"><strong>banana-jungle problem</strong></a>. It has also been recognized that it’s a <strong>bad practice</strong> in JavaScript to directly <strong>export a class</strong> from a module, since it limits how the module can evolve and be updated/refactored (the factory pattern is much better). More on this later.</li><li><strong>Testability</strong>: Testing can be done by instantiating the class, running its methods, and trying to check the effects. This can turn out to be a bit tricky in cases of large classes or classes including communication or other outside dependencies. We could be forced to change the internals of the class only to be able to mock dependencies or reach inside to check tested effects.</li></ul><p>The <em>second</em> <em>best</em> way to work with classes is to try to <a href="https://medium.com/javascript-scene/3-different-kinds-of-prototypal-inheritance-es6-edition-32d777fa16c9"><em>only</em> work with <strong>composition</strong></a> and to try to <a href="https://medium.com/@PurpleGreenLemon/we-need-to-talk-about-composition-patterns-patterns-in-object-oriented-javascript-bcbeb770f806">keep as much code as possible outside classes</a> — all functions should reference (pure) functions outside the class. The <em>best</em> way to work with classes is to <a href="https://medium.com/better-programming/fp-toy-7f52ea0a947e">recognize the better alternatives</a> and use those instead, like objects or factories.</p><h3>Constructor</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AONS0d_g6pBcNWpQEb_7Ng.jpeg" /><figcaption>Red submarine</figcaption></figure><p>In JavaScript, we have already had the ability to create objects with the new keyword, just like with classes, even before the introduction of the <em>class</em> syntax.</p><p>This is how the Circle class could look using the <em>constructor</em> pattern:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a7d3115b990c13bf8184c580c8b45a11/href">https://medium.com/media/a7d3115b990c13bf8184c580c8b45a11/href</a></iframe><p>But now you say:</p><p><em>That is not correspondent to the class example! We need to use the prototype, and we could still use getters and setters!</em></p><p>Yes, but this guide is about patterns and a direction, and each version will not always equal the other. The main reason to even include the constructor pattern is that it is an interesting bridge to the factory.</p><p><strong>The constructor is just a function</strong> — where inside, you could attach values and methods to this. this is the function object that gets instantiated when you call it with the new keyword. By simply keeping private variables (let or const) in the function scope, we easily create and handle private unexposed constants and states, and we can do so because of JavaScript’s <em>closure</em> (not in the scope of this article). By creating our own getters and setters as methods, we expose an <strong>API</strong> that will define what’s private, read-only, writable etc.</p><p>The small difference in the usage of objects created with this constructor, compared to the class, is that we will have to call our API functions instead of directly accessing and setting properties:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e4971287224512e801c684a0bb6d51f7/href">https://medium.com/media/e4971287224512e801c684a0bb6d51f7/href</a></iframe><p>Because of that the new class syntax has gotten extra features, this old equivalent pattern does not give the exact same API of using the instantiated objects. But it is much closer to the core language, and it is an interesting demonstration of how closure works in JavaScript. The difference regarding our developmental measurements is not that significant, but there might be some comments worth giving:</p><ul><li><strong>Reuseability</strong>: Our code is still ensnared inside a construct, a function body, but it is perhaps a bit more apparent that just attaching arrow functions to properties of an object <em>opens up the possibility</em> of using external generic functions to define the guts of the object constructor. If we would lift out interesting parts of the code into reusable generic utilities (namely think more in line with functional programming), we would get a higher score here. It is of course possible to do this in the class pattern as well, but the class syntax somewhat hides rather than highlights this.</li><li><strong>Extendability</strong>: We are still forcing external code to use new which blocks patching in certain updates or refactoring our module and instead making such changes breaking.</li><li><strong>Testability</strong>: Not essentially different from the class pattern, although adding testing purpose adaptations inside the module might look different.</li></ul><p>So, looking at the fact that what the constructor is doing is just tie functions and values to its own properties, through this — what if we replace this with just another object?</p><h3>Factory</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*moItabp3elTyvWcCAemlNA.jpeg" /><figcaption>Factory buildings on a waterfall</figcaption></figure><p>Below is one way to make our circle objects with a factory.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/dfe939d06a1ddad2bbbcff849cfc7f64/href">https://medium.com/media/dfe939d06a1ddad2bbbcff849cfc7f64/href</a></iframe><p>The first thing to notice here is that this is <strong>just a function</strong>, not any class, constructor, interface or other “object-descriptive” abstract construct (indicated by the lowercase first letter of <strong>makeCirle</strong>). The function, when called, will simply create a regular object with a set of properties (const obj = {...}) and return it. We are still using closure to keep hits &amp; r private. To clarify: new could not and should not be used when using a factory.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f41022a7b14967a4241dc0f5373787b4/href">https://medium.com/media/f41022a7b14967a4241dc0f5373787b4/href</a></iframe><p>Factories in JavaScript can sometimes take another object to be set as the new object’s prototype (using Object.create), called <em>prototypal inheritance</em>. But regarding trying to use the prototype as much as possible, like that or using classes, the factual penalty of creating new objects with own properties is getting smaller and smaller with increased device performance and more optimized JS engines. It is indeed nice that it is nowadays recommended to <strong>simply create a basic object every time we need one</strong>, and optimize later should you actually find your object creation being a bottle-neck. This way we can actually skip using prototypal inheritance, or any prototype juggling for that matter. It is good to know about it, to read and work on others code, but we <em>can</em> build great JavaScript software without ever having to take any prototype into account explicitly.</p><ul><li><strong>Reuseability</strong>: We explicitly use JavaScript’s <em>closure</em> instead of implicit this which even more opens up for defining and building objects in our factory using external reused code. More on this below (pun intended). But we are still not doing this yet, so our potentially generic code is still trapped.</li><li><strong>Extendability</strong>: The major difference here is getting rid of new for callers. This allows us to create and return things more freely. Examples would be the possibility of keeping objects in some kind of pool or cache. Or to return a tuple/pair (array) with not only the object but also perhaps a callback or any other related construct or value (compare for example with the React hook useState). On that note, we could consider returning an <a href="https://www.npmjs.com/package/tri-fp"><em>error-first pair</em></a> if the object creation could go wrong. We also no longer pretend to give any type guarantee, helping surrounding code avoid the use of any unreliable type checking, like the “broken” instanceof. As we inside the factory simply add more and more properties to an object, there would be nothing stopping us from continuing to attach functionality to the object <em>after</em> we have returned it from the factory. This idea would point in the direction of <a href="https://medium.com/javascript-scene/functional-mixins-composing-software-ffb66d5e731c"><em>functional mixins</em></a> which is a powerful higher order pattern, but a subject outside the scope of this article. A more straightforward general approach is again to work with <em>composition</em> (when something is made up of other parts, like in React), and also — since we should strive to mainly use <em>pure functions</em> — <em>functional composition</em> (e.g. using compose in <a href="https://ramdajs.com/">Ramda</a>).</li><li><strong>Testability</strong>: A rather significant difference has again to do with unlocking the shackle we were chained with through new. If we need to provide something extra behind the scenes other than the actual object, for testing purposes — in a factory we are free to do such things.</li></ul><p><strong>A thing worth expressing explicitly is that we no longer need the keyword </strong><strong>this in the factory pattern. The workings of that keyword can be rather confusing in JavaScript at times and therefore a source of bugs. It is actually a good rule to never use </strong><strong>this, it will help in moving over to the functional paradigm. Removing </strong><strong>this will namely also remove classes, constructors, binding, and juggling around different </strong><strong>this in some </strong><strong>that or </strong><strong>self as seen here and there.</strong></p><h3>Functional Style</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wHA_VYE57usUCseizkL6kg.jpeg" /><figcaption>A very blue bedroom</figcaption></figure><p>It is a really good general idea in programming to always <strong>start with the simplest implementation first and move to more complex patterns only as needed</strong>. This means <em>pure functions</em> as the first approach, and a class would actually be the last resort (if you really ever need one).</p><p><strong>If you’re new to the concept of pure functions, they are basically defined by (1) having no side effects and (2) their return value only depends on the given input arguments.</strong></p><p>Using mainly pure functions leads to the separation of <em>operations</em> and <em>data</em> — the perhaps most apparent structural aspect of Functional Programming that differs heavily from Object Oriented Programming where those 2 are tightly coupled.</p><p>Another consequence of pure functions is that we will not be mutating any data — everything in FP land is going to be <em>immutable </em>(at least treated as). (There are exceptions, but being firm with this rule in the beginning is going to help in shifting our way of thinking into functional style, and reap the benefits).</p><p><strong>Armed with</strong> the concept and understanding of <strong>pure functions</strong>, let’s start over and try to code our Circle objects again from scratch. We first write a pair of helpers for doing immutable updates followed by our circle computations — all pure:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/12dc2333ecf2a0f9b97ef32b2f7662ac/href">https://medium.com/media/12dc2333ecf2a0f9b97ef32b2f7662ac/href</a></iframe><p><strong>Since this looks so different from the previous patterns — some general comments about functional style:</strong></p><ul><li>As a general rule, we <em>separate computations from data</em>.</li><li>Instead of functions most often being bound inside objects, we make <em>sets of self standing functions</em> that can operate on different objects or data.</li><li>The functions <em>do not mutate any data or have any other side effects</em> (1st rule of pure functions).</li><li>The functions don’t have any outside scope or context, but instead <em>operate only on the incoming arguments</em> (2nd rule of pure functions).</li><li>Since we want our data to get updated in certain ways, though being treated as immutable, we include in our set of pure functions a couple of helpers for making those updates, using ES6 <em>spread operator</em> (incHits &amp; setPos above).</li><li>Always using <em>arrow functions</em> can be a good habit since all simple functions then become more <em>declarative</em> (no imperative body) and it also makes it easier to refactor a function to <em>point-free style</em> (e.g. made through composition).</li><li><a href="https://medium.com/@esbblo/safer-code-with-es6-destructuring-explained-in-one-example-a5d6910d7dce">ES6 <em>destructuring</em></a> provides a way to make a form of pattern matching on the incoming argument(s), unpacking only exactly what we need.</li></ul><p>Notice how our intersect function now returns new updated copies of the incoming objects.</p><p>Using the above code directly in practice means holding and managing the data, since that is now outside of the above functionality. And so far we don’t have any way of enforcing immutability, so mutating our circles is unfortunately possible (c1.hits = 4; below). But if we by convention (or by some immutability enforcement, discussed later) <strong>never mutate</strong> our state/circles then shared state will not mutate(!), demonstrated by the c2ref below.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/36220cf3bf0644c0c7d21e19b08aa231/href">https://medium.com/media/36220cf3bf0644c0c7d21e19b08aa231/href</a></iframe><p>The state, our circles, are just <em>serializable</em> objects — nothing fancy, just <em>pure data</em>. And they need to be replaced by new <em>updated clones</em> at every step that should alter any state. If we store and use a reference to a state, it will be the state at the point in time when it was taken as a reference, that object will never change. This means that we have eliminated shared state mutation, which is a good thing.</p><p>But what the heck is this kind of syntax: [hit, c1, c2] = intersect(c1, c2);? — It is just <em>destructuring</em> again but for an array and into existing variables created with let. We are just matching the output of intersect and directly using it in assignments.</p><ul><li><strong>Reuseability</strong>: We are now in a completely new world regarding this. We can easily see that area() and circlesIntersect() are so general we could probably find them in a common library instead of defining them ourselves. Otherwise we now have the start of our own general geometry module, to use in any future project that needs to handle circular objects (game engine?).</li><li><strong>Extendability</strong>: Extending our code is now simply a matter of importing precisely the functions we need and use them in any library, class, factory, object, prototype or any other construct. If we have tree-shaking in our module/build system, we won’t even get the functions we don’t import into our final code.</li><li><strong>Testability</strong>: There is basically nothing more simple to test than pure functions. Depending on what you give the function, it returns something based on that. With no side effects, we won’t have any problem examining any result of calling such functions, and we don’t have to mock anything.</li></ul><h3>Functional Style Factory</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MRJPZBuNjEf9UlVuMVtpuQ.jpeg" /><figcaption>A view near the sea</figcaption></figure><p>I have been repeating in the previous patterns that functions and calculation should be extracted out into generic utilities, striving to make our code in general more reusable, <em>DRY</em> and testable. Well, now we come from the <em>complete opposite direction</em> and could instead easily wrap the keeping of a state together with the use of our pure functions from above, into a <em>factory</em>:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6f463f4f93197c021ca6a1da6f19a981/href">https://medium.com/media/6f463f4f93197c021ca6a1da6f19a981/href</a></iframe><p>We have kind of gone <strong>full circle</strong> now, haven’t we? We have a factory which only job is to be stateful (keep a state over time), and otherwise “tunnel” calls to external utilities. Using this factory is almost exactly the same as with the previous factory pattern above, so I won’t repeat that code (the only difference is c1.getState().hits instead of c1.getHits() although we could of course make a <em>getHits</em> function in this factory as well).</p><p>Regarding <em>reuseability</em>, <em>extendability</em> and <em>testability</em> — this factory has all the benefits of the previous factory example together with some of the benefits of the above functional style pattern.</p><p>What can be noticed however is that we introduce some lines of logic due to the nature of intersect, namely that such operation might not be at the right level here — it needs to affect multiple circles. Could we find a more powerful way to handle state, as a collection?</p><p>It’s common in JavaScript that mutations are avoided by convention, using certain patterns (like ES6 spread), or some of the very many libraries, where some interesting examples are:</p><ul><li><a href="https://redux.js.org/">Redux</a></li><li><a href="https://xstate.js.org/docs/">XState</a></li><li><a href="https://ramdajs.com/">Ramda</a></li><li><a href="https://github.com/lodash/lodash/wiki/FP-Guide">Lodash/fp</a></li><li><a href="https://github.com/kolodny/immutability-helper">immutability-helper</a></li><li><a href="https://github.com/guigrpa/timm">timm</a></li></ul><p>There are however ways to block mutation of state, where perhaps most notably <a href="https://immerjs.github.io/immer/docs/introduction">Immer</a> is a good example. A much simpler one is <a href="https://github.com/aearly/icepick">Icepick</a>. It is still more common for immutability to be maintained by convention with structural patterns and with the help of linting (static code analysis).</p><p>Since I don’t want to mix in and favor any library in this guide , I would instead like to show you that <strong>we can stay in native JavaScript and pretty easily build a tiny bit of code to get a Redux-like immutable state handler</strong>. This below state manager is however not a suggested piece of code to use in a project. <strong>You should evaluate some of the libraries above </strong>or any other state management package with an immutable style and use that. (My personal favourite is <em>Ramda</em>, in combination with Redux or XState for bigger applications.)</p><p>With that said — let’s see how a small piece of native JavaScript can combine <em>enforced immutability</em> and a tiny <em>Redux-like</em> state handler. This will give us a <em>store</em> that updates by <em>dispatching actions</em> through a <em>reducer</em>.</p><h3>Functional Style with Immutable Store</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gudJiLKgMsKgpKitjtNtUQ.jpeg" /><figcaption>Lots of people on a small boat</figcaption></figure><p>First we make use of the Object.freeze method and write a helper for freezing (making immutable) complex data structures, deepFreeze. Then we also define a super-simple Redux-like store creator, createStore:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4897701b79bb8bab7c3b9e2eabc7bc8f/href">https://medium.com/media/4897701b79bb8bab7c3b9e2eabc7bc8f/href</a></iframe><p>deepFreeze is a recursive function where if the incoming data is a non-primitive that is not already frozen, we deepFreeze it. Our createStore function takes an initialState and a so called reducer that can, given a state, return a new altered state according to <strong>“actions”</strong>. createStore then returns a way to dispatch actions (send action objects to our reducer) and a getState to, at any point in time, get hold of our current state (which can not be mutated due to it being frozen).</p><p>An interesting reflection on createStore is that it is actually very similar to our “Functional Style Factory” wrapper function above, but you could call this one a generalized factory wrapper. They both keep a state locally and privately, and they both return an object with methods both for retrieving state and for making state updates. <strong>Even without </strong><strong>deepFreeze </strong>— <strong>using only </strong><strong>dispatch to alter state ensures immutability</strong>.</p><p>The reducer we need for our circles is something like this (using again our previous update helpers setPos and incHits):</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/75665f3ff295b67da3ef526a0739ebed/href">https://medium.com/media/75665f3ff295b67da3ef526a0739ebed/href</a></iframe><p>An <strong>action</strong> is an object with a type that matches a defined one, and arguments in some way that fits each action (a common convention is to always use payload, but I’m free-styling a bit above). Yes, I know, usually switch statements are used in reducers, but I have a stupid personal dislike to them and often prefer alternative patterns, for example the strategy pattern.</p><p>Now we can use the above 3 new functions in combination, in order to get our <strong>immutable circles example</strong>:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/36d12bf67e22f1806ca72720c087bccb/href">https://medium.com/media/36d12bf67e22f1806ca72720c087bccb/href</a></iframe><p>With our reducer and an initialState, createStore gives us getState that we call whenever we want to <em>use</em> parts of our state, and dispatch that we call whenever we want to <em>change</em> our state. With our built in deepFreeze we block any direct attempt to mutate our state.</p><p>On the <em>usage side</em> of a pattern like this we haven’t reduced the lines of code, rather the opposite. <strong>But this kind of pattern is meant instead to keep things streamlined and <em>less error prone as projects grow</em></strong>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=79b5717e9345" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Safer Code with ES6 Destructuring — Explained in One Example]]></title>
            <link>https://realworldjs.medium.com/safer-code-with-es6-destructuring-explained-in-one-example-a5d6910d7dce?source=rss-a4c3a2bd191f------2</link>
            <guid isPermaLink="false">https://medium.com/p/a5d6910d7dce</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[safe-code]]></category>
            <category><![CDATA[example]]></category>
            <category><![CDATA[es6]]></category>
            <category><![CDATA[destructuring]]></category>
            <dc:creator><![CDATA[Esbjörn Blomquist]]></dc:creator>
            <pubDate>Wed, 30 Oct 2019 13:19:28 GMT</pubDate>
            <atom:updated>2020-11-05T08:35:38.772Z</atom:updated>
            <content:encoded><![CDATA[<h3>Safer Code with ES6 Destructuring — Explained in One Example</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VWrh8Jq72395R7negPwJdA.jpeg" /></figure><pre>Uncaught TypeError: Cannot read property ‘x’ of undefined</pre><p>Recognize this? Seen this before? It is perhaps the <em>most</em> common error in Javascript.</p><h3>Error prone dynamic data</h3><p>We often deal with dynamic data in complex structures in all web applications (browser + node.js) which, when we try to use that data, might produce unexpected behaviors and errors.</p><p>Let’s look at a small example where we have a collection items (key indexed) of objects with certain properties. We need to <strong>get hold of an item&#39;s parent, and some properties from that parent item</strong>. It could look like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7f9d97b3eaed2b006f2a5b098175c922/href">https://medium.com/media/7f9d97b3eaed2b006f2a5b098175c922/href</a></iframe><p>But this is a <strong>whole bunch of delicious baits</strong> for the unforgiving X-of-undefined-creature. It <em>will</em> jump out, attack you from the side, and bite you — hard!</p><p>The problem is that we expect item to have a parent <em>and</em> that this parent id exists in items <em>and</em> that the parent item has <em>both</em> types and name defined. types might also cause problems further ahead if it is assumed to be an array.</p><h3>Fallback default values to the rescue?</h3><p>We have to insert multiple fallback default values, perhaps like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b45254630c472a2bac5c324e735267ba/href">https://medium.com/media/b45254630c472a2bac5c324e735267ba/href</a></iframe><p>Ok, so we can feel rather safe now perhaps? But it looks a bit messy and unstructured, doesn’t it?</p><h3>ES6 Destructuring</h3><p>Let’s start over completely and try the amazing <em>ES6 Destructuring</em> syntax:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/cf4c96cc0947f9b17f89ae7b00f0e803/href">https://medium.com/media/cf4c96cc0947f9b17f89ae7b00f0e803/href</a></iframe><p>We first destructure item and also rename its parent property to parentId (because we can, otherwise it would automatically get the nameparent).</p><p>Then we find the parent in items by destructuring that whole collection, and at the same time we also destructure the parent to reach into it and get both types and name, with fallback defaults.</p><h3>Conclusion</h3><h4>If we…</h4><p><strong>Use destructuring as much as possible</strong>:</p><ul><li>Whenever we need something from within an object or array</li><li>Use eslint to get warnings and help</li></ul><p><strong>Try to always think about default values in our destructurings</strong>:</p><ul><li>Much in the same way that we are used to with function arguments</li></ul><p>…we might then be able to better shield ourselves against X-of-undefined errors.</p><p>A big bonus: <strong><em>Half the code size!</em></strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a5d6910d7dce" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How Promise.race Solved a Problem In Our Async CI Testing]]></title>
            <link>https://realworldjs.medium.com/how-promise-race-solved-a-problem-in-our-async-ci-testing-366e427447b7?source=rss-a4c3a2bd191f------2</link>
            <guid isPermaLink="false">https://medium.com/p/366e427447b7</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[async]]></category>
            <category><![CDATA[promises]]></category>
            <category><![CDATA[race]]></category>
            <category><![CDATA[testing]]></category>
            <dc:creator><![CDATA[Esbjörn Blomquist]]></dc:creator>
            <pubDate>Wed, 30 Oct 2019 11:15:48 GMT</pubDate>
            <atom:updated>2021-11-07T10:04:44.216Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kYAwWHdp_YqliFm_Tm_lfg.jpeg" /></figure><p>Javascript is really a great language when it comes to <strong>async</strong> programming. But it is not always a walk in the park to <strong>test</strong> async code.</p><p>It is a good idea in <strong>unit testing</strong> to try to test at the <strong>highest possible level </strong>— focusing on testing of the module’s API from an outside/usage perspective. That way, we ensure that it does <strong>what</strong> it should, but we don’t care exactly <em>how </em>— making <strong>refactoring</strong> of the module almost zero work when it comes to updating tests. However, this often increases the amount of async testing.</p><p>In cases where the calls to test are <em>straightforward promises</em>, you await those and test on the result. But this is not always the case. For instance when callbacks have to be used, like when <strong>subscribing</strong> to a message bus, there is no promise to await.</p><h3>A first try — with dummy delay</h3><p>A common pattern in those cases is to have an arbitrary delay after the tested call. In Javascript we can define the simple wait/delay function first, as a handy utility:</p><pre>const wait = (ms) =&gt; new Promise((r) =&gt; setTimeout(r, ms));</pre><p>And then use that to “make sure” we got the published message:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/12df0cbb6feb8710a082a12e890fc1bf/href">https://medium.com/media/12df0cbb6feb8710a082a12e890fc1bf/href</a></iframe><p>This trivial approach has a couple of problems though:</p><ul><li>It causes the testing to take <em>way longer</em> than necessary (imagine that hundreds of similar tests are run).</li><li>It makes assumptions about the performance and scheduling in the environment where the tests are run, making it possible for tests to <em>actually fail</em> when they shouldn’t in cases of unfortunate scheduling and delays in the execution.</li></ul><h3>Second try —a triggerPromise</h3><p>To solve this, we create a utility function that we can call triggerPromise:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f141eee63f4b25916fab4d9ec37671a8/href">https://medium.com/media/f141eee63f4b25916fab4d9ec37671a8/href</a></iframe><p>The utility function returns a new Promise along with the resolve function for that promise. Let&#39;s use it and see how it does away with the long arbitrary wait in our test:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4acb91f1dda4ab65b51700fe47fb2886/href">https://medium.com/media/4acb91f1dda4ab65b51700fe47fb2886/href</a></iframe><p>We are now effectively signaling at the precise time when we have received the message, along with <em>awaiting </em>that signal, instead of guessing and overestimating.</p><h3>Wrapping it all up with a race against a timeout</h3><p>However, if the tested module has some error in this async functionality, then we <em>don’t want to get stuck and wait forever</em> because it would not work well with CI. So the next desired utility would be something like “await this thing but with a timeout”. Since there is a sibling to the much more used Promise.all, namely <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/race">Promise.race</a>, we could utilize that like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/eda2a5d199cc88600a3ae137e39d0e6b/href">https://medium.com/media/eda2a5d199cc88600a3ae137e39d0e6b/href</a></iframe><p>So now, instead of only doing await promise in our tests, we use await asyncWithTimeout(promise), and <em>voila — </em>no more stalled CI because of newly introduced bugs in our async behaviours!</p><p>Oh yes, we need to have an example of this in use, <em>completing</em> our small async test:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6a01d9d050781265878fea9c0f191f40/href">https://medium.com/media/6a01d9d050781265878fea9c0f191f40/href</a></iframe><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=366e427447b7" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>