<?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"><channel><title><![CDATA[Ady Ngom's Tech Corner]]></title><description><![CDATA[Ady Ngom's Tech Corner]]></description><link>https://adyngom.com</link><generator>RSS for Node</generator><lastBuildDate>Wed, 22 Apr 2026 11:55:43 GMT</lastBuildDate><atom:link href="https://adyngom.com/rss.xml" rel="self" type="application/rss+xml"/><language><![CDATA[en]]></language><ttl>60</ttl><item><title><![CDATA[The AI Future Accelerator:  
2-Day ADK Master Class]]></title><description><![CDATA[DEEP DIVE: Agent Developer Kit (ADK) Mastery with ADY NGOM
WHEN: December 3rd & 4th 2025 from 4pm to 8pm ESTWHERE: Advanced Technology Department Center ATDC ( Directions )COST: $1500 per attendee[CLICK HERE TO REGISTER]
STOP WAITING TO BUILD. START ...]]></description><link>https://adyngom.com/the-ai-future-accelerator-2-day-adk-master-class</link><guid isPermaLink="true">https://adyngom.com/the-ai-future-accelerator-2-day-adk-master-class</guid><category><![CDATA[google adk workshop]]></category><category><![CDATA[AI Agent Development]]></category><category><![CDATA[google adk]]></category><dc:creator><![CDATA[Ady Ngom]]></dc:creator><pubDate>Mon, 17 Nov 2025 07:30:08 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1763363558175/76c006b0-34bd-44df-8c86-7b22c1157ed2.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h2 id="heading-deep-dive-agent-developer-kit-adk-mastery-with-ady-ngom"><em>DEEP DIVE: Agent Developer Kit (ADK) Mastery with ADY NGOM</em></h2>
<p><strong>WHEN:</strong> December 3rd &amp; 4th 2025 from 4pm to 8pm EST<br /><strong>WHERE:</strong> Advanced Technology Department Center ATDC ( <a target="_blank" href="https://www.google.com/maps/dir//75+5th+St+NW,+Atlanta,+GA+30308/@34.2504262,-84.2173394,15z/data=!4m8!4m7!1m0!1m5!1m1!1s0x88f50466e88323f9:0xb1720ff0f45b8f08!2m2!1d-84.3894776!2d33.7779315?entry=ttu&amp;g_ep=EgoyMDI1MTExMi4wIKXMDSoASAFQAw%3D%3D">Directions</a> )<br /><strong>COST:</strong> $1500 per attendee<br /><a target="_blank" href="https://register.adyngom.com/adk-2-day-masterclass"><strong>[CLICK HERE TO REGISTER]</strong></a></p>
<h3 id="heading-stop-waiting-to-build-start-owning-the-future"><em>STOP WAITING TO BUILD. START OWNING THE FUTURE.</em></h3>
<p><em>The cost of waiting is too high. The time to transition from observer to creator is NOW</em>.</p>
<p>The response to the power of Agentic AI systems has been absolutely electrifying. If you are a developer, architect, or innovator <em>alive</em> in the current tech landscape, you understand that agentic AI is the future. This 2-Day Master Class is your <em>crucial follow-through</em> and the <em>definitive answer to your still-unanswered questions</em> on building with Google’s Agent Development Kit.</p>
<p>For a <em>groundbreaking</em> <strong><em>investment of just $1500,</em></strong> <em>you will dramatically elevate your AI development skills and transform yourself into a builder</em> of that future. This is not merely an option—<em>this is non-negotiable!</em></p>
<h3 id="heading-your-investment-1500-limited-enrollment"><em>YOUR INVESTMENT: $1500 (Limited Enrollment)</em></h3>
<p><em>This is the essential next step</em> to seriously level up your skills. We have extended the renowned intensive workshop format into two full days of hands-on mastery to ensure you bypass the basics and solidify your understanding.</p>
<p><em>Space is severely limited</em> to ensure a high mentor-to-attendee ratio, guaranteeing the immediate, direct developer support you need to crush code roadblocks. <em>Secure your spot now—this unprecedented opportunity to continue the build</em> will not last.</p>
<p><a target="_blank" href="https://register.adyngom.com/adk-2-day-masterclass"><strong>[CLICK HERE TO REGISTER]</strong></a></p>
<h3 id="heading-the-2-day-agent-architect-immersion"><em>THE 2-DAY AGENT ARCHITECT IMMERSION</em></h3>
<p>We are moving beyond simple demos to focus intensely on <em>actionable, practical skill-building. This Master Class is entirely focused on getting you shipping functional code</em>.</p>
<h4 id="heading-day-1-unpacking-the-adk-and-defining-the-tools"><em>DAY 1: Unpacking the ADK and Defining the Tools</em></h4>
<p>If you attended introductory sessions and left with more questions than answers, Day 1 provides the solutions. You will gain a comprehensive, practical understanding of Google’s Agent Development Kit (ADK) and how it simplifies the creation of complex, multi-step AI workflows.</p>
<ul>
<li><p><em>Zero Fluff Deep Dive:</em> We bypass the basics to immediately master defining tools and managing state within the ADK.</p>
</li>
<li><p><em>The Architecture Mandate:</em> You will master the structure behind reliable, scalable AI agents and learn the patterns needed to build complex, multi-agent systems.</p>
</li>
<li><p><em>Gemini Integration:</em> Work side-by-side with experienced developers (Expert Mentorship) to troubleshoot code in real-time.</p>
</li>
</ul>
<h4 id="heading-day-2-deployment-and-portfolio-creation"><em>DAY 2: Deployment and Portfolio Creation</em></h4>
<p>Day 2 focuses entirely on execution, ensuring you move from theory to high-velocity creation.</p>
<ul>
<li><p><em>The 9-Agent Guarantee:</em> You will architect, code, and deploy your <em>first NINE functional AI agents immediately</em>. This hands-on process solidifies your understanding of agentic systems and tool-use by creating a portfolio of working agents.</p>
</li>
<li><p><em>Deployment Mastery:</em> Learn how to deploy agents that actually solve real-world problems.</p>
</li>
<li><p><em>Networking &amp; Support:</em> Benefit from a highly focused, collaborative space designed for maximum knowledge transfer and direct peer-to-peer connection. You'll receive <em>direct developer support</em> to ensure you deploy successful agents.</p>
</li>
</ul>
<h3 id="heading-why-you-must-enroll-today"><em>WHY YOU MUST ENROLL TODAY</em></h3>
<p><em>This is your crucial follow-through to go from observer to creator</em>. This intensive workshop is designed to answer all your technical questions and ensure you leave as a master architect of Agentic AI.</p>
<p>Your $1500 investment covers <em>two full days</em> of expert-led, hands-on instruction (a significantly expanded version of the highly sought-after intensive workshop).</p>
<ul>
<li><p><em>What's Included:</em></p>
<ul>
<li><p><em>The Very Best Learning Environment</em> designed for maximum knowledge transfer.</p>
</li>
<li><p><em>Expert Mentorship</em> from experienced developers like Lead UI Architect, <em>Ady Ngom</em>, who can troubleshoot your code in real-time.</p>
</li>
<li><p><em>Direct Developer Support</em> throughout the 2 days.</p>
</li>
<li><p>Fuel for the Build: Light snacks &amp; refreshments will be provided to keep the code flowing.</p>
</li>
</ul>
</li>
</ul>
<p><em>Don't miss this opportunity to seize the future of AI!</em></p>
<p><a target="_blank" href="https://register.adyngom.com/adk-2-day-masterclass"><strong>[CLICK HERE TO REGISTER]</strong></a></p>
]]></content:encoded></item><item><title><![CDATA[Agent Developer Kit (ADK) - The Deep Dive Workshop  with Ady Ngom]]></title><description><![CDATA[When: Thursday November 20th 2025Where: DUE TO AN OVERWHELMING RESPONSE THIS EVENT IS NOW ALL VIRTUALHow to attend: [👉 Register Now for the ADK Deep Dive!]
🔥 The Build Continues!
DevFest Atlanta 2025 was just the launchpad—now it’s time for the dee...]]></description><link>https://adyngom.com/agent-developer-kit-adk-the-deep-dive-workshop-with-ady-ngom</link><guid isPermaLink="true">https://adyngom.com/agent-developer-kit-adk-the-deep-dive-workshop-with-ady-ngom</guid><category><![CDATA[ai agent development workshop]]></category><category><![CDATA[agent development kit]]></category><category><![CDATA[AI Agent Development]]></category><category><![CDATA[google adk]]></category><category><![CDATA[ai-agent]]></category><dc:creator><![CDATA[Ady Ngom]]></dc:creator><pubDate>Mon, 17 Nov 2025 01:04:14 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1763341153296/476943a3-00e4-44b5-8d71-0ad6ecbf1373.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p><strong>When:</strong> Thursday November 20th 2025<br /><strong>Where</strong>: <strong>DUE TO AN OVERWHELMING RESPONSE THIS EVENT IS NOW ALL VIRTUAL</strong><br /><strong>How to attend:</strong> <a target="_blank" href="https://register.adyngom.com/adk-fast-api-workshop">[<strong>👉 Register Now for the ADK Deep Dive!</strong>]</a></p>
<h3 id="heading-the-build-continues"><strong>🔥 The Build Continues!</strong></h3>
<p><strong>DevFest Atlanta 2025 was just the launchpad—now it’s time for the deep dive!</strong></p>
<p>The response to the Agent Developer Kit (ADK) workshop was electrifying, and we listened! If you attended the introductory session with <strong>ADY NGOM</strong> and left with more questions than answers, or if you're just ready to seriously level up your skills, this <strong>4-hour intensive, hands-on workshop</strong> is your essential next step.</p>
<p>This is the <strong>definitive answer to your still-unanswered questions</strong> on building with Google's Agent Development Kit.</p>
<h3 id="heading-what-you-will-conquer-in-4-hours"><strong>What You Will Conquer in 4 Hours:</strong></h3>
<p>We're moving beyond simple demos to focus on <strong>actionable, practical skill-building</strong>. Working directly with experienced developers, you will architect, code, and deploy your <strong>first NINE functional AI agents</strong>.</p>
<ul>
<li><p><strong>9 Agents, Zero Fluff:</strong> Dive into creating a portfolio of working agents, designed to solidify your understanding of agentic systems and tool-use.</p>
</li>
<li><p><strong>Expert Mentorship:</strong> Work side-by-side with experienced developers who can troubleshoot your code in real-time.</p>
</li>
<li><p><strong>Unpack the ADK:</strong> Gain a comprehensive, practical understanding of Google’s Agent Development Kit (ADK) and how it simplifies the creation of complex, multi-step AI workflows. Learn how to define tools, manage state, and deploy agents that actually solve problems.</p>
</li>
<li><p><strong>Architecture Deep Dive:</strong> Master the structure behind reliable, scalable AI agents and learn the patterns needed to build complex, multi-agent systems.</p>
</li>
</ul>
<h3 id="heading-why-you-must-be-there-this-is-non-negotiable"><strong>Why You MUST Be There (This is Non-Negotiable!):</strong></h3>
<p>If you are a developer, architect, or innovator <strong>alive</strong> in the current tech landscape, you understand that agentic AI is the future. This workshop transforms you from an observer to a <strong>builder</strong> of that future.</p>
<p>Forget the theoretical hang-ups; this event is entirely focused on getting you <strong>shipping functional code</strong>.</p>
<h3 id="heading-whats-included"><strong>What's Included:</strong></h3>
<ul>
<li><p><strong>The Very Best Learning Environment:</strong> A highly focused, collaborative space designed for maximum knowledge transfer and direct peer-to-peer connection.</p>
</li>
<li><p><strong>Direct Developer Support:</strong> Immediate help to get through the inevitable code roadblocks.</p>
</li>
<li><p><strong>Light Snacks &amp; Refreshments:</strong> Fuel your brain and keep the code flowing.</p>
</li>
</ul>
<p><strong>Space is severely limited to ensure a high mentor-to-attendee ratio.</strong> Secure your spot now to guarantee you don't miss this opportunity to <strong>continue the build</strong> and elevate your AI development skills dramatically.</p>
<p><a target="_blank" href="https://register.adyngom.com/adk-fast-api-workshop">[<strong>👉 Register Now for the ADK Deep Dive!</strong>]</a></p>
]]></content:encoded></item><item><title><![CDATA[Moving Zeros Code Challenge - JavaScript Data Structures and Algorithms]]></title><description><![CDATA[There are usually two variations of this challenge, the only difference being if the zeroes need to be moved to the end  (right) or start (left ) of the array. Below is the challenge as copied from the  geeksforgeeks  website:
Given an array of rando...]]></description><link>https://adyngom.com/moving-zeros-code-challenge-javascript-data-structures-and-algorithms</link><guid isPermaLink="true">https://adyngom.com/moving-zeros-code-challenge-javascript-data-structures-and-algorithms</guid><category><![CDATA[JavaScript]]></category><category><![CDATA[100DaysOfCode]]></category><category><![CDATA[data structures]]></category><category><![CDATA[algorithms]]></category><category><![CDATA[challenge]]></category><dc:creator><![CDATA[Ady Ngom]]></dc:creator><pubDate>Tue, 24 Nov 2020 18:08:32 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1605887496785/s0RTS4MHC.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>There are usually two variations of this challenge, the only difference being if the zeroes need to be moved to the end  (right) or start (left ) of the array. Below is the challenge as copied from the <strong> <a target="_blank" href="https://www.geeksforgeeks.org/move-zeroes-end-array/">geeksforgeeks</a> </strong> website:</p>
<p><strong><em>Given an array of random numbers, push all the zero’s of a given array to the end of the array.</em></strong> </p>
<p><strong><em>For example, if the given arrays is {1, 9, 8, 4, 0, 0, 2, 7, 0, 6, 0}, 
it should be changed to {1, 9, 8, 4, 2, 7, 6, 0, 0, 0, 0}.</em></strong> </p>
<p><strong><em>The order of all other elements should be same. 
Expected time complexity is O(n) and extra space is O(1).</em></strong></p>
<p>We will cover two ways of solving for this, the first a  <a class="post-section-overview" href="#brute-force-first-solution">brute force</a>  or a first best guess on a working solution, then we will tackle  <a class="post-section-overview" href="#optimized-solution-recommended-one">the recommended way</a>  to have a point of comparison.</p>
<h2 id="heading-video-here">Video here</h2>
<div class="embed-wrapper"><div class="embed-loading"><div class="loadingRow"></div><div class="loadingRow"></div></div><a class="embed-card" href="https://www.youtube.com/watch?v=CC8edj19Uiw">https://www.youtube.com/watch?v=CC8edj19Uiw</a></div>
<h2 id="heading-brute-force-first-solution">Brute Force - First solution</h2>
<p>My first intuition could be broken down into the steps below:</p>
<ol>
<li>Get the size of the current array</li>
<li>Create a second array the size of the first one and fill with zeroes</li>
<li>Filter out all zeroes from the first array which will maintain the order of the non zero items</li>
<li>Take the difference of lengths between the first array and the filtered array to get the offset index</li>
<li>If the zeroes need to be on the end of the array, fill the holder array from the start to the length of filtered array</li>
<li>If the zeroes need to be at the start, replace the items starting from the offset to the end.</li>
<li>Return the holder array</li>
</ol>
<p>Now that we have the steps, let's look it with code and hopefully make it easy to register. Let's start with the function declaration:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> moveZeroes = <span class="hljs-function">(<span class="hljs-params"> arr, dir = <span class="hljs-string">'end'</span></span>) =&gt;</span> {
    <span class="hljs-comment">// body of function here</span>
}
</code></pre>
<p>Our function expects a well formed array of digits and an optional direction parameter that defaults to 'end'. Now on to the steps for the body of the function:</p>
<ol>
<li>Get the size of the current array<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> size = arr.length;
</code></pre>
</li>
<li>Create a second array the size of the first one and fill with zeroes<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> holder = <span class="hljs-built_in">Array</span>.from({ <span class="hljs-attr">length</span>: size}, <span class="hljs-function">() =&gt;</span> <span class="hljs-number">0</span>);
</code></pre>
</li>
<li>Filter out all zeroes from the first array which will maintain the order of the non zero items<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> filtered = arr.filter( <span class="hljs-function"><span class="hljs-params">v</span> =&gt;</span> v !== <span class="hljs-number">0</span>);
</code></pre>
</li>
<li>Take the difference of lengths between the first array and the filtered array to get the offset index<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> offset = size - filtered.length;
</code></pre>
</li>
<li>If the zeroes need to be on the end of the array, fill the holder array from the start to the length the filtered array<pre><code class="lang-javascript"><span class="hljs-keyword">if</span>( dir === <span class="hljs-string">'end'</span> ) {
 filtered.forEach( <span class="hljs-function">(<span class="hljs-params">v, i</span>) =&gt;</span> holder[i] = v );   
}
</code></pre>
</li>
<li>If the zeroes need to be at the start, replace the items starting from the offset to the end.<pre><code class="lang-javascript"><span class="hljs-keyword">if</span>( dir === <span class="hljs-string">'start'</span> ) {
 filtered.forEach( <span class="hljs-function">(<span class="hljs-params">v, i</span>) =&gt;</span> holder[ i + offset] = v );
}
</code></pre>
</li>
<li>Return the holder array</li>
</ol>
<p><em>Au final</em>, we get the code below as our brute force solution:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> moveZeroes = <span class="hljs-function">(<span class="hljs-params"> arr, dir = <span class="hljs-string">'end'</span></span>) =&gt;</span> {
    <span class="hljs-keyword">const</span> size = arr.length;
    <span class="hljs-keyword">let</span> holder = <span class="hljs-built_in">Array</span>.from({ <span class="hljs-attr">length</span>: size}, <span class="hljs-function">() =&gt;</span> <span class="hljs-number">0</span>);

    <span class="hljs-keyword">const</span> filtered = arr.filter( <span class="hljs-function"><span class="hljs-params">v</span> =&gt;</span> v !== <span class="hljs-number">0</span>);
    <span class="hljs-keyword">const</span> offset = size - filtered.length;

    <span class="hljs-keyword">if</span>( dir === <span class="hljs-string">'end'</span> ) {
        filtered.forEach( <span class="hljs-function">(<span class="hljs-params">v, i</span>) =&gt;</span> holder[i] = v );
    }

    <span class="hljs-keyword">if</span> ( dir === <span class="hljs-string">'start'</span> ) {
        filtered.forEach( <span class="hljs-function">(<span class="hljs-params">v, i</span>) =&gt;</span> holder[ i + offset] = v )
    }

    <span class="hljs-keyword">return</span> holder;
}
</code></pre>
<p>And we can test it with:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> arr = [<span class="hljs-number">1</span>, <span class="hljs-number">9</span>, <span class="hljs-number">8</span>, <span class="hljs-number">4</span>, <span class="hljs-number">0</span>, <span class="hljs-number">0</span>, <span class="hljs-number">2</span>, <span class="hljs-number">7</span>, <span class="hljs-number">0</span>, <span class="hljs-number">6</span>, <span class="hljs-number">0</span>];
<span class="hljs-built_in">console</span>.log(<span class="hljs-string">'Zeroes to end: '</span>, moveZeroes(arr));
<span class="hljs-built_in">console</span>.log(<span class="hljs-string">'Zeroes to start: '</span>, moveZeroes(arr, <span class="hljs-string">'start'</span>));
</code></pre>
<p>Which outputs</p>
<pre><code><span class="hljs-attr">Zeroes to end   :</span>   [<span class="hljs-number">1</span>, <span class="hljs-number">9</span>, <span class="hljs-number">8</span>, <span class="hljs-number">4</span>, <span class="hljs-number">2</span>, <span class="hljs-number">7</span>, <span class="hljs-number">6</span>, <span class="hljs-number">0</span>, <span class="hljs-number">0</span>, <span class="hljs-number">0</span>, <span class="hljs-number">0</span>]
<span class="hljs-attr">Zeroes to start :</span>   [<span class="hljs-number">0</span>, <span class="hljs-number">0</span>, <span class="hljs-number">0</span>, <span class="hljs-number">0</span>, <span class="hljs-number">1</span>, <span class="hljs-number">9</span>, <span class="hljs-number">8</span>, <span class="hljs-number">4</span>, <span class="hljs-number">2</span>, <span class="hljs-number">7</span>, <span class="hljs-number">6</span>]
</code></pre><p>This satisfies the expected output of the challenge but, we should run an auto critique and see the many things that make our solution not so optimized:</p>
<ul>
<li>First we are creating a second array to hold the the filtered items</li>
<li>Second we create a third array then fill it with zeroes, each of those steps is an additional computation step and increase the execution time as the array grows in size</li>
<li>Lastly, we iterate and change the newly created array to place our filtered items and respect the order of the items</li>
</ul>
<p>So the big question is can we achieve the same with only the one array passed and not to have to create all this new ones and how do we swap the zeroes to an end without affecting the order.</p>
<p>The answer is of course yes and like the first solution we will start with a breakdown of the logic of the solution to hopefully help with understanding</p>
<h2 id="heading-optimized-solution-recommended-one">Optimized solution - recommended one</h2>
<p>We will operate within only one array and keep track of two indexes: a <strong>read index</strong> and a <strong>write index</strong> which both start at the same position.</p>
<p>We will use the <strong>readIndex</strong> to scan the array from end to end and skip any cell that contains a zero. </p>
<p>When we encounter a <strong>non-zero</strong>, we update the value at the <strong>writeIndex</strong> with the <strong>non-zero</strong> value then we decrement or increment the <strong>writeIndex</strong> based on which side we need to move the zeroes to.</p>
<p>If your head is spinning from reading the above steps, I have put up a visualization that might help you understand it quickly. This below shows the step by step of moving the zeroes to the left</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1606098899334/7e81Tq8Ex.gif" alt="0-viz-move-zeroes.gif" /></p>
<p>Let's translate that into code with two separate functions this time starting with the zeroes to the left.</p>
<h3 id="heading-optimized-move-zeroes-left">[Optimized] Move Zeroes Left</h3>
<p>As always we start with the function declaration</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> moveZeroesLeft = <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">arr</span>) </span>{

}
</code></pre>
<p>Then we declare two local variables to hold a <strong>writeIndex</strong> and a <strong>start</strong> position</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> writeIndex = arr.length - <span class="hljs-number">1</span>;
<span class="hljs-keyword">let</span> start = writeIndex;
</code></pre>
<p>Both indexes start at the end of the array.</p>
<p>You might've guessed from the visualization that we will run two internal loops. </p>
<p>The first loop will scan for non-zeroes with a <strong>readIndex</strong> and put the value found at the <strong>writeIndex</strong>. 
The <strong>writeIndex</strong> will decrement every time after such an operation</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">for</span>(<span class="hljs-keyword">let</span> readIndex = start; readIndex &gt;= <span class="hljs-number">0</span>; readIndex-- ) {
    <span class="hljs-keyword">if</span>( arr[readIndex] !== <span class="hljs-number">0</span>) {
        arr[writeIndex] = arr[readIndex];
        writeIndex--;
    }
}
</code></pre>
<p>The second loop will start at the beginning now and swap each value with a zero up until it reaches the <strong>writeIndex</strong> cell which also will get a zero value</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">for</span> (<span class="hljs-keyword">let</span> j = <span class="hljs-number">0</span>; j &lt;= writeIndex; j++) {
    arr[j] = <span class="hljs-number">0</span>;
}
</code></pre>
<p>To finish, we can now simply return the updated array</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">return</span> arr;
</code></pre>
<p>The complete code:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> moveZeroesLeft = <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">arr</span>) </span>{
    <span class="hljs-keyword">let</span> writeIndex = arr.length - <span class="hljs-number">1</span>;
    <span class="hljs-keyword">let</span> start = writeIndex;

    <span class="hljs-keyword">for</span>(<span class="hljs-keyword">let</span> readIndex = start; readIndex &gt;= <span class="hljs-number">0</span>; readIndex-- ) {
        <span class="hljs-keyword">if</span>( arr[readIndex] !== <span class="hljs-number">0</span>) {
            arr[writeIndex] = arr[readIndex];
            writeIndex--;
        }
    }

    <span class="hljs-keyword">for</span> (<span class="hljs-keyword">let</span> j = <span class="hljs-number">0</span>; j &lt;= writeIndex; j++) {
        arr[j] = <span class="hljs-number">0</span>;
    }

    <span class="hljs-keyword">return</span> arr;
}
</code></pre>
<p>We can verify that this works with the statements and the output below:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> arr = [<span class="hljs-number">1</span>, <span class="hljs-number">9</span>, <span class="hljs-number">8</span>, <span class="hljs-number">4</span>, <span class="hljs-number">0</span>, <span class="hljs-number">0</span>, <span class="hljs-number">2</span>, <span class="hljs-number">7</span>, <span class="hljs-number">0</span>, <span class="hljs-number">6</span>, <span class="hljs-number">0</span>];
<span class="hljs-built_in">console</span>.log(<span class="hljs-string">'\n------------ Move zeroes left --------\n'</span>);
<span class="hljs-built_in">console</span>.log(moveZeroesLeft(arr));
<span class="hljs-comment">// outputs to console</span>
[<span class="hljs-number">0</span>, <span class="hljs-number">0</span>, <span class="hljs-number">0</span>, <span class="hljs-number">0</span>, <span class="hljs-number">1</span>, <span class="hljs-number">9</span>, <span class="hljs-number">8</span>, <span class="hljs-number">4</span>, <span class="hljs-number">2</span>, <span class="hljs-number">7</span>, <span class="hljs-number">6</span>]
</code></pre>
<h3 id="heading-optimized-move-zeroes-right">[Optimized] Move Zeroes Right</h3>
<p>The code to have the zeroes at the right is following the same logic as the previous one. </p>
<p>The main difference is that the <strong>readIndex</strong> and <strong>writeIndex</strong> will start at the beginning of the array instead of the end. </p>
<p>No need for a step by step then, here is the finished code:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> moveZeroesRight = <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">arr</span>) </span>{
    <span class="hljs-keyword">let</span> writeIndex = <span class="hljs-number">0</span>;
    <span class="hljs-keyword">const</span> size = arr.length;

    <span class="hljs-keyword">for</span>(<span class="hljs-keyword">let</span> readIndex = <span class="hljs-number">0</span>; readIndex &lt; size; readIndex++) {
        <span class="hljs-keyword">if</span>(arr[readIndex] !== <span class="hljs-number">0</span>) {
            arr[writeIndex] = arr[readIndex];
            writeIndex++;
        }
    }

    <span class="hljs-keyword">for</span>(<span class="hljs-keyword">let</span> j = writeIndex; j &lt; size; j++) {
        arr[j] = <span class="hljs-number">0</span>;
    }

    <span class="hljs-keyword">return</span> arr;
}
</code></pre>
<p>We can expect and verify the zeroes to be moved to end of the array with the below statements again:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> arr = [<span class="hljs-number">1</span>, <span class="hljs-number">9</span>, <span class="hljs-number">8</span>, <span class="hljs-number">4</span>, <span class="hljs-number">0</span>, <span class="hljs-number">0</span>, <span class="hljs-number">2</span>, <span class="hljs-number">7</span>, <span class="hljs-number">0</span>, <span class="hljs-number">6</span>, <span class="hljs-number">0</span>];
<span class="hljs-built_in">console</span>.log(<span class="hljs-string">'\n------------ Move zeroes right --------\n'</span>);
<span class="hljs-built_in">console</span>.log(moveZeroesRight(arr));
<span class="hljs-comment">// outputs to console</span>
[<span class="hljs-number">1</span>, <span class="hljs-number">9</span>, <span class="hljs-number">8</span>, <span class="hljs-number">4</span>, <span class="hljs-number">2</span>, <span class="hljs-number">7</span>, <span class="hljs-number">6</span>, <span class="hljs-number">0</span>, <span class="hljs-number">0</span>, <span class="hljs-number">0</span>, <span class="hljs-number">0</span>]
</code></pre>
<h2 id="heading-conclusion">Conclusion</h2>
<p>I tried to be thorough in showing you multiple ways to solve this fun challenge. </p>
<p>I hope you enjoyed the [long] read and more importantly understand both approaches and why one is a better option than the other. </p>
<p>Share in the comments any feedback and alternate solutions and don't forget to stay tuned for more 😃</p>
]]></content:encoded></item><item><title><![CDATA[How to build a simple counter and a vending machine app with React hooks]]></title><description><![CDATA[Today I will introduce to you what many would argue is the shiniest new feature of the popular React library - React Hooks.
I personally am falling in love with the React.memo concept, but we can reserve it for another tutorial though.
We are here to...]]></description><link>https://adyngom.com/how-to-build-a-simple-counter-and-a-vending-machine-app-with-react-hooks</link><guid isPermaLink="true">https://adyngom.com/how-to-build-a-simple-counter-and-a-vending-machine-app-with-react-hooks</guid><category><![CDATA[JavaScript]]></category><category><![CDATA[React]]></category><category><![CDATA[Web Development]]></category><category><![CDATA[Frontend Development]]></category><dc:creator><![CDATA[Ady Ngom]]></dc:creator><pubDate>Mon, 08 Jul 2019 18:42:30 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1562611341630/U6ms275TJ.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Today I will introduce to you what many would argue is the shiniest new feature of the popular React library - React Hooks.</p>
<p>I personally am falling in love with the <a target="_blank" href="https://reactjs.org/docs/react-api.html#reactmemo"><strong>React.memo</strong></a> concept, but we can reserve it for another tutorial though.</p>
<p>We are here to talk about Hooks so let's get into it.</p>
<h3 id="heading-first-thing-first-what-are-hooks">First thing first what are hooks??</h3>
<p>Fair question. Components are at the heart of the React library and there are essentially two ways to write them. Either as a <strong>class base component</strong> or a <strong>functional component</strong>.</p>
<p>Prior to version <strong>16.8</strong> I believe, using the class base syntax was the only way to tap in into the <strong>component life cycle methods</strong> and also the only way to directly access the very important <strong>state</strong> object.</p>
<p>The workaround or status-quo was to wrap the functional component inside a class component and have it pass the state as <strong>props</strong>.</p>
<p>With the addition of hooks, that is no longer necessary since functional components are now literally able to "hook into" the React exposed methods such as <strong>useState</strong> and <strong>useEffect</strong> which we are going to look into extensively.</p>
<p>Now that we have that out of the way, let's see it in code</p>
<h3 id="heading-a-simple-counter">A simple counter</h3>
<p>Let's put together our example functional component. The user interface is two buttons in charge of incrementing or decrementing a count value that defaults to 0.</p>
<p>The code below is one of the ways we could go about it</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">import</span> React, { useState } <span class="hljs-keyword">from</span> <span class="hljs-string">"react"</span>;
<span class="hljs-keyword">import</span> { render } <span class="hljs-keyword">from</span> <span class="hljs-string">"react-dom"</span>;
<span class="hljs-keyword">import</span> <span class="hljs-string">"./styles.css"</span>;

