<?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 Paweł Puzio on Medium]]></title>
        <description><![CDATA[Stories by Paweł Puzio on Medium]]></description>
        <link>https://medium.com/@ppuzio?source=rss-def01e3503c4------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*Izxg5jtJd9z9-YHlat4Kqg.jpeg</url>
            <title>Stories by Paweł Puzio on Medium</title>
            <link>https://medium.com/@ppuzio?source=rss-def01e3503c4------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 01 Dec 2026 21:58:34 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@ppuzio/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[The Self-Improving Assistant: How Kaizen Principles Transform AI Interactions]]></title>
            <link>https://ppuzio.medium.com/the-self-improving-assistant-how-kaizen-principles-transform-ai-interactions-f6275af94f31?source=rss-def01e3503c4------2</link>
            <guid isPermaLink="false">https://medium.com/p/f6275af94f31</guid>
            <category><![CDATA[kaizen]]></category>
            <category><![CDATA[productivity]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[prompt-engineering]]></category>
            <dc:creator><![CDATA[Paweł Puzio]]></dc:creator>
            <pubDate>Tue, 08 Apr 2025 12:05:49 GMT</pubDate>
            <atom:updated>2025-04-08T12:05:49.952Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/420/1*k1QsuncI36bR37lYk_akjg.png" /><figcaption>The Japanese term ‘kaizen’ written in kanji characters. Source: Wikipedia</figcaption></figure><p>There’s a sentence that resonates with me: <strong>“Love the process, not the result.”</strong> I think it’s especially important for personal projects, hobbies, and other long-term activities that don’t have a well-defined endpoint. If you pick up running, for example, you might initially view it through the lens of beating personal records. But as time passes, progress inevitably slows down, achieving new milestones becomes more difficult, and that can lead to frustration and ultimately make you quit.</p><p>But what if you switch your focus to continuous improvement instead? What if you concentrate on finding new ways to enhance your skills, simply enjoying the process of dedicating yourself to something, <strong>and becoming the person who runs/learns languages/writes novels?</strong></p><p>This focus on the process itself forms the foundation of <strong>Kaizen</strong>, a Japanese business philosophy. Originally introduced to improve quality management in production environments, many Kaizen principles can be applied beyond this narrow context — focusing on eliminating waste, self-organizing, maintaining discipline. These concepts can transform our approach to household chores, hobbies, interactions with people, and even our use of technology.</p><h3>Applying Kaizen to LLM Interactions</h3><p>One of the biggest game-changers when working with Large Language Models (<strong>LLMs</strong>) like ChatGPT, Claude, or tools more closely integrated with specific activities such as Cursor or Windsurf for programming, is communicating your preferences to the model.</p><p>Why does this matter? In my experience, most code suggestions from LLMs default to Python, which isn’t helpful if you work in another language (unless you enjoy code porting as an intellectual challenge). Without specifying your requirements, you’ll <em>waste time and computation resources</em> asking the LLM to rewrite examples in your preferred language.</p><p>As a result, most users create or find online templates that follow the 80/20 rule — they eliminate the most common problems but aren’t perfect. Users typically adapt to suboptimal user experiences and develop workarounds — anyone who’s used Meta products can attest to this pattern. I’ve noticed that hastily crafted LLM templates follow this same pattern of compromise. But can we do better? Can we apply Kaizen principles here?</p><h3>Core Kaizen Principles and Their LLM Applications</h3><p>To better understand how Kaizen can transform our LLM interactions, let’s examine several key principles of this philosophy and see how they map to prompt engineering:</p><h3>1. Elimination of Waste (Muda)</h3><p>Kaizen identifies several types of waste that reduce efficiency. In traditional manufacturing, this includes overproduction, waiting time, and unnecessary processing. In the context of LLM interactions, waste appears as:</p><ul><li>Repetitive prompting for the same information (like constantly asking for JavaScript instead of Python)</li><li>Time spent correcting misaligned outputs</li><li>Computational resources used on irrelevant generations</li></ul><p>When I repeatedly asked LLMs to “rewrite this in JavaScript” or “check if this sounds natural,” I was engaging in a form of waste. Each repetition consumed both my time and computational resources.</p><h3>2. Plan-Do-Check-Act (PDCA) Cycle</h3><p>This iterative four-step management approach is central to Kaizen:</p><ul><li><em>Plan</em>: Identify an opportunity and plan for change</li><li><em>Do</em>: Implement the change on a small scale</li><li><em>Check</em>: Evaluate the results and identify learnings</li><li><em>Act</em>: Take action based on what you learned</li></ul><p>In LLM interactions, the <a href="https://www.lean.org/lexicon-terms/pdca/#:~:text=PDCA%20is%20an%20improvement%20cycle,results%2C%20and%20taking%20appropriate%20action."><em>PDCA</em> cycle</a> can be implemented through a structured feedback loop. Instead of merely using the model for one-off tasks, we can establish mechanisms that continuously evaluate and improve our interactions. As I’ll explain later, I’ve implemented a specific prompt technique that allows me to regularly assess our conversation quality and make incremental improvements to my interaction patterns.</p><p>This systematic approach to feedback — asking for specific improvements rather than starting from scratch each time — embodies the <em>PDCA</em> philosophy by creating an ongoing cycle of refinement rather than isolated interactions.</p><h3>3. Standardization</h3><p>Kaizen emphasizes that standardization creates a stable foundation for continuous improvement. Without standards, improvements are disorganized and inconsistent.</p><p>In the context of LLM interactions, standardization means creating consistent templates and interaction patterns. When we develop standardized ways of communicating with models, we establish a baseline that can be systematically refined. This might involve creating template prompts that contain our preferences, technical requirements, and other context that would otherwise need to be repeated in every interaction.</p><h3>4. Small, Incremental Improvements</h3><p>Rather than radical reorganizations, Kaizen focuses on small changes that accumulate over time. This approach reduces resistance to change and allows for continuous adaptation.</p><p>Applied to LLM prompting, this principle suggests that gradually refining our interaction patterns yields better results than completely reinventing our approach with each conversation. By identifying specific areas for improvement and addressing them one by one, we can build increasingly effective communication patterns with AI systems without the overwhelming task of perfecting everything at once.</p><p>Let me share two examples where these Kaizen principles could be applied to streamline LLM usage, and how I ultimately implemented them in my own workflow.</p><h3>Example 1: Algorithmic Problem-Solving</h3><p>At <a href="https://codecomply.ai/"><em>CodeComply.ai</em></a>, we work with spatial algorithms for code compliance software. To sharpen my algorithmic skills, I separately spend time daily solving challenges on LeetCode. Since I don’t always come up with the optimal solution on my first attempt, I enjoy discussing potential improvements with Claude.</p><p>However, I encountered two significant challenges when discussing algorithms with the model:</p><ol><li>The model occasionally suggested solutions with worse time complexity than my original approach — when I asked for help with a specific edge case my logic wasn’t handling, it sometimes introduced code that exceeded time limits.</li><li>The suggested solutions often had little similarities to my original code — the model would essentially provide a memorized solution rather than improving my existing logic, which felt less educational and helpful for my learning process.</li></ol><h3>Example 2: Improving Written Communication</h3><p>Personally, I struggle with transforming my thoughts into polished written form. LLMs made this process much easier, but I discovered that prompt engineering significantly impacts results. When I asked an LLM if my text was grammatically correct, it typically confirmed it was. <br>However, when I asked if the text sounded natural to a native speaker, it would identify and rewrite awkward passages. This <em>repetitive dance</em> of asking two separate questions felt inefficient.</p><h3>The Kaizen Solution</h3><p>Both problems were solved by adding a continuous improvement mechanism to my master prompt:</p><pre>5. Continuous Improvement<br>When I type &quot;IMPROVE PROMPT&quot; or end my message with &quot;??&quot; (double question mark), analyze our interaction and suggest <br>1–2 specific improvements to my preferences that would make your responses more helpful or accurate. Focus on:<br>- Missing technical context that would have improved our exchange<br>- Patterns in my questions that could be better addressed in the preferences<br>- Technical specifications or algorithm preferences that could be more precise<br>- Any recurring themes in our discussions that should be formalized in preferences<br>Limit suggestions to what would be most impactful based on our specific interaction rather than general improvements.</pre><p>Since adding this to my preferences, I’ve been expanding my rule set <strong>almost daily</strong>. I no longer need to repeat the same instructions in every interaction, which allows me to focus on the productive aspects of my work — precisely what LLMs were designed to facilitate from the beginning. The process of improving this article has resulted in a <strong>??</strong> prompt as well, obviously ;)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pfXMQCvefkQ9j_drxAoc8A.png" /><figcaption>Improvements to my master prompt after this article</figcaption></figure><p>By applying Kaizen principles to my LLM interactions, <strong>I’ve created a system of continuous improvement that evolves based on my specific needs and usage patterns</strong>.</p><p>This approach transforms LLMs from useful but sometimes frustrating tools into highly personalized assistants that grow <strong>more aligned with my workflow over time.</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f6275af94f31" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[PostgreSQL’s JSON functionalities as an alternative to NoSQL]]></title>
            <link>https://ppuzio.medium.com/postgresqls-json-functionalities-as-an-alternative-to-nosql-a90c6e9cf6df?source=rss-def01e3503c4------2</link>
            <guid isPermaLink="false">https://medium.com/p/a90c6e9cf6df</guid>
            <category><![CDATA[backend]]></category>
            <category><![CDATA[postgresql]]></category>
            <category><![CDATA[database]]></category>
            <category><![CDATA[json]]></category>
            <category><![CDATA[postgres]]></category>
            <dc:creator><![CDATA[Paweł Puzio]]></dc:creator>
            <pubDate>Fri, 13 Dec 2024 09:20:48 GMT</pubDate>
            <atom:updated>2024-12-15T13:22:40.703Z</atom:updated>
            <content:encoded><![CDATA[<h4>Optimizing GeoJSON processing with built-in JSON operations</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*gGs0Y8Mmid-Z0Jzl" /><figcaption>Photo by <a href="https://unsplash.com/@sxoxm?utm_source=medium&amp;utm_medium=referral">Sven Mieke</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>The Challenge: Efficient GeoJSON Processing at Scale</h3><p>At <a href="https://codecomply.ai/"><em>CodeComply.ai</em></a>, we transform floor plans into actionable data by converting them into GeoJSON features using <a href="https://togal.ai/"><em>Togal.ai</em></a><em>’</em>s processing capabilities. These features enable us to perform dozens of automated checks for fire safety, accessibility, and state-specific statuses.</p><p>As our system grew, we faced a critical challenge: efficiently processing large volumes of memory-intensive GeoJSON objects stored in PostgreSQL’s <em>JSONB</em> columns. <br>Our initial approach of fetching entire collections before filtering was causing performance issues — high memory usage and slow response times. <br>While a dedicated NoSQL database seemed like a good solution, we discovered that PostgreSQL’s native <em>JSON</em> operations could solve our problems without adding architectural complexity.<br>Let’s examine our approach using Koa.js, Sequelize, and PostgreSQL. These optimizations work with most recent PostgreSQL versions, so you won’t need the absolute latest release.</p><h3>The Data Model</h3><p>Let’s examine some primary data structures we work with:</p><h4><strong>Individual features — representing elements like doors</strong></h4><pre>const point: Feature&lt;Point&gt; = {<br>  type: &quot;Feature&quot;,<br>  geometry: {<br>    type: &quot;Point&quot;,<br>    coordinates: [5230, 4957]<br>  },<br>  properties: {<br>    name: &quot;Door center&quot;,<br>    id: &quot;0193a241-2fd1-705a-aa18-4f9fdbc6c10f&quot;,<br>    types: [&quot;DOOR_POINT&quot;, &quot;MANUAL&quot;]<br>  }<br>}</pre><p>These point features contain essential metadata: coordinates, a unique identifier, and classification types we use for filtering.</p><h4><strong>Feature Collections — how we store related features:</strong></h4><pre>{<br>  &quot;type&quot;: &quot;FeatureCollection&quot;,<br>  &quot;features&quot;: [<br>    {<br>      type: &quot;Feature&quot;,<br>      geometry: {<br>        type: &quot;Polygon&quot;,<br>        coordinates: [<br>          [<br>            [480, 3552],<br>            [529, 3552],<br>            [529, 3606],<br>            [480, 3606],<br>            [480, 3552],<br>          ],<br>        ],<br>      },<br>      properties: {<br>        id: &quot;019312ff-0a6e-751d-8f7e-419a099ef666&quot;,<br>        str: &quot;D&quot;,<br>        name: &quot;text_1&quot;,<br>      },<br>    },<br>    (other features)<br>  ]<br>}</pre><p>Our database stores these collections in <em>JSONB</em> columns, allowing us to leverage PostgreSQL’s JSON operations for efficient querying.</p><h3>Steps to optimize queries</h3><p>Our initial implementation retrieved complete <em>FeatureCollections</em> for processing:</p><pre>const objects = await Model.findAll({<br>  attributes: [&#39;geojson_text&#39;]<br>});</pre><p>This approach produced the following metrics:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/544/1*RKRYm2ePAlKdbiDva1sGag.png" /><figcaption>The array of numbers represents text feature counts per object, showing significant variation (from 0 to 2671 features, undefined means that the text analysis has not been performed on this page).</figcaption></figure><p>In the next step, we implemented database-level filtering using PostgreSQL’s <em>JSON</em> operators — we’ll only return text features with a specific prefix:</p><pre>  const text_path = `feature-&gt;&#39;properties&#39;-&gt;&gt;&#39;name&#39;`;<br><br>  const PARAGRAPH_PREFIX = &quot;paragraph_&quot;;<br><br>  const filtered_text = literal(`<br>    jsonb_build_object(<br>      &#39;type&#39;, &#39;FeatureCollection&#39;,<br>      &#39;features&#39;, COALESCE(<br>        (<br>          SELECT jsonb_agg(feature)<br>          FROM jsonb_array_elements(geojson_text-&gt;&#39;features&#39;) feature<br>          WHERE ${`${text_path} LIKE :paragraph_prefix || &#39;%&#39;`}<br>        ),<br>        &#39;[]&#39;::jsonb<br>      )<br>    )<br>  `);<br><br>  const objects = await Model.findAll({<br>    where,<br>    attributes: [<br>      [filtered_text, &quot;geojson_text&quot;],<br>    ],<br>    replacements: {<br>      paragraph_prefix: PARAGRAPH_PREFIX,<br>    },<br>  });</pre><p>Key components of this optimization:</p><h4>JSON path operations:</h4><ul><li><strong>-&gt;</strong>: Retrieves JSON objects</li><li><strong>-&gt;&gt;</strong>: Extracts text values</li><li>Combined in expressions like <em>feature-&gt;’properties’-&gt;&gt;’name’</em> for property access</li></ul><h4>PostgreSQL Functions:</h4><ul><li><em>jsonb_build_object()</em>: Creates a JSON object from key-value pairs, useful for restructuring our output</li><li><em>jsonb_agg()</em>: Aggregates multiple records into a JSON array</li><li><em>jsonb_array_elements()</em>: Expands a JSON array into a set of rows, enabling us to query individual array elements</li><li><em>COALESCE()</em>: Returns the first non-null value from its arguments; we use it to return <em>‘[]’::jsonb</em> when no features match our criteria</li></ul><h4><em>Sequelize </em>helpers with text matching:</h4><ul><li>Sequelize’s <em>literal()</em>: Allows raw SQL injection into queries when we need complex operations that aren’t supported by Sequelize’s standard query builder</li><li><em>replacements: </em>the <em>PARAGRAPH_PREFIX</em> parameter allows flexible text matching. For example:<br>- With <em>PARAGRAPH_PREFIX = ‘text_’</em>, we match features named <em>‘text_1’</em>, <em>‘text_2’</em>, etc.<br>- The <em>WHERE ${text_path} LIKE :paragraph_prefix || ‘%’</em> condition performs this prefix matching efficiently at the database level</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/634/1*zZiM46TuHth0w5YKDZm3Sw.png" /></figure><p>We immediately see a <strong>26%</strong> shorter duration and a <strong>76%</strong> reduction of response size. Pages with zero counts indicate no text features matching our filter.</p><p>Analysis of our test cases revealed we were sending unnecessary data — particularly geometry information. We implemented property selection:</p><pre>  const selected_properties = [&quot;id&quot;, &quot;str&quot;, &quot;name&quot;];<br><br>  const filtered_text = literal(`<br>    jsonb_build_object(<br>      &#39;type&#39;, &#39;FeatureCollection&#39;,<br>      &#39;features&#39;, COALESCE(<br>        (<br>          SELECT jsonb_agg(jsonb_build_object(<br>            &#39;type&#39;, &#39;Feature&#39;,<br>            &#39;properties&#39;, jsonb_build_object(<br>              ${selected_properties<br>                .map((prop) =&gt; `&#39;${prop}&#39;, feature-&gt;&#39;properties&#39;-&gt;&gt;&#39;${prop}&#39;`)<br>                .join(&quot;,&quot;)}<br>            )<br>          ))<br>          FROM jsonb_array_elements(geojson_text-&gt;&#39;features&#39;) feature<br>          WHERE ${`${text_path} LIKE :paragraph_prefix || &#39;%&#39;`}<br>        ),<br>        &#39;[]&#39;::jsonb<br>      )<br>    )<br>  `);</pre><p>Below we can see the results of such optimization:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/630/1*HUVRZ1U5HAHQWMksCbm7yA.png" /></figure><p>The response size keeps getting smaller — <strong>87%</strong> reduction from baseline, <strong>52%</strong> from the second approach, the duration is <strong>38%</strong> faster than baseline and <strong>15%</strong> faster than the filtered approach.</p><p>Our optimization journey demonstrates that PostgreSQL’s JSON capabilities can effectively replace dedicated NoSQL solutions while:</p><ul><li><strong>Significantly reducing response sizes (87% reduction)</strong></li><li><strong>Improving query performance (38% faster)</strong></li><li><strong>Maintaining a simpler architecture</strong></li><li><strong>Preserving type safety and data integrity</strong></li></ul><p>In the follow-up article, we’ll explore how we abstracted these patterns into a reusable query generator, covering:</p><ul><li><strong>Dynamic property selection</strong></li><li><strong>Complex filtering conditions</strong></li><li><strong>Type-safe JSON operations</strong></li><li><strong>Performance optimization techniques</strong></li></ul><p>Stay tuned!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a90c6e9cf6df" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Resolving KMS Key Error in Backup Replication for Encrypted RDS Volumes Across Regions]]></title>
            <link>https://ppuzio.medium.com/resolving-kms-key-error-in-backup-replication-for-encrypted-rds-volumes-across-regions-2cf7a81de20d?source=rss-def01e3503c4------2</link>
            <guid isPermaLink="false">https://medium.com/p/2cf7a81de20d</guid>
            <category><![CDATA[multi-region]]></category>
            <category><![CDATA[aws-kms]]></category>
            <category><![CDATA[encryption]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[rds]]></category>
            <dc:creator><![CDATA[Paweł Puzio]]></dc:creator>
            <pubDate>Mon, 10 Jun 2024 12:49:31 GMT</pubDate>
            <atom:updated>2024-06-10T12:49:31.669Z</atom:updated>
            <content:encoded><![CDATA[<p>Let’s assume you want to enable backup replication in another region for your encrypted RDS instance. You’ve created the correct key in KMS with the appropriate regional settings, set up the correct permissions, and confirmed that the key is enabled.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hlDoSu8z17BvznWAaWbtiA.png" /></figure><p>After double-checking all data, everything seems fine. You then navigate to the <em>Maintenance &amp; Backups</em> section, click <em>Modify</em>, scroll down to <em>Backup replication</em>, and check the box to enable it. When prompted to provide an <em>AWS KMS</em> key, you open the dropdown but don’t see your newly created key. <strong>This seems</strong> <strong>odd</strong>, so you decide to copy the <em>ARN</em> from the <em>General configuration </em>above.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/932/1*zHEiBs1rL9hAHgNM-xn55Q.png" /></figure><p>Despite seeing that the values were extracted correctly, you’re surprised by an unexpected error message when attempting to modify the DB instance:</p><blockquote>We’re sorry, your request to modify DB instance has failed. The target KMS key does not exist, is not enabled or you do not have permissions to access it.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2gK3iTLVzBJRW3YctmSmLA.png" /></figure><p>You know that the key exists, is enabled, and you have the necessary permissions. So, what’s the problem? The biggest issue here is the misleading error message 🙃. When I first saw it, I started searching for possible missing policy configurations, but nothing seemed to work.</p><p>Feeling hopeless, I turned to ChatGPT, which highlighted a non-obvious step I had missed.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2YS9DvuvHJQllTZH_aVJ1A.png" /></figure><p>It even generated an example policy to help me double-check for any mistakes. Amazon Q, which is supposed to assist with AWS products, didn’t provide <strong>any</strong> help.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/678/1*O1XXj5IH2DosWJpoSTwb9w.png" /></figure><p>So, what’s the solution? Create a new key replica in the region where the backups will be stored.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_NdLVo0TrodZim0dqQICtQ.png" /></figure><p>Once this is done, you should be able to modify the DB instance. <strong>You’ll also start seeing the <em>ARN</em> of the key in the dropdown mentioned above</strong> — a good sign that the operation was successful — and once you’ve modified the instance, you’ll see the chosen region in the <em>Backup </em>section.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rKyCCVCeWeKmcqVkKaTOOQ.png" /></figure><p>Unfortunately, the UX of AWS occasionally leaves a lot to be desired (race conditions, incorrect error messages, etc.), and the robust documentation often provides a lot of information, except what you currently need. Therefore, sharing such knowledge feels like a duty, as these seemingly minor bugs can lead to a lot of frustration. Let me know if this helped!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2cf7a81de20d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Multithreading in the browser with Emscripten and Boost ASIO]]></title>
            <link>https://ppuzio.medium.com/multithreading-in-the-browser-with-emscripten-and-boost-asio-1e4d8484e155?source=rss-def01e3503c4------2</link>
            <guid isPermaLink="false">https://medium.com/p/1e4d8484e155</guid>
            <category><![CDATA[multithreading]]></category>
            <category><![CDATA[emscripten]]></category>
            <category><![CDATA[wasm]]></category>
            <category><![CDATA[boost]]></category>
            <category><![CDATA[webassembly]]></category>
            <dc:creator><![CDATA[Paweł Puzio]]></dc:creator>
            <pubDate>Tue, 26 Sep 2023 13:36:24 GMT</pubDate>
            <atom:updated>2023-09-26T13:36:24.143Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*JhkMIrpShFEljARM" /><figcaption>Photo by <a href="https://unsplash.com/@maksym_tymchyk?utm_source=medium&amp;utm_medium=referral">Maksym Tymchyk 🇺🇦</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>JavaScript’s single-threaded nature has always been raising doubts about its suitability for environments where high performance is crucial. However, now that we can use technologies such as Emscripten and Boost ASIO, developers can incorporate multithreading capabilities, allowing JavaScript to keep up with its counterparts. In this article, we’ll present a straightforward setup for enabling it.</p><p>As mentioned in my <a href="https://medium.com/@ppuzio/c-in-the-browser-with-webassembly-via-emscripten-vite-and-react-bd82e0598a5e">previous article</a>, we’ve been using WebAssembly for some of our calculations at <a href="https://codecomply.ai/">CodeComply.ai</a>. At one moment, we encountered a performance challenge while handling large plans; the limitations of single-threaded WebAssembly became evident, resulting in slow response times and an unsatisfactory user experience. Our C++ engineer modified the script for multithreading, and our responsibility was to successfully launch it in the browser.</p><p>Navigating Emscripten’s documentation on multithreading proved to be less than ideal. Implementing a final solution involved a substantial amount of trial and error, with the help of some equally lost people in GitHub issues. Ultimately, we found ourselves needing to debug the output JavaScript file, despite its size of a few thousand lines. This article aims to assist its readers in avoiding the need for such extensive measures in their own projects.</p><h4>emcc commands</h4><p>To achieve multithreading with ASIO, the initial step is to enable the feature in your C++ code, though the specifics won’t be covered in this article. Once that’s set, we need to add the following parameters to the the <em>emcc</em> invocation (please refer to the previously linked article since we will build upon the emcc command from it):</p><pre>-pthread \</pre><p>The first, and most important flag - without it, implementing multithreading in WASM is not possible. Read more <a href="https://emscripten.org/docs/porting/pthreads.html">here.</a></p><pre>-sENVIRONMENT=web,worker \</pre><p>Here I extended the environment variable flag from the previous article with “worker”, since I personally use a web worker to launch WASM.</p><pre>-s PTHREAD_POOL_SIZE=32 \</pre><p>Setting the thread pool size became a task which led to a tricky bug that was difficult to resolve. Initially, I had set the value to 8, matching the number of cores on my laptop, which, however, later caused machines with more cores to encounter infinite loops during code execution. To mitigate this issue and make our build future-proof, we’ll later replace the fixed value with one obtained from navigator.hardwareConcurrency, ensuring we don&#39;t spawn unnecessary workers on lower-end machines and at the same time are prepared for even more powerful CPUs in the future.</p><pre>-sEXPORT_NAME=yourWasmModule \</pre><p>The clearest explanation of why you should use this flag comes from the error:<br><em>pthreads + MODULARIZE currently require you to set -sEXPORT_NAME=Something (see settings.js) to Something != Module, so that the .worker.js file can work.<br></em>Since we have to use MODULARIZE as Vite has problems working with files that aren’t modules, we’re forced to keep this one :)<br>Our final emcc<em> </em>invocation looks as follows:</p><pre>emcc -lembind \<br>  yourBinding.cpp \<br>  -O2 \<br>  -s MODULARIZE=1 \<br>  -o yourWasmModule.js  \<br>  -pthread \<br>  -sENVIRONMENT=web,worker \<br>  -s PTHREAD_POOL_SIZE=32 \<br>  -sEXPORT_NAME=centerline \<br>  -s TOTAL_MEMORY=256MB \<br>  -I ../eigen/  \<br>  -I ../spatial/src/  \<br>  -I ../boost_1_78_0/  \<br>  -std=c++14 \<br>  -Wno-enum-constexpr-conversion \<br>  --no-entry</pre><h4>Adjusting command</h4><p>In the previous article, we presented some commands that customise the final JS files to suit our project’s specific requirements.</p><pre>sed -i &#39;&#39; &#39;s|locateFile(&quot;yourWasmModule.worker.js&quot;)|locateFile(&quot;/wasm/yourWasmModule.worker.js&quot;)|&#39; yourWasmModule.js &amp;&amp; \</pre><p>As we introduce the new file yourWasmModule.worker.js, we must handle its location in our project, similarly to how we did it before.</p><pre>sed -i &#39;&#39; &#39;s/||_scriptDir/||&quot;.\/yourWasmModule.js&quot;||_scriptDir/g&#39; yourWasmModule.js &amp;&amp; \</pre><p>This one took me a day or two :) basically, we need to pass the JS script used for loading WASM to the workers that are used to simulate the threads. However, the default way of doing it, using _scriptDir, was malfunctioning, so I replaced it with a direct path.</p><pre>sed -i &#39;&#39; &#39;s|self.location.href|&quot;&quot;|&#39; yourWasmModule.js &amp;&amp; \</pre><p>Now that we are deeply involved in the worker logic, we need to be on the lookout for potential traps. One such obstacle arose when the script attempted to load the workers from a path relative to the script’s launch location, and we store the file launching the WASM files in another folder. A quick replacement fixed this hurdle.</p><pre>sed -i &#39;&#39; &#39;s/pthreadPoolSize=32/pthreadPoolSize=yourWasmModule.maxThreads-4||32/&#39; yourWasmModule.js &amp;&amp; \</pre><p>As mentioned earlier with threads, we replace the thread pool size from the building process with one that depends on window.navigator.hardwareConcurrency. From my experience, it’s better to set a value which is a bit lower than the maximum amount, for cases when a really heavy workload would freeze your computer. To avoid potential errors when this script is called in a worker, we pass it as a parameter when invoking the script.</p><pre>sed -i &#39;&#39; &quot;s|if (typeof exports === &#39;object&#39; &amp;&amp; typeof module === &#39;object&#39;)|if(0)typeof await/2//2; export default yourWasmModule;|g&quot; yourWasmModule.js &amp;&amp; \</pre><p>This one is admittedly a hack, and a dirty one. As I’ve mentioned above, we need a version of this script to load in the worker. Since the worker cannot interpret syntax like default export or module.exports by default, and I wanted to avoid creating two files that differed only by one line (export), I resorted to using <a href="https://stackoverflow.com/questions/48396968/how-do-i-check-if-a-script-is-running-as-a-es6-module-so-that-it-can-export/72314371#72314371">a trick from StackOverflow</a> to handle the situation. If only Vite was better with importing non-modules :)</p><h4>Enabling necessary headers in your project</h4><p>Since you’ll need to enable the functionality of SharedArrayBuffer to make multithreading work, you’ll also have to enable certain headers. The documentation of emscripten<em> </em>actually <a href="https://emscripten.org/docs/porting/pthreads.html">mentions a way to achieve this</a>, but the included link doesn’t provide any specific tips about the implementation. <br>For Vite<em>, </em>the following configuration helped with enabling it locally:</p><pre>export default defineConfig(({ command }) =&gt; {<br>  return {<br>    ...<br>    plugins: [<br>       ...<br>      {<br>        name: &quot;configure-response-headers&quot;,<br>        configureServer: (server) =&gt; {<br>          server.middlewares.use((_req, res, next) =&gt; {<br>            res.setHeader(&quot;Cross-Origin-Embedder-Policy&quot;, &quot;require-corp&quot;);<br>            res.setHeader(&quot;Cross-Origin-Opener-Policy&quot;, &quot;same-origin&quot;);<br>            if (_req.headers.host.includes(&quot;localhost&quot;)) {<br>              res.setHeader(<br>                &quot;Access-Control-Allow-Origin&quot;,<br>                `http://${_req.headers.host}`<br>              );<br>            }<br>            next();<br>          });<br>        },<br>      },</pre><p>while this <a href="https://www.reddit.com/r/aws/comments/q4ux1b/how_to_attain_cross_origin_isolation/iiikiqz/?utm_source=share&amp;utm_medium=web3x&amp;utm_name=web3xcss&amp;utm_term=1&amp;utm_content=share_button"><em>reddit link</em></a> helped with enabling it on the AWS side.</p><h4>The invocation itself</h4><pre>    const wasmMethods = await yourWasmModule({<br>      maxThreads,<br>    });</pre><p>In the browser environment, we created the variable maxThreads, which holds the value of window.navigator.hardwareConcurrency and is later passed to the worker calling our WASM module. As demonstrated above, we access this value using yourWasmModule.maxThreads. This mechanism works thanks to the output JS file accepting a parameter, enabling seamless communication with the WASM handler.</p><pre>wasmMethods.PThread?.terminateAllThreads();</pre><p>After completing your calculations, be sure to terminate any hanging threads. It appears that the garbage collection may often be unreliable when the script is initiated repeatedly.</p><p>Once you’ve successfully deployed the WebAssembly script with multithreading, you should observe multiple instances of yourWasmModule.worker.js in the Memory tab.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/939/1*gCIy3xf0tX7TwJegSjFOzg.png" /></figure><h4>Results</h4><p>Results may vary based on your specific usage. It’s important to keep in mind that every architectural decision involves trade-offs. If you identify a consistent pattern where a single-threaded instance of WebAssembly produces better results, it might be a wise approach to use conditional logic to switch between single and multithreaded solutions accordingly.</p><p>With smaller plans, we have observed slightly worse results, likely due to the overhead of orchestrating threads. However, as the plan size increased, the performance significantly improved. For plans with a few hundred rooms, we have noticed performance differences of multiple times (from 2 minutes to under 30 seconds).</p><p>Nevertheless, with certain plans we haven’t observed any noticeable performance advantages, and later on decided to move the calculations away from frontend.</p><p>Hopefully this article helped you understand how to configure and utilize multi-threaded WebAssembly. Please leave a follow if you found it valuable and feel free to comment if you had any problems with setting it up, maybe we can work on it together!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1e4d8484e155" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[C++ in the browser with WebAssembly via Emscripten, Vite and React]]></title>
            <link>https://ppuzio.medium.com/c-in-the-browser-with-webassembly-via-emscripten-vite-and-react-bd82e0598a5e?source=rss-def01e3503c4------2</link>
            <guid isPermaLink="false">https://medium.com/p/bd82e0598a5e</guid>
            <category><![CDATA[cpp]]></category>
            <category><![CDATA[emscripten]]></category>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[webassembly]]></category>
            <category><![CDATA[react]]></category>
            <dc:creator><![CDATA[Paweł Puzio]]></dc:creator>
            <pubDate>Fri, 02 Dec 2022 11:39:38 GMT</pubDate>
            <atom:updated>2022-12-02T12:45:43.826Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SdHe1z2hxMatpd3j_cTEtw.png" /></figure><h4>At <a href="http://codecomply.ai/">CodeComply.ai</a>, by building upon the functionality of <a href="https://togal.ai/">Togal.ai,</a> we’re creating a product which performs a complex fire safety review of floor plans. Since that requires a lot of computation, we decided to give WebAssembly a try.</h4><p><em>This will be the first article in a series, in which I’ll share tips and experience gained during the process of porting scripts from our internal C++ library to the browser, where we handle them using React Hooks and TypeScript.</em></p><p>Most of the articles I’ve found online describe fairly simple examples which couldn’t be applied when connecting a real-world set of functions. <br>There was no mention of linking libraries (we’re using <em>Boost</em>, <em>Eigen</em> and <em>Spatial</em>) or errors resulting from more advanced use. <br>Therefore, this one might seem to have a bit of a steep learning curve. I’ll link the simpler examples and documentation along the way and at the end, hoping it will help you comprehend the whole topic more quickly.</p><h4>Before we start</h4><p><em>There is a reason why I’m mentioning Vite in the title — examples in most of the articles are built with Webpack, which seems to be handling the output much more gracefully. With Vite, many solutions wouldn’t work, even when the same files were used. The reason will be explained later on. <br>Also, this article won’t be mentioning </em><a href="https://github.com/emscripten-core/emscripten/wiki/WebAssembly-Standalone"><em>standalone WASM</em></a><em> (launched without the use of a JS helper). As of December 2022, there’s no good polyfill for WASI that we could use in the browser (</em><a href="https://nodejs.org/api/wasi.html"><em>although Node seems to be doing pretty well</em></a><em>).</em></p><h4>Installing</h4><p>Personally, I consider installing <a href="https://emscripten.org/docs/getting_started/downloads.html"><em>emsdk</em></a><em> </em>to be the supreme way of setting the <em>emcc </em>compiler up. For Mac users, <em>brew install emscripten</em> is an even better option. If you’re planning to integrate some CI/CD scripts, <a href="https://github.com/marketplace/actions/setup-emscripten-toolchain">there should already be a launcher for your platform</a>.</p><h4>Writing our first binding</h4><p>Lots of articles were compiling functions that were placed in the same file where the binding was taking place. <br>In real world, this approach would tie our hands — our functions are usually long and depend on other modules, so what we want to achieve is some kind of interface, where we’ll just import the functions that we want to expose and create a binding.</p><pre>// embinding.cpp<br>#include &lt;emscripten/bind.h&gt;<br>#include &quot;../Scripts/some_module.h&quot;<br><br>EMSCRIPTEN_BINDINGS(my_module) {<br>    emscripten::function(&quot;testFunction&quot;, &amp;testFunction)<br>}</pre><p>Not surprisingly, we need to import the bind module from <em>emscripten</em>, and the function which we want to bind. Next, we call the <a href="https://emscripten.org/docs/porting/connecting_cpp_and_javascript/embind.html#embind"><em>EMSCRIPTEN_BINDINGS</em></a> function. The <em>my_module</em> parameter is there to avoid name collisions. <br>In a simple case like the one above, we invoke a function from the <em>emscripten</em> namespace, giving it two parameters — the name that we’ll use to call the function in the browser, and a reference to the function.</p><h4>Gotchas in this step</h4><p>As I’ve mentioned, the case above is a very optimistic one. For example, if your function uses raw pointers, the <em>emscripten::function</em> will require a third parameter: <a href="https://emscripten.org/docs/porting/connecting_cpp_and_javascript/embind.html#raw-pointers"><em>emscripten::allow_raw_pointers().</em></a></p><p>But still, this might not be the end of your trouble — the compilation might succeed, but in the browser you’ll now see binding errors , such as:</p><blockquote>Cannot call testFunction due to unbound types: PKc, PPc</blockquote><p>If your function expects parameters of a type that’s not implemented in JS, (such as <em>char*), </em>you’ll need to prepare a custom way of calling them.<br>And here E<em>mscripten’s </em><strong>optional_override </strong>comes to the rescue. For example, a function expecting a pointer to a <em>char </em>would be handled like this:</p><pre>EMSCRIPTEN_BINDINGS(my_module) {<br>    emscripten::function(&quot;functionWithPointer&quot;, <br>    emscripten::optional_override(<br>        [](std::string firstArg) {<br>            return functionWithPointer(firstArg.c_str());<br>        })<br>    );<br>}</pre><h4>Writing the <em>compilation</em> command</h4><p>Once we’re done with the previous step, we can begin implementing the <em>emcc </em>compilation command. Since it accepts parameters that <em>gcc</em> would accept as well, this should mostly be familiar to you. <br>As it can get long with all necessary parameters, we’ll prepare a script to launch everytime we want to compile.</p><pre> emcc -lembind \<br>  embinding.cpp \<br>  -O2 \<br>  -s MODULARIZE=1 \<br>  -o yourOutput.js  \<br>  -sENVIRONMENT=&quot;web&quot; \<br>  -I ../eigen/  \<br>  -I ../spatial/src/  \<br>  -I ../boost_1_78_0/  \<br>  -std=c++14 \<br>  -sNO_DISABLE_EXCEPTION_CATCHING \<br>  -Wno-enum-constexpr-conversion \<br>  --no-entry</pre><ul><li>First, we’re launching <em>emcc </em>with the -<em>lembind </em>flag (<a href="https://emscripten.org/docs/tools_reference/emcc.html#emcc-bind"> — bind works too, although it’s deprecated</a>), which is used for linking against the <em>embind</em> library.</li><li>Next, we pass the file containing the bindings (<em>embinding.cpp).</em></li><li><em>-O2 </em>is a flag which means that we want <em>Emscripten </em>to <a href="https://emscripten.org/docs/optimizing/Optimizing-Code.html">optimize the output file’s size.</a> To show you what kind of optimization we’re talking about, let’s look at a table I’ve made based on compiling some of our scripts:</li></ul><pre>| Level | Output WASM size | Output JS size   | Output overall     |<br>| ----- | ---------------- | ---------------- | ------------------ |<br>| O0    | 901 kB           | 242 kB           | 1143 kB            |<br>| O1    | 360 kB (40%)     | 200 kB (82%)     | 560 kB (49%)       |<br>| O2    | **319 kB (35%)** | 106 kB (44%)     | **425 kB (37.1%)** |<br>| O3    | 393 kB (43%)     | **102 kB (42%)** | 495 kB (43%)       |<br>| Os/Oz | 328 kB (36%)     | **102 kB (42%)** | 430 kB (37.6%)     |</pre><p>There’s a sudden drop in JS size between <em>O1</em> and <em>O2 </em>because of the minimization of code - all comments are removed, and the final solution has around 22 lines (compared to 3000+ originally). <br>The WASM size notes a big decrease too, but we’re already getting that with <em>O1.</em></p><ul><li><em>-s MODULARIZE=1 </em>— without this parameter, the output would be placed in the global scope. This doesn’t fix the Vite problem yet, but it’s a good starting point</li><li><em>-o yourOutput.js </em>— specifies the output name</li><li><em>-sENVIRONMENT=”web” </em>— <a href="https://emscripten.org/docs/getting_started/FAQ.html#can-i-build-javascript-that-only-runs-on-the-web">for cases, where you only want to run your code on the Web side.</a></li><li><em>-I ../eigen/ — </em>specifies the headers of the libraries you want to link</li><li><em>-std=c++14 — </em>if your code uses functionalities unavailable in e.g. C++17, you can specify the target version with this flag.</li><li><em>-sNO_DISABLE_EXCEPTION_CATCHING —</em> <a href="https://emscripten.org/docs/porting/exceptions.html#c-exceptions-support">enables exception catching</a>.</li><li>-<em>Wno-enum-constexpr-conversion — </em><a href="https://github.com/emscripten-core/emscripten/issues/17700#issuecomment-1223284259">related to false negatives that might occur in your code, caused by <em>clang</em></a>. Might not be useful in your case.</li><li><em>— no-entry — </em>we have to specify that we’re not creating a <em>main()</em> function.</li></ul><p>Launching this method should create a JS and WASM file in the directory.</p><h4>Improving the output</h4><p>First, we add an <em>/* eslint-disable */ </em>line at the beginning of the file, since some parts of the output code are in conflict with our <em>Eslint</em> config (<a href="https://dominoc925.blogspot.com/2020/12/how-to-setup-c-webassembly-component-to.html">inspired by this article</a>).</p><pre>sed -i &#39;1s;^;\/* eslint-disable *\/;&#39; yourOutput.js<br># for Mac add &#39;&#39; after -i<br>sed -i &#39;&#39; &#39;1s;^;\/* eslint-disable *\/;&#39; yourOutput.js</pre><p>Second, by default the path to the WASM file is less than ideal. We place the files in the <em>public/wasm</em> folder, so let’s also add the following line:</p><pre>sed -i &#39;s|yourOutput.wasm|/wasm/yourOutput.wasm|&#39; yourOutput.js</pre><p>Let’s also look at how the module is currently exported.</p><pre>if (typeof exports === &#39;object&#39; &amp;&amp; typeof module === &#39;object&#39;)<br>  module.exports = Module;<br>else if (typeof define === &#39;function&#39; &amp;&amp; define[&#39;amd&#39;])<br>  define([], function() { return Module; });<br>else if (typeof exports === &#39;object&#39;)<br>  exports[&quot;Module&quot;] = Module;</pre><p>This way of exporting just doesn’t seem to sit well with <em>Vite,</em> it works fine with <em>Webpack</em> though. 🤷 <br>Let’s replace the whole block of code using a Perl one-liner <a href="https://stackoverflow.com/questions/1030787/multiline-search-replace-with-perl#comment126668011_47525973">(inspired by this comment)</a> with <em>export default Module;</em></p><pre>perl -i -p0e  &quot;s/(if \(typeof exports === &#39;object&#39; &amp;&amp; typeof module === &#39;object&#39;\))[\s\S]*/export default Module;/g&quot; yourOutput.js </pre><p>For the comfort of usage, I created a typed <em>useWASM </em>hook:</p><pre>import { useState } from &quot;react&quot;;<br><br>export interface BaseWASMModule {<br>  _malloc: Function;<br>  HEAPU8: Uint8Array;<br>}<br><br>const useWASM = &lt;T&gt;(<br>  helperOutput: (<br>    Module?: unknown,<br>    ...args: unknown[]<br>  ) =&gt; Promise&lt;BaseWASMModule &amp; T&gt;<br>) =&gt; {<br>  const [methods, setMethods] = useState&lt;(BaseWASMModule &amp; T) | null&gt;(null);<br><br>  helperOutput().then((m) =&gt; {<br>    !methods &amp;&amp; setMethods(m);<br>  });<br><br>  return methods;<br>};<br><br>export default useWASM;</pre><p><em>I’m passing the exported module as a parameter, but you could also pass the path/filename and dynamically import it.</em></p><pre>import { useEffect } from &quot;react&quot;;<br>import useWasm from &quot;./useWASM&quot;;<br>import Module from &quot;./yourOutput&quot;;<br><br>interface YourOutputMethods {<br>  functionWithPointer: (<br>    firstArg: string,<br>  ) =&gt; number;<br>}<br><br>export const useYourOutput = () =&gt; {<br>  const module = useWasm&lt;YourOutputMethods&gt;(Module);<br><br>  useEffect(() =&gt; {<br>    if (module) {<br>      // do something, probably assign the output to some state and return it<br>      // or perform some operation and return the result<br>    }<br>  }, [module]);<br>  // return something<br>};</pre><p>Now you can call the above hook in your <em>React</em> component and see the magic happen.<br>If you notice any problems with how your function works, remember — the <em>std::cout </em>calls are actually propagated to the console. It might not be the best debugging experience, but it’s something 😅</p><p>In the next article, I’ll show you how to test the JS/WASM output, how to create TypeScript interfaces from the bindings and share some tips related to moving the process to CI/CD. <br>Hope you’ve enjoyed this article, if you happen to have any problems along the way, make sure to comment, I’ll try to help the best I can.</p><p><em>I’d like to thank my colleagues Olek and Dmitry for helping me with certain C++ and CI/CD challenges and to Olek and Piotr for their comments </em>🙌</p><h4>Articles and repositories worth visiting:</h4><ul><li><a href="https://github.com/bobbiec/react-wasm-demo"><em>Repository which describes how certain emcc params work really well</em></a></li><li><a href="https://emscripten.org/_sources/docs/tools_reference/emcc.txt"><em>Tool reference (although there’s no styling so you’ll have to use CTRL + F to make anything out of it)</em></a></li><li><a href="https://guptanikhil.medium.com/part-ii-opengl-to-webassembly-with-react-8f15430ab6c6"><em>OpenGL with WebAssembly (in case you’d wish to port some WebGL stuff)</em></a></li><li><a href="https://kapadia.github.io/emscripten/2013/09/13/emscripten-pointers-and-pointers.html"><em>Helpful article when you don’t know how to handle input parameters with multiple pointers</em></a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bd82e0598a5e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to use Reduce in JavaScript]]></title>
            <link>https://ppuzio.medium.com/how-to-use-reduce-in-javascript-fbef639b62c1?source=rss-def01e3503c4------2</link>
            <guid isPermaLink="false">https://medium.com/p/fbef639b62c1</guid>
            <category><![CDATA[arrays]]></category>
            <category><![CDATA[reduce]]></category>
            <category><![CDATA[jest]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[functional-programming]]></category>
            <dc:creator><![CDATA[Paweł Puzio]]></dc:creator>
            <pubDate>Thu, 27 Jan 2022 14:58:52 GMT</pubDate>
            <atom:updated>2022-01-27T14:58:52.298Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*rG90-OM7L0cvGA8c" /><figcaption>Photo by <a href="https://unsplash.com/@photoholgic?utm_source=medium&amp;utm_medium=referral">Photoholgic</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><blockquote><em>Why should you care about reduce? It’s a powerful method that allows you to perform complex transformations without writing too much code. This article will explain some of the intricacies of this functionality and hopefully will make you wish you’d been using it more before.</em></blockquote><p>Most commercial programmers will sooner or later stumble upon a term called <em>Declarative Programming</em>. It’s a style that most high schools and universities don’t teach, focused on readability and telling you <strong>what </strong>is done instead of describing <strong>how </strong>things are implemented.</p><p>Oftentimes, when following the declarative approach, we’ll use inbuilt methods like the ones featured in <em>Array.prototype</em> or provided by an external library, like <a href="https://ramdajs.com/"><em>ramda</em></a><em> </em>or <a href="https://lodash.com/"><em>lodash</em></a><em> </em>— in such case we don’t know how the function was implemented exactly, but usually, it’s not a problem.</p><p>Most of these methods are very straightforward — for example <em>Array.prototype.some</em> checks if there’s an element that fulfills our requirements and returns either <em>true</em> or <em>false</em>. <em>Array.prototype.map</em> creates a new array that features all previous elements modified according to the function we passed.</p><p>But there’s one method that also confuses experienced developers — <em>Array.prototype.reduce</em>. In an attempt to demystify it for you, we’ll use it to implement a <strong>basic</strong> version of three popular<em> Array.prototype</em> methods and one <em>Object.prototype </em>method that takes an array as the input. Step-by-step solutions will make sure that also beginners will understand the solution and <strong>Jest tests</strong> provided in the <a href="https://github.com/ppuzio/array-methods-achieved-with-reduce">repository</a> will prove that the newly created methods work as they should.</p><blockquote>Disclaimer: these are not meant to be used as production ready polyfills — I tried to cover as many cases as possible while making sure the examples are not too complicated.</blockquote><h4>Some of you will ask: what’s the fuss about reduce?</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TanAo0qug8lYGLnr5c5jsA.png" /><figcaption>source: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce#Browser_compatibility">https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce#Browser_compatibility</a></figcaption></figure><p>JavaScript keeps evolving; however, some developers still have to support legacy projects. If one wants to use the newest functionalities while e.g. supporting IE9, they’ll have to resort to polyfilling (creating an implementation of a feature for an environment that doesn’t support it). The <em>reduce </em>function works great in that matter.</p><p>Let’s look at the function itself quickly. The way it’s built is both the strongest point and the biggest obstacle when approaching it at first. The function itself accepts two parameters — a <strong>reducer function</strong> and an <strong>initial value, </strong>which is<strong> </strong>optional.</p><blockquote>Array.reduce(reducerFunction, initialValue)</blockquote><p>We’ll talk about the reducer function in a moment, let’s focus on the <em>initial value </em>first. Lots of people will wonder: what makes reduce so powerful? One of the answers lies in the initial value itself. Other array methods return a specific type — <em>map, filter, flat</em>, etc. will return<strong> </strong>an array; <em>some, every</em> return a <em>Boolean (true/false).</em> <br><em>Reduce </em>allows us to return <strong>any type of value, </strong>and the factor that determines the type is our <em>initial value — </em>it will yield different results when provided with different <em>initial values</em>. Mindblowing?</p><p>The<strong> reducer function </strong>itself<strong> </strong>accepts <strong>four </strong>parameters.</p><ul><li><strong>accumulator</strong>: the value that will eventually be returned after the execution, which accumulates the values. In the first step, the <em>accumulator</em> will be equal to <em>initialValue,</em></li><li><strong>current value </strong>— the meaning of <em>current </em>in this context will be explained in a moment,</li><li><strong>current index — </strong>as above,</li><li><strong>the original (input) array</strong>.</li></ul><h4>Warmup example</h4><p>Let’s start with an easy task: we’re given an array of numbers that we want to add together. The imperative approach that’s taught in high schools would probably make use of a <em>for</em> loop. We’d iterate over every element of the array and add that element to a helper variable. And that’s where the non-technical folks will get confused.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9ace424a1e863e6bf2b35a54df7f59d3/href">https://medium.com/media/9ace424a1e863e6bf2b35a54df7f59d3/href</a></iframe><p>This approach demands some knowledge already. While it <strong>is</strong> good for CS101, at the same time it’s a bit <strong>too verbose</strong> for what it does. One needs to know the role of <em>i++</em>, what the <em>[i] </em>after <em>array </em>stands for, and why <em>i</em> was invoked in the first place. Let’s see how <em>reduce</em> could help us here.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9fdec7614bed2edc1bec03d59f92e62b/href">https://medium.com/media/9fdec7614bed2edc1bec03d59f92e62b/href</a></iframe><p>Let’s see what this function does, step by step. Meet <em>console.log</em>, a function that allows us to output each step of the process. We’ll add the aforementioned third reducer variable, <em>index</em>, to show you what happens with each iteration.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1ace2bd54a3e6fda0e67c16ff47b2b84/href">https://medium.com/media/1ace2bd54a3e6fda0e67c16ff47b2b84/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/03fd15d1a1230bf770a924f2ad13864e/href">https://medium.com/media/03fd15d1a1230bf770a924f2ad13864e/href</a></iframe><p><strong>Notice that the value which we return with each iteration becomes the new <em>accumulator</em>. </strong>Notice that, as mentioned before, the <em>accumulator</em> is equal to the <em>initial value</em> in the first iteration.</p><h4><strong>Since <em>Reduce 101</em> is behind us, let’s get to work.</strong></h4><h4>map</h4><p>So how do we recreate <em>Array.prototype.map </em>using <em>reduce</em>? What <em>map</em> does is:</p><p>· it takes each element and applies the passed function to it,</p><p>· it then returns a new array with the modified elements.</p><p>Let’s say we have an array of numbers and we’d want to multiply each by three. We can achieve it with the following function:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0c8d4d87641a3588798a90070755119a/href">https://medium.com/media/0c8d4d87641a3588798a90070755119a/href</a></iframe><p>We’re using the <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions">arrow function expression</a> syntax here, thanks to which we don’t have to use curly braces and <em>return </em>for short functions. Each number is multiplied by 3 and returned. The lengths of arrays before and after are equal. How do we achieve that with <em>reduce</em>?</p><p>What we need to do is to:</p><p>· <strong>create an array </strong>— the initial value has to be an empty array or the <em>concat</em> function will throw an error,</p><p>· take elements of the input array and modify them according to the passed function (we’ll call functions passed as parameters <em>callbacks</em> from now on),</p><p>· add the modified elements to our <em>accumulator</em> array, which will then be returned.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/58e9010e93131c19be98f7a573fd1791/href">https://medium.com/media/58e9010e93131c19be98f7a573fd1791/href</a></iframe><p><em>Concat</em> is an <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/concat"><em>Array.prototype</em> method</a> that allows us to merge an existing array with another one or pass values to it. Code with tests can be accessed <a href="https://github.com/ppuzio/array-methods-achieved-with-reduce/tree/main/methods/map">here</a>.</p><h4>filter</h4><p>Filter returns a new array including the elements that fulfill our requirement. How do we achieve that? By creating a filtering function that returns <strong>true </strong>when the requirements are met.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/59e732bdec2a76cfb0782a6b3373fdf8/href">https://medium.com/media/59e732bdec2a76cfb0782a6b3373fdf8/href</a></iframe><p>What we essentially do is:</p><p>· create an array,</p><p>· take elements from the input array and inspect them with the provided function,</p><p>· when the result of passing the <em>current</em> value to the filtering callback function is <em>true, </em>the value is added to the <em>accumulator</em>, otherwise we leave the <em>accumulator</em> as it is.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/66c931d53dbb7709cf7f3a2509c2e0a5/href">https://medium.com/media/66c931d53dbb7709cf7f3a2509c2e0a5/href</a></iframe><p>Code with tests can be accessed <a href="https://github.com/ppuzio/array-methods-achieved-with-reduce/tree/main/methods/filter">here</a>.</p><blockquote>What’s the deal with this question mark and colon, all of a sudden?</blockquote><p>one might ask. The <em>ternary operator </em>is a shortcut for a traditional <em>if/else </em>conditional statement. If the value passed before the question mark (here <em>callback(currentValue)</em>) is <a href="https://developer.mozilla.org/en-US/docs/Glossary/Truthy"><em>truthy</em></a>, it returns the value after the question mark — in this case, the concatenation of the <em>accumulator</em> and <em>current value</em>, otherwise the value after the colon, which is the <em>accumulator</em> itself.</p><p>It won’t be an exaggeration to say that the TC39 committee and everyone involved in supporting the new ECMA features are heroes to all JavaScript developers by constantly providing functionalities that make our work easier. I promised to provide a way to use new, unsupported functionalities — both <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/flat#Browser_compatibility"><em>Array.prototype.flat</em></a> and <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/fromEntries#Browser_compatibility"><em>Object.fromEntries</em></a> are powerful but unsupported in IE.</p><h4>fromEntries</h4><p>To know what <em>fromEntries</em> does, it’s best to first see how <em>Object.entries </em>works.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b4fc1be1fe16b782c334108d030b75df/href">https://medium.com/media/b4fc1be1fe16b782c334108d030b75df/href</a></iframe><p>The object is transformed into an array of arrays <em>(yikes)</em>, each of them holding a pair of <em>key </em>and <em>value</em>. How do we go back to the original object? The more fortunate ones by using <em>Object.prototype.fromEntries()</em>:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f5f2a135973e934262356c226b46f730/href">https://medium.com/media/f5f2a135973e934262356c226b46f730/href</a></iframe><p>The legacy supporters will have to find another way to achieve that. How?</p><p>We see that for simple objects, the output of <em>entries </em>is always the same. The first element in the array is the index, the second is the value. You can read about the dot syntax that we use in the example below <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_syntax">here</a>.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/576fa3d039b93b11acfc1de802976a41/href">https://medium.com/media/576fa3d039b93b11acfc1de802976a41/href</a></iframe><p>But what about deeply nested objects?</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d1d30185f645d778c2ea716b5cf108b2/href">https://medium.com/media/d1d30185f645d778c2ea716b5cf108b2/href</a></iframe><p>Since <em>Object.entries</em> doesn’t transform nested objects into arrays, our algorithm is also prepared for cases of nested data. Code with tests can be accessed <a href="https://github.com/ppuzio/array-methods-achieved-with-reduce/tree/main/methods/fromEntries">here</a>.</p><p><strong>flat</strong></p><blockquote>Just FYI — this implementation will be longer and more detailed than the previous ones. Don’t think less of yourself if you don’t understand it at first — it also features the thought process that’s necessary to achieve a solution that covers most cases and introduces some tricks.</blockquote><p><em>Array.prototype.flat </em>is an interesting function — as the name suggests, it will flatten (reduce the depth) of the array by as many times as we intend.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8ce5c4b9be142fc6254bd68a67eef5f0/href">https://medium.com/media/8ce5c4b9be142fc6254bd68a67eef5f0/href</a></iframe><p>If no argument is passed to <em>Array.prototype.flat, </em>then the array is flattened by one level. To make sure that any array will be maximally flattened we call <em>flat(infinity). </em>This one will be the most confusing of them all, so fasten your seatbelts. The first attempt looks as follows (don’t worry, we’ll improve it):</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a98a54ec8dde1de90e19f53bba339a5a/href">https://medium.com/media/a98a54ec8dde1de90e19f53bba339a5a/href</a></iframe><p>So, we’ve got the flattening of undefined and numbers down. But what about other values? That’s where it gets dirty.</p><p>What I found out is that that <em>flat </em>treats all <em>falsy</em> values other than undefined <strong>and all other values in general other than numbers bigger than 0 and a Date object </strong>as it would with <em>flat(0)</em>. As you’ve probably guessed, our script isn’t ready for that (yet).</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e4d20bdbcda4a5176cdfdfb0bfe04f39/href">https://medium.com/media/e4d20bdbcda4a5176cdfdfb0bfe04f39/href</a></iframe><p>We’re performing lots of checks in here:</p><ul><li>checking whether <em>times</em> is <em>falsy</em> but not <em>undefined</em>,</li><li>checking whether <em>times </em>is an empty object,</li><li>checking whether <em>times </em>is an empty array,</li><li>checking whether <em>times</em> is a number below zero,</li><li>checking whether <em>times</em> is a nonempty string.</li></ul><p>In any of these cases, we should return the original array. And that covers most of the cases, albeit rather gruesomely.</p><p>There’s one (actually, two) problem — if <em>times </em>is equal to <em>Number.POSITIVE_INFINITY </em>then our do/while loop will never stop iterating. Additionally (that’s the second problem), <em>Date </em>objects are treated as an integer by the native flat function, which interprets them as the number of milliseconds since midnight, January 1, 1970 (around 1.64 * 10¹² as of 19.01.2022).<br>In both of these cases, we want to somehow check if the loop still has to keep going. Additionally, it seems that there are fewer cases where we actually want to perform the flattening than where we want to return the input array, so we’ll simplify the first check as well.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f7b80c3e2a06fdd069b8cd3d0d2c1c03/href">https://medium.com/media/f7b80c3e2a06fdd069b8cd3d0d2c1c03/href</a></iframe><p>Okay, but how do we know for certain that our function will yield the same results as the native one? That’s where unit tests come in handy. Since these tests are a bit more complex than the previous ones, they’ll be described step by step.</p><p>We need to create some data that we’ll use to verify if our function works properly. This means that we have to cover several cases of depth and irregular nesting. <br>First, we create some methods and variables that will help us test edge cases and create data.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ca4d066cf2bcb600ab94ecddc5406f96/href">https://medium.com/media/ca4d066cf2bcb600ab94ecddc5406f96/href</a></iframe><p>Our first method <em>arrayOfNumbers</em> creates an array of numbers, starting from <em>1</em> up until the number that we provide as length, so calling it with 3<em> </em>will return [1,2,3], etc. Then we create an array that we’ll use to check if a very deeply nested array has been correctly flattened. <br>The last variable and function might look scary, so let me explain them with an example.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/43030cfaa579d7706d395696068e73da/href">https://medium.com/media/43030cfaa579d7706d395696068e73da/href</a></iframe><p>Our <em>nestedArrayGenerator</em> function uses <em>reduceRight, </em>which basically works like <em>reduce, </em>but starts iterating from the last element. In each iteration, the function creates an array where the first element is the current element, and the second element is the <em>accumulator</em> array. If the accumulator array is empty (first step), then we just insert the current element inside.</p><p>Afterward, I created some more data using a different nesting pattern — the first group of variables follows a symmetrical nesting pattern, and the second one follows a wavy one.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/898c0c0f92e713a057a7634db84ccf60/href">https://medium.com/media/898c0c0f92e713a057a7634db84ccf60/href</a></iframe><p>Then we create cases for our tests to check — each of these cases will be an array, containing the input array that we provide to our <em>flat </em>function, the depth argument that we’ll use, and our expected output array. I also provided cases that can make our function crash.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9de00e801086473f5e7df89b244ef772/href">https://medium.com/media/9de00e801086473f5e7df89b244ef772/href</a></iframe><p>The last missing piece is the actual test itself. I used the<em>test.each </em>function provided by Jest, but it’s also possible to use <em>forEach </em>on the <em>cases </em>array. <br>The second <em>each </em>call accepts two parameters: a string that explains the case which is tested and an assertion function that will perform the actual test. Each <em>%p </em>in the first string represents an argument in the assertion function.</p><p>In line 5 we create a result of using the in-built flat function, and in line 6 we create a result of using our custom function. Then we check if both arrays are equal to the array that we’re expecting.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/22534041c23c817c622683962722e07d/href">https://medium.com/media/22534041c23c817c622683962722e07d/href</a></iframe><p>Code with tests can be found <a href="https://github.com/ppuzio/array-methods-achieved-with-reduce/tree/main/methods/flat">here</a>.</p><p>As you can see, we managed to achieve quite a lot thanks to the power of <em>reduce </em>(and <em>do/while </em>in the last example, I’ve got to admit the imperative style came in handy). I hope you’ve learned how powerful <em>reduce </em>is, that the immediate intimidation is gone and that you’ll start using it in your projects!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fbef639b62c1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Flexbox gap workaround for Safari on iOS 14, 13 and lower]]></title>
            <link>https://ppuzio.medium.com/flexbox-gap-workaround-for-safari-on-ios-14-13-and-lower-ffcae589eb69?source=rss-def01e3503c4------2</link>
            <guid isPermaLink="false">https://medium.com/p/ffcae589eb69</guid>
            <category><![CDATA[flexbox]]></category>
            <category><![CDATA[responsive-design]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[css]]></category>
            <category><![CDATA[safari]]></category>
            <dc:creator><![CDATA[Paweł Puzio]]></dc:creator>
            <pubDate>Fri, 09 Jul 2021 13:46:24 GMT</pubDate>
            <atom:updated>2021-07-09T13:46:24.998Z</atom:updated>
            <content:encoded><![CDATA[<h4>How to create a correct CSS @supports at-role to eliminate visual inconsistencies between browsers</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*9WUPd87bXFPrFn8j" /><figcaption>Photo by <a href="https://unsplash.com/@raagesh?utm_source=medium&amp;utm_medium=referral">Raagesh C</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><blockquote>tl;dr:</blockquote><blockquote>@supports (-webkit-touch-callout: none) and (not(translate: none))</blockquote><p>Since working on a commercial project almost always means having to support at least the previous version of each browser available, some surprises might always occur when inspecting the way your project works for older versions.</p><p>Unless you’re purposefully avoiding adjusting the layouts for mobile clients, <a href="https://www.statista.com/statistics/277125/share-of-website-traffic-coming-from-mobile-devices/">which might hurt your business, considering around 50% of </a><a href="https://www.statista.com/statistics/277125/share-of-website-traffic-coming-from-mobile-devices/">worldwide</a> <a href="https://www.statista.com/statistics/277125/share-of-website-traffic-coming-from-mobile-devices/">website traffic </a><a href="https://www.statista.com/statistics/277125/share-of-website-traffic-coming-from-mobile-devices/">nowadays</a><a href="https://www.statista.com/statistics/277125/share-of-website-traffic-coming-from-mobile-devices/"> comes from mobile devices</a>, you’ll quickly run into problems related to styling mobile Safari below 14.1 (iOS below 14.5).</p><p>Some problems that I’ve encountered so far:</p><ul><li>incorrect evaluation of the height of <em>&lt;button&gt; </em>elements,</li><li>containers with <em>display: flex </em>having problems interpreting the height of their children, therefore rendering a second child somewhere in the middle of the first one,</li><li>inconsistent behaviour of <em>height </em>attribute compared to other browsers,</li><li>and the icing on the cake: lack of support for the <em>gap </em>property when using <em>display: flex.</em></li></ul><p>Why is the last one so annoying? The <em>gap</em> property, before iOS 14.5, was implemented only for <em>display: grid, </em>and since both of these properties don’t have any distinction when it comes to the name of the property, it’s not really possible to create a <em>@supports </em>at-rule as easily as we would’ve normally.</p><figure><img alt="Support tables for flex-gap and grid-gap respectively" src="https://cdn-images-1.medium.com/max/1024/1*CWK5x9wi0AaNUpaTMLBM7A.png" /><figcaption>source: <a href="https://developer.mozilla.org/en-US/docs/Web/CSS/gap">https://developer.mozilla.org/en-US/docs/Web/CSS/gap</a></figcaption></figure><p>Since <em>@supports not (grid: 8px) </em>is out of the question, we’ll have to take another approach.</p><p>So how does the aforementioned selector work? Thanks to some googling, I quickly managed to find a <a href="https://stackoverflow.com/questions/30102792/css-media-query-to-target-only-ios-devices">selector that would only target Safari on iOS</a>.</p><figure><img alt="Support table for the webkit property" src="https://cdn-images-1.medium.com/max/998/1*UmcgGgfh_VNtu0HvIDzpVQ.png" /><figcaption>source: <a href="https://developer.mozilla.org/en-US/docs/Web/CSS/-webkit-touch-callout">https://developer.mozilla.org/en-US/docs/Web/CSS/-webkit-touch-callout</a></figcaption></figure><p>The second part was much more difficult — how do we find a property that’s only been supported since the release of Safari 14.1? A quick peek into the release notes helped — bingo, the <em>translate</em> property had not been supported before Safari 14.1 for both macOS and iOS was released:</p><figure><img alt="Release notes for Safari 14.1 — info about flex-gap being supported from now on" src="https://cdn-images-1.medium.com/max/767/1*pWFtAYoJD_1BXun7rP8tfg.png" /><figcaption>source: <a href="https://developer.apple.com/documentation/safari-release-notes/safari-14_1-release-notes">https://developer.apple.com/documentation/safari-release-notes/safari-14_1-release-notes</a></figcaption></figure><figure><img alt="Browser compatibility for translate" src="https://cdn-images-1.medium.com/max/1024/1*NQcvLZEtI2G1AdaRmt_zSw.png" /><figcaption>source: <a href="https://developer.mozilla.org/en-US/docs/Web/CSS/translate">https://developer.mozilla.org/en-US/docs/Web/CSS/translate</a></figcaption></figure><p>Therefore, by combining these two we can create a selector that targets</p><ul><li>only mobile Safari</li></ul><p>and</p><ul><li>devices with iOS version lower than 14.5 (Safari version lower than 14.1).</li></ul><p>which is exactly what we were aiming for.</p><p>I enjoy this approach as well because you don’t have to write <em>@media </em>queries when using it, as only mobile Safari is targeted thanks to the first part.</p><p>So how do we test this? Thankfully, we have <a href="https://www.browserstack.com/">Browserstack</a>. It’s an amazing tool that lets you simulate the behaviour of various browsers on many different phone models.</p><p>Let’s start with a simple example — three divs of 30% width separated by a 5% width gap. I set the background-color to <strong>#cde9c5</strong> so that the gap is visible.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/446c0fa409c56150a33cc5b250f859c1/href">https://medium.com/media/446c0fa409c56150a33cc5b250f859c1/href</a></iframe><figure><img alt="Gap applied correctly on a Samsung device that uses Chrome" src="https://cdn-images-1.medium.com/max/622/1*Fly-bZKzhiM6P7fIAq8sww.png" /><figcaption>Chrome on Galaxy S20 interprets gap correctly</figcaption></figure><p>How will it work on a Safari 14/13 device though?</p><figure><img alt="Gap not applied correctly on iPhone" src="https://cdn-images-1.medium.com/max/644/1*jFTrEFr71NKcMfCOmuz5qw.png" /></figure><p>As we can see, the gap is not there, and therefore the divs took 90% of the space, and the remaining 10% is green. How do we fix this then?</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d0236cf798503190036f9fba9b92d90e/href">https://medium.com/media/d0236cf798503190036f9fba9b92d90e/href</a></iframe><p>By providing a 5% margin-right to each but the last child, we managed to overcome the problem.</p><figure><img alt="Screenshot of Safari on iPhone, this time displaying the gaps correctly" src="https://cdn-images-1.medium.com/max/673/1*rR3V06-zsZJ0Hl0FnI0h_g.png" /></figure><p>As we can see after inspecting the elements, the extra at-rule was applied.</p><figure><img alt="Screenshot of the styles part of developer tools, proving that the additional styling was applied" src="https://cdn-images-1.medium.com/max/327/1*NHkEIbAtZInM-0VfIN2MjA.png" /></figure><p>As expected, devices that support flex-gap will not see this rule.</p><figure><img alt="The styles shown above are not present this time in the styles tab" src="https://cdn-images-1.medium.com/max/327/1*TGof5BCmFP0jAQ15Gk-geA.png" /></figure><p>I hope this article helps you facilitate the process of supporting Safari below 14.1. Other solutions out there mostly demand using JS, and I find using CSS to handle such problems a more consistent technique, as we’re taking care of styling problems in the exact place where they should be managed.</p><p>P.S. The example above was done using <a href="https://styled-components.com/"><em>styled-components</em></a><em>. </em>If you want to use the @supports syntax with CSS try <a href="https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Conditional_Rules/Using_Feature_Queries">this article</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ffcae589eb69" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to smoothly manage shared logic with custom React hooks]]></title>
            <link>https://medium.com/jit-team/how-to-smoothly-manage-shared-logic-with-custom-react-hooks-558575c11bcf?source=rss-def01e3503c4------2</link>
            <guid isPermaLink="false">https://medium.com/p/558575c11bcf</guid>
            <category><![CDATA[hooks]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[higher-order-components]]></category>
            <category><![CDATA[front-end-development]]></category>
            <category><![CDATA[react-testing-library]]></category>
            <dc:creator><![CDATA[Paweł Puzio]]></dc:creator>
            <pubDate>Wed, 04 Nov 2020 06:43:04 GMT</pubDate>
            <atom:updated>2020-11-04T06:43:04.043Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*lOq4RCDuhAQiL0LO" /><figcaption>Photo by <a href="https://unsplash.com/@vishu_2star?utm_source=medium&amp;utm_medium=referral">Vishal Jadhav</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>As our apps grow in complexity, there’s an inevitable increase in the component logic that follows along the way. We need to address aspects such as custom error handling, data transforming or applying domain specific business logic. We might usually deem it as straightforward, <strong>as long as we don’t have to deal with any side effects or internal state</strong> — we simply create a function that’s also easy to reuse. However, sooner or later, we’ll stumble upon a more advanced case.</p><p>Disclaimer — this article will only try to demonstrate why handling external logic with hooks might be <strong>more readable, easily testable (I’ll include examples of tests for hooks under the code examples) and scalable in the long run</strong>. I’m not aiming to belittle the previous API or idealize Hooks in any way.</p><p>Lots of React developers will remember working with the <em>Component API </em>that made use of <em>JavaScript classes</em>. For people coming from a more systematic background, such as backend languages or <em>Angular</em>, it faciliated the process of working with <em>React</em>. Yes, they still had to face the intricacies of working with e.g. the <em>JSX </em>syntax, but it reminded them of code that they were accustomed to working with, especially when paired with <em>TypeScript </em>(sadly, not supported out of the box by the <em>Create-react-app CLI </em>at that time).</p><p>Unfortunately, the <em>Component API </em>has its pitfalls, existence of which we realized mostly after the introduction of <em>Hooks</em>. Where should we begin? <strong>Local state of a component can only be pointing to one reference</strong> — with hooks we can create as many <em>useState </em>methods as we wish. <br>Yes, the fact that the in-built <em>setState </em>function would only overwrite the part of state that we want it to helps, but it still makes local state a bit cluttered at times. Lifecycle methods are a pain to control once you have several different, unrelated topics to handle and introduce a pretty steep learning curve as well.</p><p>And the worst pitfall? <strong>Higher-Order Components.</strong> Back then it was the only way to handle inserting logic into components and gave us some hope of being able to overcome it in a way that wouldn’t make us ill, but it comes with its own problems. Remember how <em>Promises </em>helped us avoid the famous callback hell when handling asynchronous operations? <em>HOCs </em>would often result in a <strong>HOC hell,</strong> where we’d wrap a component in a multitude of providers. This often resulted in not only worse readability but could also potentially mean hard to find bugs — for example in the case of a name collision.</p><p>Let’s say we wanted to create a reusable component that would make use of the <a href="https://reactrouter.com/web/guides/quick-start"><em>React-router-dom</em></a><em> </em>library parameters. We’d have to first wrap it with the <em>withRouter HOC</em>, then create a new class extending <em>React.Component</em>, that handles the logic inside (possibly in some lifecycle hooks) and sends the parameters down via props to a child component. What’s the problem here? First, we’re adding <strong>two additional levels</strong> that could result in bugs — each of these <em>HOC-s</em> could potentially misbehave, so we’d have to analyze<strong> each of them </strong>if a problem were to occur. Secondly, we’re extending the <em>props </em>object, adding additional work with typing and potentially introducing performance issues (since props are one of the triggers for re-rendering components).</p><p>So, let’s see how such problems were overcome and simplified with <em>Hooks</em>. Let’s first look at an example of logic that’s set inside of a functional component.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c8ed8140d64b4be3c92723725be8b179/href">https://medium.com/media/c8ed8140d64b4be3c92723725be8b179/href</a></iframe><p>Inside, we have a simple, one-line declaration of the <em>state hook</em>, as well as the <em>useParams </em>hook responsible for selecting a parameter from the URL. There’s also a single <em>useEffect</em> hook that will react according to the parameter change. Can you already see an improvement? <strong>We didn’t have to wrap the component with <em>withRouter</em>, because <em>useParams </em>is a</strong> <strong>(spoiler) custom hook </strong>responsible for fetching <strong>only the part of the object provided by withRouter we’re interested in</strong> — parameters — <strong>while with Components we’d also receive the history and location objects</strong>. <br>But what we’d like to reuse this logic across the application? <strong>That’s where the custom hooks magic begins.</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4c7ae5f19764655029455cce071b48a6/href">https://medium.com/media/4c7ae5f19764655029455cce071b48a6/href</a></iframe><p>This change might appear a bit confusing — most of the code is repeated. We created a function called <em>useFetchBook</em>, which includes all of the logic present above but exported to a separate file. As you might have already noticed, we’re still using the <em>useParams </em>custom hook as well as the basic <em>useState </em>hook inside of our new hook — yes, we can nest hooks, which means <strong>we don’t have to pass such parameters as arguments</strong>, a thing that was unimaginable with the Component API. <br>This results in <strong>much cleaner code and simpler debugging experience.</strong> But how do we use our custom hook in our component?</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/91ce9f6dda2b4a8101bb0f4de0d64e5b/href">https://medium.com/media/91ce9f6dda2b4a8101bb0f4de0d64e5b/href</a></iframe><p>The <em>useParams </em>usage might have spoiled it — we just have to invoke the custom hook inside of our function component and destructure the properties we need. We can now reuse it all across the application in <strong>a</strong> <strong>very simple and comprehensible way,</strong> <strong>instead of having to resort to using some HOC mumbo-jumbo.</strong></p><p>Let’s look at another example — a custom hook that will handle the frontend pagination logic for us. Inside, we’ll have two simple state hooks that will store the current page and amount of items per page, as well as methods that will handle changing the page, items per page and resetting the page. The code looks as follows.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3e6a9117b813d6cfe5a6b06960e3cf5f/href">https://medium.com/media/3e6a9117b813d6cfe5a6b06960e3cf5f/href</a></iframe><p>One might ask why the methods are wrapped with <em>useCallback </em>— using it can improve performance in some use cases — <a href="https://medium.com/jit-team/web-applications-performance-7776ebb38070">more in this article that Oskar wrote</a>. In our experience, when using this hook with tables, we noticed some unexpected performance issues before wrapping above functions with <em>useCallback</em>.</p><p>Now, we only have to create an instance of <em>usePaginatedTable </em>in our component and pass it to the table.</p><p>What if we wanted to make sure that our custom hook will always handle the pagination logic correctly? That’s where <a href="https://github.com/testing-library/react-hooks-testing-library"><em>testing-library/react-hooks-testing-library</em></a> comes in handy. Let’s see how we would test our newly created hook with the help of it.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ab84e8472fba2f2321b86f71874ecbc9/href">https://medium.com/media/ab84e8472fba2f2321b86f71874ecbc9/href</a></iframe><p>We need to import two methods from the library in this example — the <em>act </em>method that will allow us to perform e.g. state changes, and the <em>renderHook </em>method that will generate the result of calling our hook. One thing that might be surprising is that the result of the rendering is stored in an object that looks like a <em>ref. </em>There’s also another thing that has to be mentioned — as you might have noticed, we don’t destructure the properties from our result. We do it for a reason — to quote the official documentation:</p><blockquote><a href="https://react-hooks-testing-library.com/usage/basic-hooks#updates"><strong>NOTE</strong>: There’s a gotcha with updates. </a><a href="https://react-hooks-testing-library.com/usage/basic-hooks#updates">renderHook mutates the value of </a><a href="https://react-hooks-testing-library.com/usage/basic-hooks#updates">current when updates happen so you cannot destructure its values as the assignment will make a copy locking into the value at that time.</a></blockquote><p>While this already makes working with hooks that return an object pretty uncomfortable, it’s absolutely dreadful when a hook returns an array — and it’s not such a rare case. Imagine a hook which we know that might be invoked multiple times in a function — one example might be a hook responsible for handling the toggle mechanism.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2b18ab7f2895e8555d9a0ed110425889/href">https://medium.com/media/2b18ab7f2895e8555d9a0ed110425889/href</a></iframe><p>We want to return an array here for the simple reason of not having to always reassign the name returned by the hook — as you might already know, destructuring an array means that we can call the destructured elements any way we want. But what does that mean in the context of testing?</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1eeeee60731c43e8d3db7fee9de4f8ca/href">https://medium.com/media/1eeeee60731c43e8d3db7fee9de4f8ca/href</a></iframe><p>As you might have noticed, I wrote the order of elements in the array and their names in a comment. So far, that’s the best way of testing hooks which return an array that I’ve come up with.</p><p>To sum up: custom hooks are a great way to extract reusable logic to an easily testable function, while also allowing us to transform a humongous chunk of code into an elegant one-liner. Also, although the current standard library for testing them might not have the most elegant API and might be tricky at first, it’s still more straightforward than e.g. Enzyme.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=558575c11bcf" width="1" height="1" alt=""><hr><p><a href="https://medium.com/jit-team/how-to-smoothly-manage-shared-logic-with-custom-react-hooks-558575c11bcf">How to smoothly manage shared logic with custom React hooks</a> was originally published in <a href="https://medium.com/jit-team">Jit Team</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Internationalisation — easier done than said]]></title>
            <link>https://medium.com/jit-team/internationalisation-easier-done-than-said-c235fd077555?source=rss-def01e3503c4------2</link>
            <guid isPermaLink="false">https://medium.com/p/c235fd077555</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[front-end-development]]></category>
            <category><![CDATA[internationalization]]></category>
            <category><![CDATA[react-intl]]></category>
            <category><![CDATA[react]]></category>
            <dc:creator><![CDATA[Paweł Puzio]]></dc:creator>
            <pubDate>Mon, 15 Jul 2019 07:51:33 GMT</pubDate>
            <atom:updated>2019-07-15T07:51:33.982Z</atom:updated>
            <content:encoded><![CDATA[<h3>Internationalisation — easier done than said</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZrdU5i7Z6qj5ZWXqciln_w.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@iambrettzeck?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Brett Zeck</a> on <a href="https://unsplash.com/search/photos/world-map?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p>Building modern web applications involves many challenges, for instance displaying the data in a way that the users are familiar with it. Apart from the most obvious aspect — providing translations — developers have to keep in mind how different countries present dates, numbers, etc. Lack thereof can result in forfeiture of clients, insulted that they’re not perceived as a group substantial enough to support.</p><p>This requires applying a tool that has a broad community support, vast documentation and is backed by a meaningful organisation. An example of such tool is <a href="https://github.com/formatjs/react-intl">react-intl</a>, created by Yahoo, that builds over the built-in <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl">Intl</a> API.</p><p>We won’t focus on the configuration too much, as the documents already describe it in a very detailed and comprehensive way. Instead, we’ll present some real world use cases that will show you how easy it is to implement internationalisation in your projects.</p><p>Supporting the internationalisation of messages is the most crucial, and sometimes, troublesome task. Each language requires a separate JSON file consisting of a unique ID and corresponding text pairs.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/722/1*UEZ2p1NgMi1PwCM_daXpjA.png" /><figcaption>Simple JSON file with a couple of ID: translation pairs</figcaption></figure><p>In case of a necessary pair not being present, the default message will be used:</p><p><a href="https://codesandbox.io/embed/messages-displayed-when-we-dont-provide-a-json-file-3czkt">Messages displayed when we don&#39;t provide a JSON file - CodeSandbox</a></p><p>There are two approaches when it comes to default messages: they can either not be specified at all — in such case, if no translation is provided, then the id will be shown instead. This is a great way to identify missing translations, but demands very strict testing.</p><p><a href="https://codesandbox.io/embed/missing-default-messages-display-ids-rps21">Missing default messages display IDs - CodeSandbox</a></p><p>The other one requires filling the messages in a language of choice. This will make sure that if an ID is missing in a JSON file, a fallback will be returned instead, as in the first example. Finding missing translations in the selected language will be almost impossible, though. It’s up to the development team to choose their approach.</p><p>Undoubtedly, it’s a good practice to sort the JSON files alphabetically by IDs and visually separate translations of respective components — it facilitates the analysis of potential mistakes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZLxGKLIdmQuJxL0kFeJRCQ.png" /><figcaption>A side-by-side view allows to spot missing translations easily.</figcaption></figure><p>Once everything is set up, it’s only a matter of introducing a language altering mechanism and the translation will proceed seamlessly.</p><p><a href="https://codesandbox.io/embed/change-locale-with-buttons-xo7yr">Change locale with buttons - CodeSandbox</a></p><p>The library provides two components for text translation: <strong>FormattedMessage</strong>, which<em> </em>creates a HTML paragraph tag with its own styling, and <strong>formatMessage</strong><em> </em>that returns a string. The latter will be more useful in situations when passing a full tag would impair the presentation — e.g. when passed to a header in a card.</p><p>Since providing translations is often the duty of non-technical employees, it should be noted that it’s easy to introduce them to internationalisation. Once a developer inserts the component into DOM, the only thing left is to fill the JSON. The business team needs to be provided with an IDE that applies the styling used by the developer team, a Git account and they’re ready to go.</p><p>Bear in mind that following the aforementioned approach might as well be beneficial to projects that don’t demand internationalisation. Hard-coded text will not only make code appear cluttered, but can also create inconsistencies across the application. One example would be a message that is shared across many components — updating its content would mean having to update it everywhere it’s featured. Fetching them from one place means smooth changes, and furthermore, can be performed by non-technical people.</p><p>One of the most confusing aspects of American culture is their manner of displaying dates, that start with month, proceeded by day and year. The question then arises: how do we present the dates to American users, if the default format is a day-month-year one? That’s where the second component — <strong>FormattedDate</strong> — comes in handy.</p><p><a href="https://codesandbox.io/embed/change-date-locale-with-button-x58yw">Change date locale with button - CodeSandbox</a></p><p>Just merely passing a locale as a parameter converts the date automatically. Bear in mind to <strong>always</strong> provide specified locales — instead of <em>en</em> distinguish <em>en-GB</em> and <em>en-US</em>! There’s also a possibility to use a relative date format — rather than exact dates, we can use phrases like yesterday, 15 minutes ago, in 2 hours. It definitely helps with presenting them in a more common, less automatic way.</p><p><a href="https://codesandbox.io/embed/example-of-relative-vs-standard-date-z8nvh">Example of relative vs standard date - CodeSandbox</a></p><p>Enterprise projects will definitely admire the rich number formatting possibilities that <strong>FormattedNumber</strong> provides. It’s absolutely crucial to use locale here — the decimal and thousand separators vary greatly in different regions. Otherwise, there’s a risk of customers misunderstanding numbers provided to them.</p><p><a href="https://codesandbox.io/embed/example-of-number-formatting-2wlf4">Example of number formatting - CodeSandbox</a></p><p>Supporting internationalisation is not a trivial matter and should always be given enough emphasis. Absence of such could result in a dissatisfaction of groups of customers, which in consequence can put the whole business at stake. With the growing popularity of accessibility, providing translations might be regarded as such in the future.</p><p>Hopefully, this article will persuade its readers that the transition to a multilingual page is completely effortless and shouldn’t be a burden on developers, once they’re briefed on the advantages.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c235fd077555" width="1" height="1" alt=""><hr><p><a href="https://medium.com/jit-team/internationalisation-easier-done-than-said-c235fd077555">Internationalisation — easier done than said</a> was originally published in <a href="https://medium.com/jit-team">Jit Team</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>