<span class="hljs-keyword">const</span> Counter = <span class="hljs-function">() =&gt;</span> {
  <span class="hljs-keyword">const</span> [count, setCount] = useState(<span class="hljs-number">0</span>);
  <span class="hljs-keyword">return</span> (
    <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"counter"</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"wrapper"</span>&gt;</span> <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">header</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"counter-header"</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"header-wrapper"</span>&gt;</span> <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
        // The fun stuff
        <span class="hljs-tag">&lt;<span class="hljs-name">button</span>
          <span class="hljs-attr">className</span>=<span class="hljs-string">"cbtn"</span> <span class="hljs-attr">onClick</span>=<span class="hljs-string">{e</span> =&gt;</span> {
            if (count &gt; 0) setCount(count - 1);
          }}
        &gt;
         -
        <span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">h1</span>&gt;</span>Simple Counter <span class="hljs-tag">&lt;/<span class="hljs-name">h1</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">button</span>
          <span class="hljs-attr">className</span>=<span class="hljs-string">"cbtn"</span> <span class="hljs-attr">onClick</span>=<span class="hljs-string">{e</span> =&gt;</span> {
            setCount(count + 1);
          }}
        &gt;
        +
        <span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span>
      <span class="hljs-tag">&lt;/<span class="hljs-name">header</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">p</span> <span class="hljs-attr">className</span>=<span class="hljs-string">"count"</span>&gt;</span>{count} <span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">p</span> <span class="hljs-attr">className</span>=<span class="hljs-string">"label"</span>&gt;</span>Off the hooks!!! <span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
    <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span></span>
  );
};

render(<span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">Counter</span> /&gt;</span></span>, <span class="hljs-built_in">document</span>.getElementById(<span class="hljs-string">"root"</span>));
</code></pre>
<p>Just like we would've imported <strong>Component</strong> on the opening line, we are instead adding the <strong>useState hook</strong>. Then a destructuring like statement is used to set the internal state</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> [count, setCount] = useState(<span class="hljs-number">0</span>);
</code></pre>
<p>The first variable - <strong>count,</strong> on the construct is the <strong>value</strong> and the second <strong>setCount</strong> is the name of the function you will later use to update the value - you can call it whatever you see fit.</p>
<p>Finally, <strong>useState</strong> on the right of the statement takes what looks like an argument but is actually initial value of the state key. </p>
<p>So in plain English:</p>
<blockquote>
<p>Using the state hook, create a variable named count and associate a function named setCount that will be in charge of updating the value of it. In the meantime, set the initial value of count to 0</p>
</blockquote>
<p>We then add event listeners on the buttons and for each we make use of the <strong>setCount </strong> to update the <strong>count </strong> value accordingly</p>
<pre><code class="lang-html"> <span class="hljs-tag">&lt;<span class="hljs-name">button</span> <span class="hljs-attr">className</span>=<span class="hljs-string">"cbtn"</span> <span class="hljs-attr">onClick</span> = <span class="hljs-string">{(e)</span> =&gt;</span> { if(count&gt; 0) setCount(count - 1)}}&gt;
-
 <span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span>

 <span class="hljs-tag">&lt;<span class="hljs-name">h1</span>&gt;</span>Simple Counter <span class="hljs-tag">&lt;/<span class="hljs-name">h1</span>&gt;</span>

 <span class="hljs-tag">&lt;<span class="hljs-name">button</span> <span class="hljs-attr">className</span>=<span class="hljs-string">"cbtn"</span> <span class="hljs-attr">onClick</span> = <span class="hljs-string">{(e)</span> =&gt;</span> { setCount(count + 1)}}&gt;
+
 <span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span>
</code></pre>
<p><img src="https://techlabs28.com/wp-content/uploads/2019/07/react-counter.gif&quot;" alt="React simple counter" /></p>
<p>There you have it for a simple example :) Now let's look at something more involved that will allow us to take advantage of a few lifecycle methods inside a functional component</p>
<h3 id="heading-a-vending-machine">A Vending Machine</h3>
<p>If you have read some of my articles, you might've come across my <strong><a target="_blank" href="https://adyngom.github.io/28-relevant-js-questions/toc.html">JavaScript - 28 relevant questions series</a>.</strong></p>
<p>One of the challenges is to build a "simplified" Vending Machine.</p>
<p>You can read more about and definitely take a stab at it following the link below.</p>
<p><a target="_blank" href="https://adyngom.github.io/28-relevant-js-questions/6-vending-machine.html"># 6 Vending Machine - 
Bob runs a successful Vending Machine business. He wants to add an interface ...</a></p>
<p>One of the solution that I have devised for it uses a function as a module. We will import that inside a React functional component and use it to update various states of the application</p>
<p>The complete code can be found here: <a target="_blank" href="https://stackblitz.com/edit/react-ruhwvv&quot;">React vending machine with hooks</a> but let's quickly go step by step. </p>
<p>Let's first look at our Vending Machine module</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">VendingMachine</span>(<span class="hljs-params">inventory</span>) </span>{
  <span class="hljs-keyword">var</span> drinks = inventory || <span class="hljs-literal">null</span>;

  <span class="hljs-keyword">if</span> (!drinks) {
    <span class="hljs-keyword">throw</span> <span class="hljs-keyword">new</span> <span class="hljs-built_in">Error</span>(<span class="hljs-string">"No inventory: Cannot add a new VM"</span>);
  }

  <span class="hljs-keyword">const</span> drinksKeys = <span class="hljs-built_in">Object</span>.keys(drinks);

  <span class="hljs-keyword">var</span> sale = <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">pid</span>) </span>{
    <span class="hljs-keyword">if</span> (!drinks[pid]) {
      <span class="hljs-keyword">return</span>;
    }

    <span class="hljs-keyword">if</span> (drinks[pid].stock &gt; <span class="hljs-number">0</span>) {
      drinks[pid].stock--;
      <span class="hljs-keyword">return</span> <span class="hljs-string">`1 <span class="hljs-subst">${drinks[pid].name}</span> - Thank you, come again!!`</span>;
    } <span class="hljs-keyword">else</span> {
      drinks[pid].stock = <span class="hljs-number">0</span>;
      <span class="hljs-keyword">return</span> <span class="hljs-string">` <span class="hljs-subst">${drinks[pid].name}</span> is out of stock :( Come back tomorrow`</span>;
    }
  };

  <span class="hljs-keyword">var</span> stock = <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params"></span>) </span>{
    <span class="hljs-keyword">const</span> total = drinksKeys.reduce(<span class="hljs-function">(<span class="hljs-params">c, n</span>) =&gt;</span> c + drinks[n].stock, <span class="hljs-number">0</span>);
    <span class="hljs-keyword">return</span> total;
  };

  <span class="hljs-keyword">return</span> <span class="hljs-built_in">Object</span>.freeze({ sale, stock });
}
</code></pre>
<p>The Vending Machine exposes two public methods <strong>sale </strong> and <strong>stock. </strong> It also needs to be passed an inventory object that looks like this</p>
<pre><code class="lang-json">{
  <span class="hljs-attr">"1"</span>: {
    <span class="hljs-attr">"name"</span>: <span class="hljs-string">"Mango Juice"</span>,
    <span class="hljs-attr">"stock"</span>: <span class="hljs-number">2</span>
  },
  <span class="hljs-attr">"2"</span>: {
    <span class="hljs-attr">"name"</span>: <span class="hljs-string">"Banana Smoothies"</span>,
    <span class="hljs-attr">"stock"</span>: <span class="hljs-number">2</span>
  },
  <span class="hljs-attr">"3"</span>: {
    <span class="hljs-attr">"name"</span>: <span class="hljs-string">"Guava Mix"</span>,
    <span class="hljs-attr">"stock"</span>: <span class="hljs-number">1</span>
  },
  <span class="hljs-attr">"4"</span>: {
    <span class="hljs-attr">"name"</span>: <span class="hljs-string">"Citrus Blend"</span>,
    <span class="hljs-attr">"stock"</span>: <span class="hljs-number">3</span>
  }
}
</code></pre>
<p>Let's assume that this object is coming from an HTTP call. In a class based component scenario, we would have probably use the <strong>ComponentDidMount</strong> lifecycle method to make the request and update the state. In the case of the functional component we will hook into the <strong>useEffect</strong> method to do so.</p>
<p>Now let's set a few rules/goals that we want our React component to do:</p>
<ul>
<li>The UI should only render when the VM has been properly set with a valid inventory</li>
<li>The component will need to make an HTTP request call to get that initial inventory</li>
<li>The UI will show a loading state until it is ready to render the VM</li>
<li>Once loaded, each drink from the inventory will be represented by a button.</li>
<li>Clicking on any of the drinks button will trigger the VM sale method call and displaying either a successful sales or an out of stock message</li>
<li>The UI will display the starting stock and that number will be updated each time a successful sale is made</li>
</ul>
<h4 id="heading-1-initial-setup">1. Initial setup</h4>
<p>Let's put the initial wrapper for our little app</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">import</span> React, { Fragment, useState, useEffect } <span class="hljs-keyword">from</span> <span class="hljs-string">"react"</span>;
<span class="hljs-keyword">import</span> { render } <span class="hljs-keyword">from</span> <span class="hljs-string">"react-dom"</span>;
<span class="hljs-keyword">import</span> VendingMachine <span class="hljs-keyword">from</span> <span class="hljs-string">"./FunModules/VendingMachine"</span>;

<span class="hljs-keyword">const</span> LocalVM = <span class="hljs-function">() =&gt;</span> {
  <span class="hljs-comment">// functional logic here</span>
  <span class="hljs-keyword">return</span> <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">Fragment</span>&gt;</span>// view logic here<span class="hljs-tag">&lt;/<span class="hljs-name">Fragment</span>&gt;</span></span>;
};

render(<span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">LocalVM</span> /&gt;</span></span>, <span class="hljs-built_in">document</span>.getElementById(<span class="hljs-string">"root"</span>));
</code></pre>
<p>As we did with the Simple Counter, we are importing <strong>useState</strong> but also <strong>useEffect</strong> and <strong><a target="_blank" href="https://reactjs.org/docs/fragments.html">Fragment</a></strong>.</p>
<p>My personal like on <strong>Fragment</strong> is how easy it let us choose if we want add additional tags to the DOM or not - very powerful.</p>
<p>The last import line simply get us our <strong>VM module</strong>. Whether I work on an Angular or React project, I usually create a folder of utilities with pure Vanilla JS that are easy to reuse in either framework or library.</p>
<h4 id="heading-2-declaring-our-states">2. Declaring our State(s)</h4>
<p>The state syntax in a class component is a key value object. We could definitely repeat that same pattern here, but what it is very interesting and flexible with the <strong>useState </strong> hook is that you could set each individual state you want to track.</p>
<p>Let's illustrate that in our functional logic section</p>
<pre><code class="lang-javascript"><span class="hljs-comment">// functional logic here</span>
<span class="hljs-keyword">const</span> [vm, setVM] = useState({});
<span class="hljs-keyword">const</span> [loading, isLoading] = useState(<span class="hljs-literal">true</span>);
<span class="hljs-keyword">const</span> [data, setData] = useState({});
<span class="hljs-keyword">const</span> [message, setMessage] = useState(<span class="hljs-string">"..."</span>);
<span class="hljs-keyword">const</span> [stock, setStock] = useState(<span class="hljs-number">0</span>);
</code></pre>
<p>I really like how this reads, it is almost self-documenting and probably easy to figure out what each of these does. Let me know if you don't agree :) </p>
<p>To be crystal clear though, this is what each will handle:</p>
<ol>
<li><strong>vm</strong> will be the local instance of our Vending Machine and starts as an empty object</li>
<li><strong>loading</strong> is a boolean that defaults to true and will be false when the VM UI is ready to be rendered</li>
<li><strong>data</strong> is the inventory object that we will get back from our HTTP request call</li>
<li><strong>message</strong> is going to be use to display a success or out of stock status</li>
<li>and finally <strong>stock</strong> will display the initial count of the total inventory of drinks and update that number anytime a purchase is made</li>
</ol>
<h4 id="heading-3-requesting-the-inventory">3. Requesting the inventory</h4>
<p>Now comes the fun part where we get to take advantage of <strong>useEffect</strong> to wrap around our HTTP request.</p>
<pre><code class="lang-javascript">useEffect(
  <span class="hljs-function">() =&gt;</span> {
    fetch(<span class="hljs-string">"https://my-json-server.typicode.com/adyngom/vmapi/db"</span>)
      .then(<span class="hljs-function"><span class="hljs-params">response</span> =&gt;</span> response.json())
      .then(<span class="hljs-function"><span class="hljs-params">data</span> =&gt;</span> {
        setData(data);
        setVM(VendingMachine(data));
        isLoading(<span class="hljs-literal">false</span>);
      });
    <span class="hljs-comment">// return function statement when component unmounts</span>
  },
  [] <span class="hljs-comment">// empty array as second argument to ensure the effect runs once</span>
);
</code></pre>
<p>The hook wraps our <strong>fetch</strong> call and once we get a response, <strong>setData</strong> updates the <strong>data</strong> state and <strong>setVM</strong> attaches an instance of the VendingMachine with the new inventory to our <strong>vm</strong> state.</p>
<p>Please note that we haven't added error handling on our <strong>fetch</strong> call for brevity.</p>
<p>The code adds two very important comments that touch on lifecycle management. It is extremely important to understand that <strong>useEffect</strong> is the equivalent of <strong>ComponentDidMount, ComponentDidUpdate and ComponentWillUnmount</strong> lifecycle methods combined</p>
<p>If we don't pass the empty array as a second argument, the <strong>"effect"</strong> will run every single time the component gets updated. </p>
<p>That would be great for certain use cases, but in this particular one , we would be telling our component to go fetch and setup a Vending Machine every single time something gets updated in the UI.</p>
<p>The empty array as second argument helps us prevent that by making it a <strong>one and done deal.</strong></p>
<p>The commented out <strong>return function statement</strong> is a placeholder of where you would put your code if you wanted to do operations when the component <strong>unmounts</strong>.</p>
<p>Think about use cases such as removing event listeners, unsubscribing from an observable etc...</p>
<p>I highly recommend to read more about those on the <a target="_blank" href="https://reactjs.org/docs/hooks-effect.html">React documentation page</a>.</p>
<h4 id="heading-4-rendering-the-ui-at-last">4. Rendering the UI at last</h4>
<p>Now that most of our logic is taken care of, we can focus on putting the meat of the component on the page. If we have received <strong>data </strong> from our fetch call, this will mean that the <strong>loading</strong> state has finished and is now false.</p>
<p>Using the ternary operator, we could compose our view like below</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">return</span> (
  <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">Fragment</span>&gt;</span>
    {loading ? (
      <span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span>loading... <span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
    ) : (
      <span class="hljs-tag">&lt;<span class="hljs-name">div</span>&gt;</span>// loading is done put the VM interface here<span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
    )}
  <span class="hljs-tag">&lt;/<span class="hljs-name">Fragment</span>&gt;</span></span>
);
</code></pre>
<p>Let's also add two helpers function just before the <strong>useEffect</strong> block that will allow for a clean way to call on the <strong>sale</strong> and <strong>stock</strong> methods of the VM</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> sale = <span class="hljs-function"><span class="hljs-params">pid</span> =&gt;</span> {
  <span class="hljs-keyword">return</span> vm.sale(pid);
};

<span class="hljs-keyword">const</span> getStock = <span class="hljs-function">() =&gt;</span> {
  <span class="hljs-keyword">return</span> vm.stock();
};
</code></pre>
<p>With everything in place, let's add the final piece of the UI inside the falsy section
of the ternary statement</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">return</span> (
  <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">Fragment</span>&gt;</span>
    {loading ? (
      <span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span>loading... <span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
    ) : (
      <span class="hljs-tag">&lt;<span class="hljs-name">div</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">h3</span>&gt;</span>Pick a fresh drink and enjoy <span class="hljs-tag">&lt;/<span class="hljs-name">h3</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span>{message} <span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">br</span> /&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">div</span>&gt;</span>
          {Object.keys(data).map(d =&gt; {
            return (
              <span class="hljs-tag">&lt;<span class="hljs-name">button</span>
                <span class="hljs-attr">key</span>=<span class="hljs-string">{d}</span>
                <span class="hljs-attr">id</span>=<span class="hljs-string">{d}</span>
                <span class="hljs-attr">onClick</span>=<span class="hljs-string">{e</span> =&gt;</span> {
                  setMessage(sale(e.target.id));
                }}
              &gt;
                {data[d].name}{" "}
              <span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span>
            );
          })}
          <span class="hljs-tag">&lt;<span class="hljs-name">br</span> /&gt;</span> <span class="hljs-tag">&lt;<span class="hljs-name">br</span> /&gt;</span>
          <span class="hljs-tag">&lt;<span class="hljs-name">small</span>&gt;</span>VM current stock: {getStock()} <span class="hljs-tag">&lt;/<span class="hljs-name">small</span>&gt;</span>
        <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
      <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
    )}
  <span class="hljs-tag">&lt;/<span class="hljs-name">Fragment</span>&gt;</span></span>
);
</code></pre>
<p>So if we are going from top to bottom on the last block we are essentially:</p>
<ul>
<li>Putting a reactive <strong>message</strong> string. This gets updated anytime we click on one the buttons which come next</li>
<li>Using the <strong>data</strong> object we cycle through the <strong>keys</strong> and dynamically build our buttons UI.</li>
<li>Each button gets an event listener attached to it and will pass the purchased id or <strong>pid</strong> to the local <strong>sale</strong> function.</li>
<li>The action is wrapped in a <strong>setMessage</strong> call that updates our <strong>message</strong> string with proper success or out of stock string</li>
<li>Finally <strong>getStock</strong> will be called initially and anytime the component updates to give the updated value of the stock count</li>
</ul>
<h4 id="heading-5-lets-see-it-in-action">5. Let's see it in action</h4>
<p><img src="https://techlabs28.com/wp-content/uploads/2019/07/react-vm-compressor.gif" alt="react vending machine" /></p>
<p>And if you do have the <strong><a target="_blank" href="https://chrome.google.com/webstore/detail/react-developer-tools/fmkadmapgofadopljbjfkapdkoienihi?hl=en">React Developer Tools</a></strong> extension installed here is a very slick representation of our UI inside the React DOM</p>
<p><img src="https://adyngom.com/wp-content/uploads/2019/07/screams-2019-07-05-at-8.30.26-PM-1024x576.jpg" alt="Local Vending Machine in React DOM With the state and effect hooks" /></p>
<h3 id="heading-conclusion">Conclusion</h3>
<p>I've warned you or at least I've tried in the title to tell you that this was going to be lengthy. If you've made it this far though, I hope that like myself you have learned a thing or two about this fascinating way of composing slick UIs with the React library.</p>
<p>The <strong>effect</strong> and <strong>state</strong> hooks, are most likely to be the most prominent ones for many of the use cases in a functional component. But don't cut yourself short by limiting yourself to those two.</p>
<p>I cannot recommend enough this gem of an article by <strong><a target="_blank" href="https://blog.bitsrc.io/@aayush1408">Aayush Jaiswal</a></strong>: 
<a target="_blank" href="https://blog.bitsrc.io/10-react-custom-hooks-you-should-have-in-your-toolbox-aa27d3f5564d">10 React Hooks you Should Have in Your Toolbox</a></p>
<p><strong><a target="_blank" href="https://antjanus.com/about-aj/">Antonin Januska</a></strong> has also put together a nice Hooks cheat sheet:
<a target="_blank" href="https://antjanus.com/blog/web-development-tutorials/front-end-development/the-definitive-react-hooks-cheatsheet">The Definitive React Hooks Cheatsheet</a></p>
<p>If you create bits of reusable code, you could definitely take a stab at creating some custom hooks and share with the rest of us. The React docs are surely a great place to start:
<a target="_blank" href="https://reactjs.org/docs/hooks-custom.html">Building Your Own Hooks</a></p>
<p>In the end, don't forget to pace yourself. Some are pretty intuitive and straightforward and some might take a few head scratches.</p>
<p>Thanks for reading this far and don't forget to "hook" a few friends up by sharing the article ;)</p>
]]></content:encoded></item><item><title><![CDATA[[JavaScript] - How to craft intuitive and self-documenting code]]></title><description><![CDATA[As a developer you probably spend more time reading code than actually writing it. Besides your regular outputs and refactors, think about the amount of time you spend on reading tutorials, documentations, reviewing a pull request, checking the lates...]]></description><link>https://adyngom.com/javascript-how-to-craft-intuitive-and-self-documenting-code</link><guid isPermaLink="true">https://adyngom.com/javascript-how-to-craft-intuitive-and-self-documenting-code</guid><category><![CDATA[JavaScript]]></category><category><![CDATA[clean code]]></category><category><![CDATA[Web Development]]></category><category><![CDATA[software development]]></category><dc:creator><![CDATA[Ady Ngom]]></dc:creator><pubDate>Mon, 10 Jun 2019 18:13:09 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1560165621261/e1O7D622C.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>As a developer you probably spend more time reading code than actually writing it. Besides your regular outputs and refactors, think about the amount of time you spend on reading tutorials, documentations, reviewing a pull request, checking the latest cool repos on Github, maintaining a project etc…, the list goes on.</p>
<p>Unfortunately, reading does not necessarily translate into understanding. 
I’m here to bet that one the main reasons a codebase or project does not get adoption or gets abandoned is simply because it requires too much brain processing power and put simply is not intuitive.</p>
<p>Many in western cultures are familiar with the 5 second rule when it comes to food, I know some who count a very slow 5 in that predicament :).</p>
<p>When it comes to code though, John Papa rightfully states that:</p>
<blockquote>
<p>If you can’t understand the code in 5 seconds, there is probably a smell, there is probably an idea that you should probably refactor.
__ John Papa — Readable Code</p>
</blockquote>
<p>So to put it in perspective, let me:</p>
<ul>
<li>First run you through a practical use case of a code refactor.</li>
<li>Then we can discuss the added value and benefits it could provide and finally</li>
<li>Share a few useful resources that have been very helpful in this “clean code” quest</li>
</ul>
<p>If you are a seasoned clean coder, we hope you can help us further improve by sharing some cool tips and resources on the subject in the comments.</p>
<h2 id="heading-a-simple-user-story">A “simple” user story</h2>
<p>Given a list of hotels, please select those that are located in the US and provide the filtered list with a properly formatted phone number. Below is a sample of the list of hotels.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> hotels = [
    {
     <span class="hljs-attr">name</span>: <span class="hljs-string">"Panthers Alley"</span>,
     <span class="hljs-attr">country</span>: <span class="hljs-string">"Wakanda"</span>,
     <span class="hljs-attr">address</span>: <span class="hljs-string">"123 Best Luck Finding, 3 Rivers, Wakanda"</span>,
     <span class="hljs-attr">phone</span>: <span class="hljs-string">"5551790871"</span>
    },
    {
     <span class="hljs-attr">name</span>: <span class="hljs-string">"The Golden Thread"</span>,
     <span class="hljs-attr">country</span>: <span class="hljs-string">"USA"</span>,
     <span class="hljs-attr">address</span>: <span class="hljs-string">"5 Maple Street, Los Angeles, CA, 90000"</span>,
     <span class="hljs-attr">phone</span>: <span class="hljs-string">"2125552345"</span>
    },
    {
     <span class="hljs-attr">name</span>: <span class="hljs-string">"12 Crowns"</span>,
     <span class="hljs-attr">country</span>: <span class="hljs-string">"Japan"</span>,
     <span class="hljs-attr">address</span>: <span class="hljs-string">"36 Wide Alley Blvd, Tokyo"</span>,
     <span class="hljs-attr">phone</span>: <span class="hljs-string">"5558725910"</span>
    },
    {
     <span class="hljs-attr">name</span>: <span class="hljs-string">"Petit Paris"</span>,
     <span class="hljs-attr">country</span>: <span class="hljs-string">"usa"</span>,
     <span class="hljs-attr">address</span>: <span class="hljs-string">"3669 Elm Street, New York, 30000"</span>,
     <span class="hljs-attr">phone</span>: <span class="hljs-string">"7075559087"</span>
    },
    {
     <span class="hljs-attr">name</span>: <span class="hljs-string">"The Empress Lounge"</span>,
     <span class="hljs-attr">country</span>: <span class="hljs-string">"USA"</span>,
     <span class="hljs-attr">address</span>: <span class="hljs-string">"1 Kings Place, Atlanta, GA, 30000"</span>,
     <span class="hljs-attr">phone</span>: <span class="hljs-string">"6785553125"</span>
    }
];
</code></pre>
<p>If you are able to read the above and understand without a squint what’s going on in 5 seconds or less, I bow to you 🙂</p>
<p>To be fair though there are a lot of good in the proposed solution such as:</p>
<ul>
<li>A very descriptive choice on the naming of the constant USHotels. This implicitly indicates the type of value it will hold which is likely to be a list of hotels in the US.</li>
<li>The use of map and filter to extract and transform the result to a new set, leaving the original unchanged or in more technical terms help avoid mutating the original object.</li>
<li>Map and filter also allow for a more declarative coding style rather than the imperative that would’ve been unavoidable with the for or forEach loops.</li>
</ul>
<p>If you want to learn more about <strong>imperative vs declarative</strong>, do yourself a favor and read this great piece from <strong>Tyler McGinnis</strong>: <a target="_blank" href="https://tylermcginnis.com/imperative-vs-declarative-programming/">Imperative vs Declarative Programming</a></p>
<p>In short, declarative is more concerned about the <strong>WHAT</strong> whereas imperative is explicit on the <strong>HOW</strong>.</p>
<p>This point us to the first area of what might need revision in our solution — the map block is too verbose and is a deep dive into <strong>HOW</strong> to transform an unformatted number to the US standard.</p>
<p>In our refactoring effort we will create a set of specialized units — read functions, that will help us ease in reading and understanding at first glance but also will have the side effect of creating reusable code.</p>
<p>I personally call this the <strong>“Toolify” step</strong> — a cool made up word 😉 Feel free to propose something else. I’m listening.</p>
<p><img src="https://thepracticaldev.s3.amazonaws.com/i/gq4v6wl9ryhnf2m44b23.jpeg" alt="Toolify: turn your code into small units of specialization" /></p>
<h2 id="heading-lets-abstract-and-conquer">Let’s abstract and conquer</h2>
<p>The map block is lengthy and will be the bulk of our refactor but let’s start with the filter step.</p>
<p>Let’s first create a helper function named <strong>propEquals</strong> which will only worry about if a property on an <strong>object x</strong> is equal to a <strong>value y</strong>.</p>
<p>Feel free to make the name more descriptive if it is not obvious to you. What is important is the name carries an implicit return type.</p>
<p>It’s almost obvious that it will return a boolean.</p>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">propEquals</span>(<span class="hljs-params">key, value, matchCase = false</span>) </span>{
 <span class="hljs-keyword">return</span> <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">obj</span>) </span>{
   <span class="hljs-keyword">return</span> (!matchCase) ? obj[key] === value 
         : obj[key].toLowerCase() === value.toLowerCase();
   }
}
</code></pre>
<p><strong>propEquals</strong> is generic enough to look up any key / value pair against any object. For example if we want to know if the first object in the hotels array is Wakanda, we could call it like this:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> IsWakanda = propEquals(‘country’, ‘Wakanda’)(hotels[<span class="hljs-number">0</span>]);
<span class="hljs-built_in">console</span>.log(IsWakanda); <span class="hljs-comment">// will output true</span>
</code></pre>
<p>Now let’s add a more specific function that will only target the US countries.</p>
<p>Using the outer function of <strong>propEquals</strong>, we can <strong>“fix” the arguments values</strong> to always default to the US. Let’s name this new functionality <strong>isUSCountry</strong>.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> isUSCountry = propEquals.call(<span class="hljs-literal">null</span>, ‘country’, ‘USA’, <span class="hljs-literal">true</span>);
</code></pre>
<p>In plain English, we could say that <strong>isUSCountry</strong> derives from <strong>propEquals</strong> and set the default values of the parent function to:</p>
<ul>
<li>country as key,</li>
<li>USA as value,</li>
<li>and want to select either lower or uppercase values of the string USA.</li>
</ul>
<p>In “simpler” technical terms, <strong>isUSCountry</strong> is a <strong>composition</strong> of <strong>propEquals</strong>.</p>
<p>Putting it to use will give us a very nice and intuitive syntax:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> USHotels = hotels.filter(isUSCountry);
<span class="hljs-built_in">console</span>.table(USHotels);
</code></pre>
<p>And below is the output of the filtered array</p>
<pre><code class="lang-javascript">[
    {
      <span class="hljs-string">"name"</span>: <span class="hljs-string">"The Golden Thread"</span>,
      <span class="hljs-string">"country"</span>: <span class="hljs-string">"USA"</span>,
      <span class="hljs-string">"address"</span>: <span class="hljs-string">"5 Maple Street, Los Angeles, CA, 90000"</span>,
      <span class="hljs-string">"phone"</span>: <span class="hljs-string">"2125552345"</span>
    },
    {
      <span class="hljs-string">"name"</span>: <span class="hljs-string">"Petit Paris"</span>,
      <span class="hljs-string">"country"</span>: <span class="hljs-string">"usa"</span>,
      <span class="hljs-string">"address"</span>: <span class="hljs-string">"3669 Elm Street, New York, 30000"</span>,
      <span class="hljs-string">"phone"</span>: <span class="hljs-string">"7075559087"</span>
    },
    {
      <span class="hljs-string">"name"</span>: <span class="hljs-string">"The Empress Lounge"</span>,
      <span class="hljs-string">"country"</span>: <span class="hljs-string">"USA"</span>,
      <span class="hljs-string">"address"</span>: <span class="hljs-string">"1 Kings Place, Atlanta, GA, 30000"</span>,
      <span class="hljs-string">"phone"</span>: <span class="hljs-string">"6785553125"</span>
    }
  ]
</code></pre>
<p>This syntax where <strong>USHotels</strong> construct is not explicitly specifying any arguments and just the function reference, is called <strong>tacit programming or point free composition</strong></p>
<h2 id="heading-the-more-helpers-the-merrier">The more helpers the merrier</h2>
<p>Now that we are done with the filter part, let’s attack the transform part or map with the same approach.</p>
<p>First let’s extract the phone formatting functionality an decouple it from the fact that it is always tied to an object.</p>
<p>We should be able to format a number whether it is part of an object or not.</p>
<p>So below we now have our <strong>USPhoneFormat</strong> function:</p>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">UPhoneFormat</span>(<span class="hljs-params">tel</span>) </span>{
    <span class="hljs-keyword">let</span> area, prefix, line;
    area = tel.substr(<span class="hljs-number">0</span>, <span class="hljs-number">3</span>);
    prefix = tel.substr(<span class="hljs-number">3</span>, <span class="hljs-number">3</span>);
    line = tel.substr(<span class="hljs-number">6</span>, <span class="hljs-number">4</span>);
    <span class="hljs-keyword">const</span> formatted = <span class="hljs-string">`(<span class="hljs-subst">${area}</span>) <span class="hljs-subst">${prefix}</span> <span class="hljs-subst">${line}</span>`</span>;
    <span class="hljs-keyword">return</span> formatted;
}
</code></pre>
<p>Now let’s add our final helper <strong>transformProp</strong>. It will basically take a key and a transform function and apply the value transformation on a given object.</p>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">transformProp</span>(<span class="hljs-params">key, fn</span>) </span>{
   <span class="hljs-keyword">return</span> <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">obj</span>) </span>{
     <span class="hljs-keyword">return</span> {…obj, [key]: fn.call(<span class="hljs-literal">null</span>, obj[key]) };
   }
}
</code></pre>
<p>Now following the same logic we did with <strong>isUSCountry</strong>, we can “compose” a more specific functionality that only handles phone number formatting</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> formatPhone = transformProp.call(<span class="hljs-literal">null</span>, ‘phone’, UPhoneFormat);
</code></pre>
<h2 id="heading-the-big-payoff">The big payoff</h2>
<p>Now that we have all of our “tools” in place, we can finally revise our original syntax to just this “above the fold”:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> USHotels = hotels.filter(isUSCountry).map(formatPhone);
<span class="hljs-comment">//add all the functions below the fold or better yet use imports</span>
</code></pre>
<p>Logging <strong>USHotels</strong> to the console will output the following:</p>
<pre><code class="lang-javascript">[
 {
 “name”: “The Golden Thread”,
 “country”: “USA”,
 “address”: “<span class="hljs-number">5</span> Maple Street, Los Angeles, CA, <span class="hljs-number">90000</span>”,
 “phone”: “(<span class="hljs-number">212</span>) <span class="hljs-number">555</span> <span class="hljs-number">2345</span>”
 },
 {
 “name”: “Petit Paris”,
 “country”: “usa”,
 “address”: “<span class="hljs-number">3669</span> Elm Street, New York, <span class="hljs-number">30000</span>”,
 “phone”: “(<span class="hljs-number">707</span>) <span class="hljs-number">555</span> <span class="hljs-number">9087</span>”
 },
 {
 “name”: “The Empress Lounge”,
 “country”: “USA”,
 “address”: “<span class="hljs-number">1</span> Kings Place, Atlanta, GA, <span class="hljs-number">30000</span>”,
 “phone”: “(<span class="hljs-number">678</span>) <span class="hljs-number">555</span> <span class="hljs-number">3125</span>”
 }
]
</code></pre>
<p>Some might scratch their heads right now thinking “that’s an awful lot of steps to essentially get the same result. What do we gain from this?” I’m glad you asked.</p>
<p>The true gain can be summed up in what I called the S.C.R.E.A.M.S principle. Using it, I try to always ensure that my code is:</p>
<ul>
<li><strong>S</strong>elf-documenting — hopefully this is an obvious one</li>
<li><strong>C</strong>omposable — made up word but gives you the idea</li>
<li><strong>R</strong>eadable — for human first and minified next for machines</li>
<li><strong>E</strong>loquent — subjective but you define what is and stick with it</li>
<li><strong>A</strong>bstraction layer — add it wherever it makes sense</li>
<li><strong>M</strong>aintainable — small units are easy to test</li>
<li><strong>S</strong>calable — separate and generic functions are easy to reuse</li>
</ul>
<h2 id="heading-in-closing">In closing</h2>
<p>I have honestly started to make that extra “craft” effort in the past few months and I can admit that it was a very, very slow start.</p>
<p>If that is something that might be of interest to you, I suggest to start with small refactors.</p>
<p>Using a combination of <strong>map, filter, reduce</strong> and <strong>bind, call, apply</strong> is your Swiss-knife that can carry you a long way and is one of the routes that will help in producing “clean-code” in JavaScript.</p>
<p>If you are convinced, it’s now time to craft some code that S.C.R.E.A.M.S!! 🙂</p>
<h2 id="heading-a-few-resources">A few resources</h2>
<p><strong>From the master himself — bookmark it!!!</strong>
<a target="_blank" href="https://speakerdeck.com/johnpapa/readable-code">Readable Code</a></p>
<p><strong>An oldie but still a goodie</strong>
<a target="_blank" href="https://javascriptissexy.com/javascript-apply-call-and-bind-methods-are-essential-for-javascript-professionals">JavaScript Apply, Call and Bind Methods Are Essential for JavaScript Professionals</a></p>
<p><strong>Can’t thank <a target="_blank" href="https://www.freecodecamp.org/news/author/cristiansalcescu/">Cristian Salcescu</a> enough for this great piece</strong>
<a target="_blank" href="https://www.freecodecamp.org/news/how-point-free-composition-will-make-you-a-better-functional-programmer-33dcb910303a/">How point-free composition will make you a better functional programmer</a></p>
<hr />
<p>Hello I’m Ady Ngom. Professionally I carry the fancy title of Solutions Designer / JS Tech Lead. At the core though, I’m just a passionate about all things JavaScript and the Front-end ecosystem. Connect with me on <a target="_blank" href="https://twitter.com/adyngom">Twitter</a>, <a target="_blank" href="https://www.linkedin.com/in/adyngom/">LinkedIn</a> and visit my blog <a target="_blank" href="https://adyngom.com/">adyngom.com</a></p>
]]></content:encoded></item><item><title><![CDATA[How to approach solving a challenge during a coding interview]]></title><description><![CDATA[Like many things in life, mastery requires practice and the coding interview is no exception. Often times though, the focus is on trying to find the best solution from the get go rather than the approach on how to iterate and maybe get there.
The mos...]]></description><link>https://adyngom.com/how-to-approach-solving-a-challenge-during-a-coding-interview</link><guid isPermaLink="true">https://adyngom.com/how-to-approach-solving-a-challenge-during-a-coding-interview</guid><category><![CDATA[JavaScript]]></category><category><![CDATA[Career]]></category><category><![CDATA[Interviews]]></category><category><![CDATA[Web Development]]></category><category><![CDATA[software development]]></category><dc:creator><![CDATA[Ady Ngom]]></dc:creator><pubDate>Mon, 20 May 2019 10:48:57 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1558349232750/ivY9zFiKd.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Like many things in life, mastery requires practice and the coding interview is no exception. Often times though, the focus is on trying to find the best solution from the get go rather than the approach on how to iterate and maybe get there.</p>
<p>The most important part, in my humble opinion is to get it right first. In your normal coding life you would rarely, if ever, be able to produce "perfect" code without first going through a set of iterations. </p>
<p>The approach during the coding interview should not differ and if played well should help you score invaluable points into demonstrating your problem solving skills. </p>
<p>I'm going to walk you through of what could be an actual conversation between you and an interviewer if you were asked to solve for the [in]famous FizzBuzz challenge.</p>
<h3 id="heading-the-challenge">The challenge</h3>
<p>Write a program that prints the numbers from 1 to 100. But for multiples of three print Fizz instead of the number and for the multiples of five print Buzz. For numbers which are multiples of both three and five print FizzBuzz</p>
<h3 id="heading-the-context">The context</h3>
<p>The FizzBuzz challenge is not specific to JavaScript and has been part of the coding interview process in almost every programing language. It is usually a quick check to assess the candidate basic programing instincts, but can also be turned in an assessment for in depth knowledge if the interviewer decides to do so.
It is usually part of a light weight first technical interview done while screen sharing. It is also a favorite from a non JavaScript programmer to ask and quickly gauge your technical knowledge and approach.</p>
<p>In a Javascript context familiarity with some or all the following concepts are expected to be demonstrated:</p>
<ul>
<li>Logical operators</li>
<li>Looping</li>
<li>Falsy values</li>
<li>Ternary operator</li>
<li>Type coercion</li>
</ul>
<h3 id="heading-the-approach">The approach</h3>
<p>As with any problems that you might encounter, even those that seem familiar, a good read and break down to small pieces is a must. Be clear to the interviewer that you need 3 to 5 minutes to read it calmly and propose a rewrite of your understanding. </p>
<p>If you are comfortable doing that part out loud, that's even better. For example this is how I might go for the rewrite:</p>
<ul>
<li>So log to the console numbers from 1 to 100 - I'm going to need a loop</li>
<li>For multiple of 3 instead of the number output the string 'Fizz'</li>
<li>Do the same for multiples of 5 with the output being 'Buzz'</li>
<li>In the case the number is a multiple of both 3 and 5 then output 'FizzBuzz' - how to check if a is a multiple of b??</li>
<li>If all the above cases fail then just output the number as is</li>
</ul>
<p>I would probably ask to the interviewer if I should worry about edge cases or bad inputs. It is usually implied that the input will be correct and edge cases might not be necessary. The fact that you ask though, adds a touch of eloquence to your problem-solving approach.</p>
<h2 id="heading-the-solutions">The solution(s)</h2>
<p>One thing that is key and is worthy of practice is walking the person through your steps as you are building the solution during the interview. Start with the obvious, you will probably need a function or class as your primary construct. Start there and always think of the K.I.A.S.S.A.P :) principle - Keep It As Stupid Simple As Possible</p>
<h3 id="heading-first-step">First step</h3>
<pre><code class="lang-javascript"><span class="hljs-comment">// comments are me talking out loud</span>
<span class="hljs-comment">// let's build the function structure</span>
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">fizzBuzz</span>(<span class="hljs-params"> start = <span class="hljs-number">1</span>, end = <span class="hljs-number">100</span></span>) </span>{ <span class="hljs-comment">// default parameters to set the default range</span>
    <span class="hljs-comment">// I need a loop - let's go with for</span>
    <span class="hljs-keyword">for</span>( <span class="hljs-keyword">let</span> i = start; i &lt;= end; i++) {
        <span class="hljs-comment">// probably a variable for what will be outputted</span>
        <span class="hljs-keyword">let</span> output = i;

        <span class="hljs-comment">// rest of the logic here</span>

        <span class="hljs-comment">// outputting the result</span>
        <span class="hljs-built_in">console</span>.log(output);
    }
}
<span class="hljs-comment">// call the function</span>
fizzBuzz(); <span class="hljs-comment">// this prints out 1 to 100 - fancy ;)</span>
</code></pre>
<p>The above satisfies my first goal on my rewritten challenge understanding</p>
<h3 id="heading-second-step">Second step</h3>
<p>Now if I follow the cadence of the challenge I will solve for two things: </p>
<pre><code>- Choosing the proper <span class="hljs-keyword">operator</span> <span class="hljs-keyword">to</span> find <span class="hljs-keyword">if</span> a number <span class="hljs-keyword">is</span> a multiple <span class="hljs-keyword">of</span> another
- Apply it <span class="hljs-keyword">for</span> the multiple <span class="hljs-keyword">of</span> <span class="hljs-number">3</span> condition <span class="hljs-keyword">and</span> output <span class="hljs-string">'Fizz'</span>
</code></pre><p>The <strong>remainder operator - %</strong>, is the perfect tool here. If number <strong>a</strong> is a multiple of number <strong>b</strong> then</p>
<pre><code class="lang-javascript">( b % a) === <span class="hljs-number">0</span>; <span class="hljs-comment">// will be true;</span>
<span class="hljs-comment">// 4 is a multiple of 2</span>
( <span class="hljs-number">4</span> % <span class="hljs-number">2</span> ) === <span class="hljs-number">0</span>; <span class="hljs-comment">// is true</span>
</code></pre>
<p>Let's apply this in the body of our function</p>
<pre><code class="lang-javascript"><span class="hljs-comment">// rest of the logic here</span>
<span class="hljs-keyword">if</span>( (i % <span class="hljs-number">3</span>) === <span class="hljs-number">0</span> ) {
    output = <span class="hljs-string">'Fizz'</span>;
}
<span class="hljs-comment">// Knowing that 3,6 and 9 are multiple of 3 let's</span>
<span class="hljs-comment">// quickly test a small sequence by calling</span>

fizzBuzz(<span class="hljs-number">1</span>,<span class="hljs-number">10</span>); 
<span class="hljs-comment">// this should output</span>
<span class="hljs-comment">// 1, 2, 'Fizz', 4, 5, 'Fizz', 7, 8, 'Fizz', 10</span>
</code></pre>
<h3 id="heading-final-step">Final step</h3>
<p>Since the Fizz condition ran perfect we can now apply the same logic  to the rest</p>
<pre><code class="lang-javascript"><span class="hljs-comment">// multiple of 5</span>
<span class="hljs-keyword">if</span>( (i % <span class="hljs-number">5</span>) === <span class="hljs-number">0</span> ) {
    output = <span class="hljs-string">'Buzz'</span>;
}

<span class="hljs-comment">// multiple of 3 and 5</span>
<span class="hljs-keyword">if</span>( (i % <span class="hljs-number">3</span>) === <span class="hljs-number">0</span>  &amp;&amp; (i % <span class="hljs-number">5</span> === <span class="hljs-number">0</span>)) {
    output = <span class="hljs-string">'FizzBuzz'</span>;
}
</code></pre>
<p>Wowza!! this satisfies all the conditions and gives us this chef d'oeuvre of a solution once assembled 
and stripped out of all comments</p>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">fizzBuzz</span>(<span class="hljs-params"> start = <span class="hljs-number">1</span>, end = <span class="hljs-number">100</span></span>) </span>{ <span class="hljs-comment">// default parameters to set the default range</span>
    <span class="hljs-keyword">for</span>( <span class="hljs-keyword">let</span> i = start; i &lt;= end; i++) {
        <span class="hljs-keyword">let</span> output = i;
        <span class="hljs-keyword">if</span>( (i % <span class="hljs-number">3</span>) === <span class="hljs-number">0</span> ) {
            output = <span class="hljs-string">'Fizz'</span>;
        }
        <span class="hljs-keyword">if</span>( (i % <span class="hljs-number">5</span>) === <span class="hljs-number">0</span> ) {
            output = <span class="hljs-string">'Buzz'</span>;
        }
        <span class="hljs-keyword">if</span>( (i % <span class="hljs-number">3</span>) === <span class="hljs-number">0</span>  &amp;&amp; (i % <span class="hljs-number">5</span>) === <span class="hljs-number">0</span>) {
            output = <span class="hljs-string">'FizzBuzz'</span>;
        }
        <span class="hljs-built_in">console</span>.log(output);
    }
}
fizzBuzz();
</code></pre>
<p>Now at this point, I have a working solution that satisfies the challenge request. What follows is very delicate in an interview situation. Something is bugging me about my code. The last <strong>if block</strong> that checks for multiples of <strong>3</strong> and <strong>5</strong> seem redundant. </p>
<p>Now should I voice that out loud and propose to refactor it or should I wait for the interviewer to call it out? </p>
<p>Interviews are about managing time and maximizing your pluses over your minuses. If you feel super confident that you have a good shot at coming up with something more solid in a manageable time then go for it. If in doubt, wait to be asked. </p>
<p>This way, the interviewer has decided that the remainder of your time might be worth digging deeper on this question. </p>
<p>If it is decided that it would be interesting to look at a refactor, this might be a way to approach the refactor steps</p>
<h3 id="heading-the-refactor">The refactor</h3>
<p>We could, of course, get to a fancy one-liner here for this particular challenge, but I'm not a particular fan of doing stuff for the sake of fancy or pretty. </p>
<p>So let's flip the switch what I'm going to do this time is I will show you my final solution and I will walk you through how did I get to it. </p>
<p>This can turn into a handy skill if you are to read and understand other people's code or if you are to explain it to someone else. Through the years I have provided many solutions for this challenge, but the one below is by far my favorite.</p>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">fizzBuzz</span>(<span class="hljs-params"> start = <span class="hljs-number">1</span>, end = <span class="hljs-number">100</span></span>) </span>{
    <span class="hljs-keyword">for</span>( <span class="hljs-keyword">let</span> i = start; i &lt;= end; i++) {
        <span class="hljs-keyword">let</span> output =  ( (i % <span class="hljs-number">3</span>) ? <span class="hljs-string">''</span> : <span class="hljs-string">'Fizz'</span> ); <span class="hljs-comment">// if multiple of 3 is falsy</span>
        output += ( (i % <span class="hljs-number">5</span>) ? <span class="hljs-string">''</span> : <span class="hljs-string">'Buzz'</span>) ; <span class="hljs-comment">// if multiple of 5 is falsy</span>
        <span class="hljs-built_in">console</span>.log(output || i); <span class="hljs-comment">// output value or i if output is falsy</span>
    }
}
fizzBuzz(<span class="hljs-number">1</span>,<span class="hljs-number">15</span>);
</code></pre>
<p>The solution uses the ternary operator syntax to set the conditions and takes advantage of something that might not very obvious at first for the untrained eye - JavaScript falsy values.</p>
<p>Let's start with falsy values JavaScript, what in the heck are we talking about. A great definition is provided by the <a target="_blank" href="https://developer.mozilla.org/en-US/docs/Glossary/Falsy">Mozilla Developer Network (MDN )</a>:</p>
<blockquote>
<p>A falsy value is a value that is considered false when encountered in a Boolean context.
JavaScript uses Type Conversion to coerce any value to a Boolean in contexts that require it, such as conditionals and loops.</p>
</blockquote>
<p>For our particular context the important keywords are <strong>"Boolean context"</strong> and <strong>"conditionals"</strong> since they are relevant to our solution. Before looking at how it applies, here is the list of the most common falsy values in Javascript:</p>
<ul>
<li>The boolean <strong>false</strong> not the same as the string <strong><em>'false'</em></strong></li>
<li>The number <strong>0</strong> - once again this is different from the string <strong><em>'0'</em></strong></li>
<li>The <strong>null</strong> object</li>
<li>The primitive type <strong>undefined</strong> assigned to a non-initialized variable</li>
<li>Any representation of an empty string such as a single quote, double quotes or back-ticks.</li>
</ul>
<h3 id="heading-the-rewrite">The rewrite</h3>
<p>Let's focus on one segment of our fizzBuzz function</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">if</span>( (i % <span class="hljs-number">3</span>) === <span class="hljs-number">0</span> ) {
output = <span class="hljs-string">'Fizz'</span>;
}
<span class="hljs-comment">// this could be refactored as</span>
<span class="hljs-keyword">if</span>( !(i % <span class="hljs-number">3</span>) ) output = <span class="hljs-string">'Fizz'</span>;
</code></pre>
<p>Breaking down the refactored line gives us this picture</p>
<ul>
<li>if (...)  ==&gt; <strong>conditional construct outside - boolean context inside</strong></li>
<li>!         ==&gt; <strong>is false</strong></li>
<li>(i % 3)   ==&gt; <strong>type coercion - will check if value is falsy or truthy</strong></li>
</ul>
<p>Replace <strong>i</strong> by a few numbers to better understand it</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">if</span> (!( <span class="hljs-number">1</span> % <span class="hljs-number">3</span>) ...) <span class="hljs-comment">/*becomes*/</span> <span class="hljs-keyword">if</span> (!( <span class="hljs-number">3</span> ) ...) <span class="hljs-comment">/*3 is not false or falsy so check fails*/</span>
<span class="hljs-keyword">if</span> (!( <span class="hljs-number">2</span> % <span class="hljs-number">3</span>) ...) <span class="hljs-comment">/*becomes*/</span> <span class="hljs-keyword">if</span> (!( <span class="hljs-number">6</span> ) ...) <span class="hljs-comment">/*6 is not false or falsy so check fails*/</span>
<span class="hljs-keyword">if</span> (!( <span class="hljs-number">3</span> % <span class="hljs-number">3</span>) ...) <span class="hljs-comment">/*becomes*/</span> <span class="hljs-keyword">if</span> (!( <span class="hljs-number">0</span> ) ...) <span class="hljs-comment">/*0 is not false but is falsy so check passes*/</span>
</code></pre>
<p>I can rewrite now my entire function using the logic above</p>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">fizzBuzz</span>(<span class="hljs-params"> start = <span class="hljs-number">1</span>, end = <span class="hljs-number">100</span></span>) </span>{
    <span class="hljs-keyword">for</span>( <span class="hljs-keyword">let</span> i = start; i &lt;= end; i++) {
        <span class="hljs-keyword">let</span> output = i;
        <span class="hljs-keyword">if</span>( !(i % <span class="hljs-number">3</span>) ) output = <span class="hljs-string">'Fizz'</span>;
        <span class="hljs-keyword">if</span>( !(i % <span class="hljs-number">5</span>) ) output = <span class="hljs-string">'Buzz'</span>;
        <span class="hljs-keyword">if</span>( !(i % <span class="hljs-number">3</span>) &amp;&amp; !(i % <span class="hljs-number">5</span>) ) output = <span class="hljs-string">'FizzBuzz'</span>;
        <span class="hljs-built_in">console</span>.log(output);
    }
}
</code></pre>
<p>I was quite ecstatic when I got to this solution, but it did not too long unfortunately. The last line was still redundant to me and honestly was bugging me. How could I combine the checks of 3 and 5 in one pass. </p>
<p>And then it hit me, what if I could start with an empty string, attach to it the word 'Fizz' if it passes the 3 condition and attach the word 'Buzz' if it passes the 5 condition too. I drew this on a piece of paper</p>
<ul>
<li>i = 1 ==&gt; no Fizz '' ==&gt; no Buzz '' ==&gt; output is 1</li>
<li>i = 3 ==&gt; yes 'Fizz' ==&gt; no Buzz '' ==&gt; output is 'Fizz'</li>
<li>i = 5 ==&gt; no Fizz '' ==&gt; yes 'Buzz' ==&gt; output is 'Buzz'</li>
<li>i = 15 =&gt; yes 'Fizz' ==&gt; yes 'Buzz' ==&gt; output is 'FizzBuzz'</li>
</ul>
<p>The ternary operator will allow assigning a value if condition checks and an alternate value if it fails in a very terse manner. </p>
<p>Something else became obvious, <strong>we are outputting either a string or a number</strong> while we cycling through the values of <strong>i</strong> and as we saw in a previous section an empty string is a falsy value. So how do we translate all that intelligence into working code? </p>
<p>The essential piece to achieve that was that the value of <strong>output</strong> was either going to be one of the possible strings 'Fizz', 'Buzz', 'FizzBuzz' or be falsy. In the falsy case <strong>i</strong> will just be passed as is. </p>
<p>So the final rewrite with more comments</p>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">fizzBuzz</span>(<span class="hljs-params"> start = <span class="hljs-number">1</span>, end = <span class="hljs-number">100</span></span>) </span>{
    <span class="hljs-keyword">for</span>( <span class="hljs-keyword">let</span> i = start; i &lt;= end; i++) {
        <span class="hljs-keyword">let</span> output =  ( (i % <span class="hljs-number">3</span>) ? <span class="hljs-string">''</span> : <span class="hljs-string">'Fizz'</span> ); <span class="hljs-comment">// output is assigned a value or empty</span>
        output += ( (i % <span class="hljs-number">5</span>) ? <span class="hljs-string">''</span> : <span class="hljs-string">'Buzz'</span>) ; <span class="hljs-comment">// output concatenates the next value</span>
        <span class="hljs-built_in">console</span>.log(output || i); <span class="hljs-comment">// || or operator if output is falsy will show i value</span>
    }
}
fizzBuzz(<span class="hljs-number">1</span>,<span class="hljs-number">15</span>);
</code></pre>
<p>Hopefully, you followed all of that :) This was a very satisfying solution to me since I believe it was easy to read, solved the problem and had a touch of eloquent JavaScript in it.</p>
<h3 id="heading-final-words">Final words</h3>
<p>The coding exercise covers only one aspect of the many things that happen during the coding interview. </p>
<p>As I mentioned the steps and being able to deliver, regardless of the complexity of the problem, take a solid amount of practice. </p>
<p>Don't hesitate to use mock interviews (we will be offering some in Javascript soon but more on that later) to practice the conversational aspect of it.</p>
<p>I hope this was useful, share and live a comment if you please :)</p>
]]></content:encoded></item><item><title><![CDATA[CSS Grid Layout - A "Quick" Overview]]></title><description><![CDATA[https://www.youtube.com/watch?v=wWGjogHcLxY
A quick warning and request
One of my friend told me that he learned a lot from the video even though it was a bit long - 25mn is kinda long. If you speed it up to 1.5x it is still watchable but at 2x I sta...]]></description><link>https://adyngom.com/css-grid-layout-a-quick-overview</link><guid isPermaLink="true">https://adyngom.com/css-grid-layout-a-quick-overview</guid><category><![CDATA[CSS]]></category><category><![CDATA[grid]]></category><category><![CDATA[Tutorial]]></category><category><![CDATA[Frontend Development]]></category><category><![CDATA[Responsive Web Design]]></category><dc:creator><![CDATA[Ady Ngom]]></dc:creator><pubDate>Mon, 13 May 2019 04:34:50 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1557722053961/_eI7VokHt.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<div class="embed-wrapper"><div class="embed-loading"><div class="loadingRow"></div><div class="loadingRow"></div></div><a class="embed-card" href="https://www.youtube.com/watch?v=wWGjogHcLxY">https://www.youtube.com/watch?v=wWGjogHcLxY</a></div>
<h1 id="heading-a-quick-warning-and-request">A quick warning and request</h1>
<p>One of my friend told me that he learned a lot from the video even though it was a bit long - 25mn is kinda long. If you speed it up to 1.5x it is still watchable but at 2x I start to sound like a total chipmunk and you might find it entertaining.</p>
<p>I hope you enjoy it and learn something from it if CSS Grid is new to you. I really miss working on the User Interface side, let me know in the comments if you would like to see more posts around UI</p>
<p>The starter coded is added inline or you can copy it from here:
<a target="_blank" href="https://gist.github.com/adyngom/dadfa4150296546c32897153addd2385">Grid starter code</a></p>
<p>And the template used can be downloaded here:
<a target="_blank" href="https://pixelbuddha.net/freebie/elton-ui-kit">Elton UI Kit</a></p>
<pre><code class="lang-html"><span class="hljs-meta">&lt;!DOCTYPE <span class="hljs-meta-keyword">html</span>&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">html</span> <span class="hljs-attr">lang</span>=<span class="hljs-string">"en"</span>&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">head</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">meta</span> <span class="hljs-attr">charset</span>=<span class="hljs-string">"UTF-8"</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">title</span>&gt;</span>Elton ui Kit<span class="hljs-tag">&lt;/<span class="hljs-name">title</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">style</span>&gt;</span><span class="css">
        <span class="hljs-keyword">@import</span> <span class="hljs-string">'https://fonts.googleapis.com/css?family=Comfortaa:300,700|Bungee+Shade|Josefin+Sans:400'</span>;

        <span class="hljs-selector-tag">html</span> {
            <span class="hljs-attribute">background-color</span>: <span class="hljs-number">#eee</span>;
        }
        <span class="hljs-selector-tag">html</span>, <span class="hljs-selector-tag">body</span> {
            <span class="hljs-attribute">margin</span>: <span class="hljs-number">0</span>;
            <span class="hljs-attribute">padding</span>: <span class="hljs-number">0</span>;
        }
        <span class="hljs-selector-tag">body</span> {
            <span class="hljs-attribute">counter-reset</span>: section;
        }
        <span class="hljs-selector-class">.wrapper</span> {
            <span class="hljs-attribute">width</span>: <span class="hljs-number">1170px</span>;
            <span class="hljs-attribute">margin</span>: <span class="hljs-number">30px</span> auto;
            <span class="hljs-attribute">box-sizing</span>: border-box;
        }
        <span class="hljs-selector-class">.box</span> {
            <span class="hljs-attribute">border-radius</span>: <span class="hljs-number">3px</span>;
            <span class="hljs-attribute">background-color</span>: <span class="hljs-number">#ffffff</span>;
            <span class="hljs-attribute">box-shadow</span>: <span class="hljs-number">0</span> <span class="hljs-number">1px</span> <span class="hljs-number">3px</span> <span class="hljs-number">0</span> <span class="hljs-built_in">rgba</span>(<span class="hljs-number">0</span>, <span class="hljs-number">0</span>, <span class="hljs-number">0</span>, <span class="hljs-number">0.06</span>);
        }
        <span class="hljs-selector-class">.hero-fashion</span> &gt; <span class="hljs-selector-class">.box</span> {
            <span class="hljs-attribute">width</span>: <span class="hljs-number">1170px</span>;
            <span class="hljs-attribute">height</span>: <span class="hljs-number">505px</span>;
            <span class="hljs-attribute">margin-bottom</span>: <span class="hljs-number">30px</span>;
        }
        <span class="hljs-selector-class">.row</span> {
            <span class="hljs-attribute">display</span>: grid;
            <span class="hljs-attribute">grid-template-columns</span>: <span class="hljs-number">1</span>fr <span class="hljs-number">1</span>fr <span class="hljs-number">1</span>fr <span class="hljs-number">1</span>fr;
            <span class="hljs-attribute">grid-auto-rows</span>: <span class="hljs-number">238px</span>;
            <span class="hljs-attribute">grid-gap</span>: <span class="hljs-number">30px</span>;
        }
        <span class="hljs-selector-class">.tall-span</span> {
            <span class="hljs-attribute">grid-row</span>: span <span class="hljs-number">2</span>;
        }
        <span class="hljs-selector-class">.wide-span</span> {
            <span class="hljs-attribute">grid-column</span>: span <span class="hljs-number">2</span>
        }

    </span><span class="hljs-tag">&lt;/<span class="hljs-name">style</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">head</span>&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">body</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"wrapper"</span>&gt;</span>

        <span class="hljs-comment">&lt;!-- hero section --&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"hero-fashion"</span>&gt;</span>
            <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"box"</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
        <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>

        <span class="hljs-comment">&lt;!-- grid section --&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"row"</span>&gt;</span>
            <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"box tall-span"</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
            <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"box wide-span"</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
            <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"box"</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
            <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"box"</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
            <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"box wide-span"</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
            <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"box"</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
            <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"box"</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
            <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"box"</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
            <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"box"</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
            <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"box"</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
            <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"box"</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
            <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"box"</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
            <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"box"</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
        <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
    <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">body</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">html</span>&gt;</span>
</code></pre>
]]></content:encoded></item><item><title><![CDATA[4 more relevant JavaScript questions to help fix the broken coding interview]]></title><description><![CDATA[As a quick refresher, there is a general sense that technical interviewing is broken. JavaScript is probably the most popular programming language today and certainly part of the top fives. 
Hiring the right candidate in the JS world - which has beco...]]></description><link>https://adyngom.com/4-more-relevant-javascript-questions-to-help-fix-the-broken-coding-interview</link><guid isPermaLink="true">https://adyngom.com/4-more-relevant-javascript-questions-to-help-fix-the-broken-coding-interview</guid><category><![CDATA[JavaScript]]></category><category><![CDATA[Career]]></category><category><![CDATA[Interviews]]></category><category><![CDATA[software development]]></category><category><![CDATA[Frontend Development]]></category><dc:creator><![CDATA[Ady Ngom]]></dc:creator><pubDate>Thu, 09 May 2019 16:21:05 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1557418003628/tPQpBjdhC.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>As a quick refresher, there is a general sense that technical interviewing is broken. JavaScript is probably the most popular programming language today and certainly part of the top fives. </p>
<p>Hiring the right candidate in the JS world - which has become a multiverse - is turning into an experimental art form. </p>
<p>I have, like many before and many more to come, been a witness of the impact of a poor screening process and this is my attempt to be a part of the solution. </p>
<p>You can read more about my mission statement in the <a target="_blank" href="https://hashnode.com/post/4-relevant-javascript-interview-questions-cjvabh0i6002yrds1biczetay">first article</a> of the series but without further ado here is your next relevant four in descending order for a change.</p>
<h3 id="heading-8-input-autocomplete">8. Input autocomplete</h3>
<p><strong><em>Best suited for:</em></strong> Senior | Expert <strong>Stage:</strong> At home | Round 2 | Onsite</p>
<h5 id="heading-8a-the-challenge">8A. The challenge</h5>
<p>The UX team has insisted that the country search input form needed to be more user-friendly.</p>
<p>They have their mind made on a "simple" autocomplete search box. What's not so simple and not obvious to the UX team, is that you have a huge dataset of possible results that would not be feasible to store on the client side. </p>
<p>Your task is to create a program that listens to user input events and fetches a list of possible matches. The UX team is not a big fan of dirty matching and wants the list to only show the country names that start with the search term entered by the user - oh and they want matches to be highlighted by the way on the list results</p>
<h5 id="heading-8b-the-context">8B. The context</h5>
<p>I have had similar tests provided and with usually a 48 to 72 hours to submit it back. I strongly advise that you use all the time allocated to come up with the most refined solution available.</p>
<p>This has the advantage to mimic to a certain extent what an actual user story might be and you are given time to execute. </p>
<p>And please, please don't just go blindly copy and paste a solution that you do not have a full grasp on. </p>
<p>You will be expected to come on site or online to talk about your solution, your reasoning and more than often a 'feature creep' will happen during evaluation to see how you will handle it. </p>
<p>For this particular problem, the async nature of the search and filter is going to be the first hurdle, but I would not personally start there. I would probably start with a small set of local data and focus on making the autocomplete and highlight as solid as possible.</p>
<p>As an interviewer I would love to see the candidate talk about and integrate all or most of the concepts below:</p>
<ul>
<li>Throttle <a target="_blank" href="https://css-tricks.com/debouncing-throttling-explained-examples/">link</a></li>
<li>Debounce <a target="_blank" href="https://davidwalsh.name/javascript-debounce-function">link</a></li>
<li>Caching</li>
<li>Memoization <a target="_blank" href="https://medium.freecodecamp.org/understanding-memoize-in-javascript-51d07d19430e">link</a></li>
<li>Error Handling </li>
</ul>
<p>Take-homes are more challenging than they might seem at first. Usually, enough is given to get you started, but a lot is expected on your delivery.</p>
<h3 id="heading-7-mini-testing-library">7 Mini testing library</h3>
<p><strong><em>Best suited for:</em></strong> Junior | Senior | Expert <strong>Stage:</strong> Round 3 | Onsite</p>
<h5 id="heading-7a-the-challenge">7A. The challenge</h5>
<p>The dev team is shyly making its debut to the TDD approach. They don't want to commit yet to a full-fledged library but want to write simple tests directly on the console to test their most important functions. They have dubbed the experiment project dotLog and have provided the initial structure below:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">var</span> dotLog = ( <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params"></span>) </span>{
 <span class="hljs-keyword">return</span> {
    describe(desc = <span class="hljs-string">'test description:'</span>, testSet = []) {
        <span class="hljs-built_in">console</span>.groupCollapsed(<span class="hljs-string">`<span class="hljs-subst">${desc}</span>: 0 passed - 0 failed`</span>);
            <span class="hljs-comment">// console out each test</span>
        <span class="hljs-built_in">console</span>.groupEnd();
    }
 }
}());
</code></pre>
<p>The <strong>describe</strong> method takes in a test label string and an array of test objects. The test object uses the following model:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">var</span> testOne = { <span class="hljs-attr">rule</span>: ( <span class="hljs-number">3</span> &lt; <span class="hljs-number">4</span>), <span class="hljs-attr">label</span>: <span class="hljs-string">" 3 is less than 4"</span> };
<span class="hljs-keyword">var</span> testTwo = { <span class="hljs-attr">rule</span>: (<span class="hljs-built_in">Math</span>.max.apply(<span class="hljs-literal">null</span>,[<span class="hljs-number">3</span>,<span class="hljs-number">4</span>,<span class="hljs-number">1</span>,<span class="hljs-number">2</span>,<span class="hljs-number">0</span>]) === <span class="hljs-number">4</span>), <span class="hljs-attr">label</span>: <span class="hljs-string">" should output 4"</span> };
</code></pre>
<p>Now those can be added to a testSet and be passed to the <strong>describe</strong> method</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">var</span> testSet = [testOne, testTwo];
dotLog.describe(<span class="hljs-string">"Basic Math tests:"</span>, testSet);
Given the following <span class="hljs-string">'naïve'</span> <span class="hljs-function"><span class="hljs-keyword">function</span>
<span class="hljs-title">function</span> <span class="hljs-title">sum</span> (<span class="hljs-params">x, y</span>) </span>{
    <span class="hljs-keyword">return</span> x + y;
}
</code></pre>
<p>Fix it and the describe method so the following output is displayed:</p>
<pre><code class="lang-javascript">sum(): <span class="hljs-number">3</span> passed - <span class="hljs-number">1</span> failed
    √ Should <span class="hljs-keyword">return</span> <span class="hljs-number">0</span> <span class="hljs-keyword">if</span> no <span class="hljs-built_in">arguments</span>
    √ Should add two numbers
    √ Should add up any amount <span class="hljs-keyword">of</span> numbers
    x Should convert any non-digit to <span class="hljs-number">0</span> and <span class="hljs-keyword">return</span> the right amount
</code></pre>
<h5 id="heading-7b-the-context">7B. The context</h5>
<p>I have had my share of rejections but have also been very successful at landing the job. In all the interviews I have been through, only two companies have ever presented a challenge similar to this one.</p>
<p>The particularity of it was that I was actually seating with the entire development team, where would eventually be my work station and participated in the standup and was given half the day to solve for the problem. At the end of the four hours, I was taken to lunch and bid farewell.</p>
<p>Though I landed both of those, the interesting part was the process. I got to work directly in what would be my daily environment, the challenge was an actual user story in their backlog. </p>
<p>I could not cheat on my soft skills if I wanted to be successful, I had to reach out to my "soon to be" teammates to find out more details, or a quick setup issue. I had to submit my changes via a PR. </p>
<p>Word of advice, commit often and use descriptive messages about your changes.</p>
<p>In summary, I think companies can invest some time in accommodating this type of setup. Another approach might be to give it as an at home exercise with a time limit and have the candidate come and discuss her solution onsite with the team.</p>
<h3 id="heading-6-vending-machine">6 Vending machine</h3>
<p><strong><em>Best suited for:</em></strong> Junior | Senior | Expert <strong>Stage:</strong> Round 2 | Round 3 | Onsite</p>
<h5 id="heading-6a-the-challenge">6A. The challenge**</h5>
<p>Bob runs a successful Vending Machine business. He wants to add an interface that makes them a bit user-friendly and make it easy to add and track inventory. Below is the typical inventory model for the machines:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> drinks = {
    <span class="hljs-number">1</span>: { <span class="hljs-attr">name</span>: <span class="hljs-string">"Mango Juice"</span>, <span class="hljs-attr">stock</span>: <span class="hljs-number">2</span> },
    <span class="hljs-number">2</span>: { <span class="hljs-attr">name</span>: <span class="hljs-string">"Banana Smoothies"</span>, <span class="hljs-attr">stock</span>: <span class="hljs-number">2</span> },
    <span class="hljs-number">3</span>: { <span class="hljs-attr">name</span>: <span class="hljs-string">"Guava Mix"</span>, <span class="hljs-attr">stock</span>: <span class="hljs-number">1</span> },
    <span class="hljs-number">4</span>: { <span class="hljs-attr">name</span>: <span class="hljs-string">"Citrus Blend"</span>, <span class="hljs-attr">stock</span>: <span class="hljs-number">3</span> }
  };
</code></pre>
<p>Write a program that creates an instance of the Vending Machine (VM) with the following specifications:</p>
<p>The VM needs to be passed an inventory object in order to create an instance
If the object is not passed, the program should throw a descriptive error:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> vm = <span class="hljs-keyword">new</span> VM(drinks); <span class="hljs-comment">// instance get created</span>
<span class="hljs-comment">// but</span>
<span class="hljs-keyword">const</span> emptyVM = <span class="hljs-keyword">new</span> VM(); <span class="hljs-comment">// throws a no inventory error</span>
</code></pre>
<p>VM should assign the newly passed inventory to a private drinks variable that is not modifiable from the instance</p>
<pre><code class="lang-javascript">vm.drinks; <span class="hljs-comment">// should output undefined</span>
</code></pre>
<p>VM should have a callable sale method that takes the drink id as an input and return a success message if in stock or a failed message if out of stock
VM will always deduct one (1) from the product id stock after a successful sale</p>
<pre><code class="lang-javascript">vm.sale(<span class="hljs-number">1</span>);
<span class="hljs-comment">// output: 1 Mango Juice - Thank you, come again!!</span>
vm.sale(<span class="hljs-number">1</span>);
<span class="hljs-comment">// output: 1 Mango Juice - Thank you, come again!!"</span>
vm.sale(<span class="hljs-number">1</span>);
<span class="hljs-comment">// output: Mango Juice is out of stock :( Come back tomorrow</span>
vm.sale(<span class="hljs-number">4</span>);
<span class="hljs-comment">// output: 1 Citrus Blend - Thank you, come again!!</span>
</code></pre>
<p>Finally VM should also have a callable stock method. It does not take any parameters and should display the total count of available drinks. </p>
<p>The drinks object given as an example has a total of 8 drinks. After buying 2 mango juice, the output of the stock method should 6. it should also output 'Out of stock' if empty.</p>
<pre><code class="lang-javascript">vm.stock(); <span class="hljs-comment">// should output total of all drinks left or Out of stock</span>
</code></pre>
<h5 id="heading-6b-the-context">6B. The context</h5>
<p>Function with a constructor, new ES6 class, or Object create?? There are so many ways to approach this that I hope that the interviewer should be as prepared as the candidate.</p>
<p>A solid understanding of closures is going to help tremendously. It will be interesting also to see how the candidate approach scope and private variable and see if any design patterns are implicitly or explicitly used.</p>
<p>I think that no matter the level of the candidate, this type of exercise should allow touching on many key concepts of the JS language.</p>
<h3 id="heading-5-code-analysis-and-possible-refactor">5 Code analysis and possible refactor</h3>
<p><strong><em>Best suited for:</em></strong> Senior | Expert <strong>Stage:</strong> Round 2 | Round 3 | Onsite</p>
<h5 id="heading-5a-the-challenge">5A. The challenge</h5>
<p>The sales team wants to have a small program that helps them remove any duplicates from a batch of tickets. Tickets batches are usually between <strong>1,000</strong> to <strong>10,000</strong> unfiltered items. The following solutions have been submitted by 3 developers in your team.</p>
<p><strong>Developer 1</strong></p>
<pre><code class="lang-javascript"><span class="hljs-keyword">if</span>( !<span class="hljs-built_in">Array</span>.prototype.uniq ) {
    <span class="hljs-built_in">Array</span>.prototype.uniq = <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params"></span>) </span>{
        <span class="hljs-keyword">let</span> _singles = [];
        <span class="hljs-keyword">const</span> arr = <span class="hljs-built_in">this</span>;
        <span class="hljs-keyword">for</span> ( <span class="hljs-keyword">let</span> i = <span class="hljs-number">0</span>; i &lt; arr.length; i++ ) {
            <span class="hljs-keyword">if</span>(_singles.indexOf(arr[i]) === <span class="hljs-number">-1</span> ) {
                _singles.push( arr[i] );
            }
        }
        <span class="hljs-keyword">return</span> _singles;
    }
}
</code></pre>
<p><strong>Developer 2</strong></p>
<pre><code class="lang-javascript"><span class="hljs-keyword">if</span>(!<span class="hljs-built_in">Array</span>.prototype.uniq) {
    <span class="hljs-built_in">Array</span>.prototype.uniq = <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params"></span>) </span>{
        <span class="hljs-keyword">return</span> <span class="hljs-built_in">this</span>.reduce( <span class="hljs-function">(<span class="hljs-params">arr, val</span>) =&gt;</span> {
            <span class="hljs-keyword">if</span> (!arr.includes(val)) arr.push(val);
            <span class="hljs-keyword">return</span> arr;
        }, [] );
    }
}
</code></pre>
<p><strong>Developer 3</strong></p>
<pre><code class="lang-javascript"><span class="hljs-keyword">if</span>(!<span class="hljs-built_in">Array</span>.prototype.uniq) {
   <span class="hljs-built_in">Array</span>.prototype.uniq = <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params"></span>) </span>{
       <span class="hljs-keyword">return</span> <span class="hljs-keyword">new</span> <span class="hljs-built_in">Set</span>([...this]);
   }
}
</code></pre>
<p>Two tests files are provided <a target="_blank" href="https://gist.github.com/adyngom/748873da9cb37828765216a36e7b7ec2"><strong>onekTickets.js</strong></a> and <a target="_blank" href="https://gist.github.com/adyngom/62c25502eed121e9092c97fd9041afa0"><strong>tenkTickets.js.</strong></a></p>
<p>Only one solution can be pushed to production. Which, if any, would you pick based on readability and performance?</p>
<p>Can any of the proposed solutions be even more optimized to get to a better one?
What would be the PR message you will leave for each of the developers regarding their solution and why it was or was not chosen?</p>
<h5 id="heading-5b-the-context">5B. The context</h5>
<p>In a normal development environment, you will be expected to read, evaluate and eventually critique other people's code.</p>
<p>The PR reviews are a critical step in making sure quality code is being pushed to the main repo.</p>
<p>Now each team or company can have their own take about how to define quality, but cannot walk away from clearly outlining standards, conventions and coding culture.</p>
<p>This type of question is both beneficial to the employer but to the candidate as well. Your main interaction with the team will be through similar exercises on a daily basis.</p>
<p>As an interviewer, my expectation will be for the candidate to reference some benchmarking tools to help determine which block of code is the fastest.</p>
<p>I surely will be impressed if she could eyeball it and clearly explain why, but since we are talking about giving feedback, it will be always easier to show rather than just tell.</p>
<p><strong>console.time</strong> and <strong>console.timeEnd</strong> might kick off the conversation in the right direction, <a target="_blank" href="jsperf.com">jsperf.com</a> is also one the industry's favorite, but ultimately looking for, suggesting, doing a basic setup and running a quick benchmark would be a clear winner.</p>
<p>Finally, I would like to have an open discussion about readability, and maybe why sometimes it might be beneficial to sacrifice a little speed in spite of it.</p>
<h3 id="heading-in-closing">In closing</h3>
<p>This ends the second batch. Today we have introduced a DOM-related exercise with the input autocomplete. Expect a lot more of those to come in the next installment. </p>
<p>In the meantime don't forget to share, clap or whatnots but most important to add to the discussion in the comments. </p>
<p>Cheers</p>
]]></content:encoded></item></channel></rss>