<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>Forem: Omi</title>
    <description>The latest articles on Forem by Omi (@ompals).</description>
    <link>https://forem.com/ompals</link>
    <image>
      <url>https://media2.dev.to/dynamic/image/width=90,height=90,fit=cover,gravity=auto,format=auto/https:%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F500340%2F70ded5e5-363b-4544-a55b-5524ebb21026.png</url>
      <title>Forem: Omi</title>
      <link>https://forem.com/ompals</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://forem.com/feed/ompals"/>
    <language>en</language>
    <item>
      <title>Gradual growth!</title>
      <dc:creator>Omi</dc:creator>
      <pubDate>Wed, 28 May 2025 18:06:22 +0000</pubDate>
      <link>https://forem.com/ompals/gradual-growth-3jo9</link>
      <guid>https://forem.com/ompals/gradual-growth-3jo9</guid>
      <description>&lt;p&gt;It has been 2-3 months since I have not posted anything new here. &lt;br&gt;
All because I have really gotten busy with my work and some family functions. &lt;/p&gt;

&lt;p&gt;Building for the excellence takes time, meaningful efforts and courage to accept yourself. Failure and frustration are just a part of the process. &lt;/p&gt;

&lt;p&gt;I joined a team of supportive developers and a calm lead. No rush, no criticizing over small mistakes. Understand slowly and steadily. &lt;/p&gt;

&lt;p&gt;However, the process will never leave you from scolding your own mind! Your teammates do not judge you, but you judge yourself. Your manager do not rush you to meet the deadline but you do it by yourself. &lt;/p&gt;

&lt;p&gt;Because, you have committed your words. You have committed to the deadlines. And you have committed to the qualities.&lt;/p&gt;

&lt;p&gt;You get curious and furious at the same time. You take a step into performing your best. It is never about competing with people. It is about competing your past self. &lt;/p&gt;

&lt;p&gt;Be collaborative. Learn, teach and gradually become a part of the most advanced crafts of the mankind. &lt;/p&gt;

&lt;p&gt;Working for a paycheck will secure your retirement. &lt;br&gt;
Working for the mankind will satisfy your soul! &lt;/p&gt;

</description>
    </item>
    <item>
      <title>This is why AI can't takeover my engineering job</title>
      <dc:creator>Omi</dc:creator>
      <pubDate>Sun, 30 Mar 2025 16:21:41 +0000</pubDate>
      <link>https://forem.com/ompals/this-is-why-ai-cant-takeover-my-developer-job-2aco</link>
      <guid>https://forem.com/ompals/this-is-why-ai-cant-takeover-my-developer-job-2aco</guid>
      <description>&lt;h2&gt;
  
  
  Short and sweet
&lt;/h2&gt;

&lt;p&gt;So, I was supposed to complete a coding task, test it and then submit. I created a prompt. AI generated a code for me. There was a bug in it, which I discovered after testing it thoroughly. I found out that what was the issue and simply added a prompt to correct the code. AI corrected the code with the syntax that I did not know, so I simply went to learn it. &lt;/p&gt;

&lt;p&gt;The thing is, LLMs just crawls through the web. Someone might have posted about the issue, that's where it got to crawl and provide a solution. The logic behind the bug was not intuitive to the humans, how could the LLMs! &lt;/p&gt;

&lt;p&gt;Your natural visualization of a problem is much more important to the industry than your "crawling through the web skills"! So, if you gotta "let's find a solution on internet" ask AI. But if you got a "What is the problem with this code" problem, don't bother that AI. &lt;/p&gt;

&lt;p&gt;&lt;em&gt;Our GPUs are melting.&lt;/em&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Sam Altman&lt;/li&gt;
&lt;/ul&gt;

</description>
      <category>ai</category>
      <category>testing</category>
    </item>
    <item>
      <title>Do you know the closures well?</title>
      <dc:creator>Omi</dc:creator>
      <pubDate>Sun, 30 Mar 2025 15:52:25 +0000</pubDate>
      <link>https://forem.com/ompals/do-you-know-the-closures-well-1cc4</link>
      <guid>https://forem.com/ompals/do-you-know-the-closures-well-1cc4</guid>
      <description>&lt;h2&gt;
  
  
  Challenge
&lt;/h2&gt;

&lt;p&gt;Go to this task on javascript.info site -&amp;gt; &lt;a href="https://javascript.info/closure#army-of-functions" rel="noopener noreferrer"&gt;Army of function&lt;/a&gt;&lt;br&gt;
(Stop reading from here, go perform the task first! Adding an image below so that you don't accidently read my solution)&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F5gfgaf3vcm4k3di0miqu.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F5gfgaf3vcm4k3di0miqu.png" alt="Mai nahi bataunga" width="800" height="461"&gt;&lt;/a&gt;&lt;/p&gt;
&lt;h2&gt;
  
  
  My experience after solving this
&lt;/h2&gt;

&lt;p&gt;I implemented a bit different approach, since the question is inside a chapter where every problem was solved by &lt;strong&gt;defining a higher order function&lt;/strong&gt;. &lt;/p&gt;

&lt;p&gt;So my solution looked something like this: [This is &lt;strong&gt;NOT&lt;/strong&gt; the full and final solution]&lt;/p&gt;
&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight javascript"&gt;&lt;code&gt;&lt;span class="kd"&gt;function&lt;/span&gt; &lt;span class="nf"&gt;makeArmy&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
  &lt;span class="kd"&gt;let&lt;/span&gt; &lt;span class="nx"&gt;shooters&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="p"&gt;[];&lt;/span&gt;

  &lt;span class="c1"&gt;// I created  a generateShooter function&lt;/span&gt;
  &lt;span class="kd"&gt;function&lt;/span&gt; &lt;span class="nf"&gt;generateShooter&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;number&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="nf"&gt;function &lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
      &lt;span class="nx"&gt;console&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;log&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;number&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
    &lt;span class="p"&gt;};&lt;/span&gt;
  &lt;span class="p"&gt;}&lt;/span&gt;

  &lt;span class="k"&gt;while &lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;i&lt;/span&gt; &lt;span class="o"&gt;&amp;amp;&lt;/span&gt;&lt;span class="nx"&gt;lt&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt; &lt;span class="mi"&gt;10&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="kd"&gt;let&lt;/span&gt; &lt;span class="nx"&gt;shooter&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nf"&gt;generateShooter&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;i&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
    &lt;span class="nx"&gt;shooters&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;push&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;shooter&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt; &lt;span class="c1"&gt;// and add it to the array&lt;/span&gt;
    &lt;span class="nx"&gt;i&lt;/span&gt;&lt;span class="o"&gt;++&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
  &lt;span class="p"&gt;}&lt;/span&gt;

  &lt;span class="c1"&gt;// ...and return the array of shooters&lt;/span&gt;
  &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="nx"&gt;shooters&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;

&lt;span class="kd"&gt;let&lt;/span&gt; &lt;span class="nx"&gt;army&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nf"&gt;makeArmy&lt;/span&gt;&lt;span class="p"&gt;();&lt;/span&gt;

&lt;span class="c1"&gt;// all shooters show 10 instead of their numbers 0, 1, 2, 3...&lt;/span&gt;
&lt;span class="nx"&gt;army&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;]();&lt;/span&gt; &lt;span class="c1"&gt;// 0&lt;/span&gt;
&lt;span class="nx"&gt;army&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;]();&lt;/span&gt; &lt;span class="c1"&gt;// 1&lt;/span&gt;
&lt;span class="nx"&gt;army&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="mi"&gt;2&lt;/span&gt;&lt;span class="p"&gt;]();&lt;/span&gt; &lt;span class="c1"&gt;// 2&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;
&lt;h2&gt;
  
  
  The catch
&lt;/h2&gt;

&lt;p&gt;(If you have read the solution completely on the javascript.info site, then you might not be reading this, but since you are here, let me serve the essence of this problem to you!)&lt;/p&gt;

&lt;p&gt;Simply switch from the &lt;code&gt;while&lt;/code&gt; loop to &lt;code&gt;for&lt;/code&gt; loop! 🧠🤯&lt;br&gt;
Refer to the full solution on javascript.info site only, since it has all the features that makes it super easy to visualize. &lt;/p&gt;
&lt;h2&gt;
  
  
  Conclusion
&lt;/h2&gt;

&lt;p&gt;Javascript.info seems to be the best site to understand js concepts with learn by doing approach. &lt;/p&gt;

&lt;p&gt;PS: It's a really fast paced world that missing a detail is so common and the cost of not knowing a basic detail will question your capability at every line of code in the thousands of lines of project.  &lt;/p&gt;

</description>
      <category>javascript</category>
      <category>closures</category>
      <category>interview</category>
    </item>
    <item>
      <title>Node.js streams | pipe through your way ✅ | say NO to pressure!</title>
      <dc:creator>Omi</dc:creator>
      <pubDate>Sat, 29 Mar 2025 14:01:44 +0000</pubDate>
      <link>https://forem.com/ompals/nodejs-streams-pipe-through-your-way-say-no-to-pressure-41mp</link>
      <guid>https://forem.com/ompals/nodejs-streams-pipe-through-your-way-say-no-to-pressure-41mp</guid>
      <description>&lt;h2&gt;
  
  
  Description
&lt;/h2&gt;

&lt;p&gt;&lt;em&gt;Poll phase is hijacked by the uncontrolled flow from readable stream.&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;This is a short post for a probable long post later. Recently I was implementing something using Node.js streams. And I got a really good opportunity to think about backpressure, event loop and closures! All concepts in one!&lt;/p&gt;

&lt;h2&gt;
  
  
  Problem overview
&lt;/h2&gt;

&lt;p&gt;There's a csv file. Parse it using csv-parser and store the rows in an internal buffer. As soon as the buffer gets full, commit the rows in the database. The functionality should utilize asynchronous programming. Simply means that the main thread should be empty while the application is performing I/O operations. &lt;/p&gt;

&lt;p&gt;Seemed an easy problem until I started implementing it. &lt;/p&gt;

&lt;p&gt;Before moving to the solution, think about your solution. (Make sure not to miss the important detail: buffer) &lt;/p&gt;

&lt;h2&gt;
  
  
  Solution overview
&lt;/h2&gt;

&lt;p&gt;Visualization of the problem: &lt;/p&gt;

&lt;p&gt;File.csv (I/O) -&amp;gt; readable stream (csv-parser) -&amp;gt; buffer -&amp;gt; commit to the database (I/O)&lt;/p&gt;

&lt;p&gt;Focus on the I/O part. I/O is handled in Node.js poll phase. &lt;/p&gt;

&lt;p&gt;The readable stream starts filling up the poll phase. As soon as a row is read by csv-parser, it will push the on data event handler to the main thread. &lt;/p&gt;

&lt;p&gt;This event handler will fill the buffer till 5 rows from csv file. &lt;/p&gt;

&lt;p&gt;After 5 rows, the handler should make a db call to commit the 5 rows. &lt;/p&gt;

&lt;p&gt;Since this is an I/O operation, we specify the async await operation. &lt;/p&gt;

&lt;p&gt;As soon as you complete the implementation and test, you'll see that the async db call made the main thread empty, so the rows from poll phase keep emitting the on data handler. &lt;/p&gt;

&lt;p&gt;Experts call this as "backpressure".&lt;/p&gt;

&lt;p&gt;Even though this implementation works for a small file, it will spike the RAM usage for a larger file. &lt;/p&gt;

&lt;p&gt;The current implementation will create a poll phase like this: &lt;/p&gt;

&lt;p&gt;csv, csv,... milion csv rows then &lt;br&gt;
db, db, ... million/5 db writes. &lt;/p&gt;

&lt;p&gt;All of these will try to execute at cpu speed. &lt;/p&gt;

&lt;p&gt;The drawback of this will be: at no point the main thread will be free until all the reads and db calls get executed. If this functionality is implemented on a rest api server, you will face a downtime since the main thread gets blocked now due to overflowing the poll phase. &lt;/p&gt;

&lt;p&gt;So, how do you control the flow of water from the tap? By closing the tap ;P&lt;/p&gt;

&lt;p&gt;Our main problem was: Poll phase is hijacked by the uncontrolled flow from readable stream. So, the solution is to simply put a pause when the buffer is full. While the stream is paused, make the db call to commit the changes and empty the buffer. Then resume the stream. This will make the poll phase look something like this: &lt;/p&gt;

&lt;p&gt;csv csv csv csv csv (5 only) db &lt;/p&gt;

&lt;p&gt;So the poll phase is not attacked by the js code. In between these operations, any api call made to the rest api server will also get served successfully since an api call will not need to wait for millions of callbacks to execute, only 6 callbacks. &lt;/p&gt;

&lt;p&gt;That's how the main thread is also made unblocked and the server is not also down and RAM usage is not spiked. &lt;/p&gt;

&lt;p&gt;Phew! &lt;br&gt;
At first it seemed like a jargon, but later on, it was just an event loop question! &lt;/p&gt;

&lt;h2&gt;
  
  
  Conclusion
&lt;/h2&gt;

&lt;p&gt;Never block the main thread! &lt;/p&gt;

&lt;p&gt;PS: I will publish my project with complete setup of csv-parser, express js, knex.js and cron job with a well commented code and complete documentation for the educational purposes. Thanks for your attention! &lt;/p&gt;

</description>
      <category>streams</category>
      <category>node</category>
      <category>pipe</category>
      <category>backpressure</category>
    </item>
    <item>
      <title>Is it intuitive though? | Story of my new ecommerce venture</title>
      <dc:creator>Omi</dc:creator>
      <pubDate>Tue, 25 Mar 2025 08:06:24 +0000</pubDate>
      <link>https://forem.com/ompals/is-it-intuitive-though-story-of-my-new-ecommerce-venture-34bn</link>
      <guid>https://forem.com/ompals/is-it-intuitive-though-story-of-my-new-ecommerce-venture-34bn</guid>
      <description>&lt;p&gt;Recently I am working with a local shop who wants to sell their products online. Not to mention, they needed a website in days. Not months, not weeks. Whatever tech stack you are building upon, it is merely impossible to even get your nextjs based ready website up and running in a matter of days with their change in requirements! &lt;/p&gt;

&lt;p&gt;So, I came across Shopify. A really good UI,features rich and great free third party apps, great customer support as well. I initiated a store front on Shopify. &lt;/p&gt;

&lt;p&gt;They have a really great UI to upload products. A sophisticated forms UI. Someone from the shop who knows the products would easily complete the work within a day. &lt;/p&gt;

&lt;p&gt;But hey, it is a local shop! No one has got much time to do it buddy. The shop owner was interested in having an excel sheet so that he can populate everything into it. &lt;/p&gt;

&lt;p&gt;There are hundreds of product the sell! It is indeed a boring stuff to get each product online with perfection. &lt;/p&gt;

&lt;p&gt;Just to conclude, someone at Shopify built a great product upload UI form. Features rich. With AI integrations. &lt;/p&gt;

&lt;p&gt;But guess which feature is most useful in this case? Excel sheet upload. Even if it doesn't come with AI integrations, it is still a go to method for such businesses. &lt;/p&gt;

&lt;p&gt;The question is not about intuitiveness. It is about the manual work with no guarantee of rewards.&lt;/p&gt;

</description>
      <category>ecommerce</category>
      <category>shopify</category>
      <category>ui</category>
      <category>forms</category>
    </item>
    <item>
      <title>Leetcode's runtime "beats x%" is x% reliable</title>
      <dc:creator>Omi</dc:creator>
      <pubDate>Mon, 17 Mar 2025 05:31:44 +0000</pubDate>
      <link>https://forem.com/ompals/leetcodes-runtime-beats-x-is-x-reliable-3j3j</link>
      <guid>https://forem.com/ompals/leetcodes-runtime-beats-x-is-x-reliable-3j3j</guid>
      <description>&lt;h2&gt;
  
  
  Introduction
&lt;/h2&gt;

&lt;p&gt;It's been a while I have been solving Leetcode problems. I always notice that Leetcode says my code sucks by showing me the image given below.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F7c3qq4z4si6xxset5rnl.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F7c3qq4z4si6xxset5rnl.png" alt="Solution beats x%" width="359" height="190"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;h2&gt;
  
  
  Digging deep into the matter
&lt;/h2&gt;

&lt;p&gt;Let's say you are solving a hard problem, which requires you to think about more optimal approach. You bring down the complexity from O(n^2) to O(nlogn) or better =&amp;gt; O(n). Or just O(1) (Who knows lol!). And suddenly you went from beats 5% to beats 100%! Which is amazing. You actually solved the problem the right way! &lt;/p&gt;

&lt;p&gt;But let's say you are just warming up. You know the problem will be solved in O(n) only. You code it the right way. Optimized and removed unnecessary calculations and still your solution beats 5%. It is taking around 500ms more. &lt;/p&gt;

&lt;p&gt;When you look at the 100% beats solutions, they have done some nasty optimizations on low level (like, on reading input etc), but for the solutions which are just same as yours beat you. In that case, the runtime estimations become unreliable. &lt;/p&gt;

&lt;h2&gt;
  
  
  Conclusion
&lt;/h2&gt;

&lt;p&gt;Look at the top solutions to know what low level optimizations are done and practice them. Learn to implement them. If you have something better, then congrats. Else, just move to the next problem. &lt;/p&gt;

</description>
      <category>competativeprogramming</category>
      <category>leetcode</category>
    </item>
    <item>
      <title>SWITCH your guess! | Monty hall problem explained</title>
      <dc:creator>Omi</dc:creator>
      <pubDate>Wed, 12 Mar 2025 21:06:11 +0000</pubDate>
      <link>https://forem.com/ompals/monte-hall-problem-simplified-36fk</link>
      <guid>https://forem.com/ompals/monte-hall-problem-simplified-36fk</guid>
      <description>&lt;h2&gt;
  
  
  &lt;strong&gt;Introduction&lt;/strong&gt;
&lt;/h2&gt;

&lt;p&gt;Every engineering student who learns probability and statistics has encountered this famous problem. You can refer to &lt;a href="https://en.wikipedia.org/wiki/Monty_Hall_problem" rel="noopener noreferrer"&gt;this link&lt;/a&gt; for the problem statement. &lt;em&gt;(But don't look at the answers yet!)&lt;/em&gt;&lt;/p&gt;

&lt;h3&gt;
  
  
  &lt;strong&gt;The Common Misconception&lt;/strong&gt;
&lt;/h3&gt;

&lt;p&gt;Many people assume:  &lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;&lt;em&gt;"The probability of getting a car behind either of the remaining two doors is 1/2, since one has a goat and the other has a car."&lt;/em&gt;&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;But this is incorrect.&lt;/p&gt;




&lt;h2&gt;
  
  
  &lt;strong&gt;Correct Solution Approach&lt;/strong&gt;
&lt;/h2&gt;

&lt;h3&gt;
  
  
  &lt;strong&gt;Step 1: Define the Events&lt;/strong&gt;
&lt;/h3&gt;

&lt;div class="table-wrapper-paragraph"&gt;&lt;table&gt;
&lt;thead&gt;
&lt;tr&gt;
&lt;th&gt;Notation&lt;/th&gt;
&lt;th&gt;Meaning&lt;/th&gt;
&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;
&lt;tr&gt;
&lt;td&gt;Hx&lt;/td&gt;
&lt;td&gt;Host places a car behind door x&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Py&lt;/td&gt;
&lt;td&gt;Player initially selects door y&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;&lt;/div&gt;

&lt;p&gt;&lt;strong&gt;Possible event space&lt;/strong&gt;&lt;/p&gt;

&lt;div class="table-wrapper-paragraph"&gt;&lt;table&gt;
&lt;thead&gt;
&lt;tr&gt;
&lt;th&gt;Host&lt;/th&gt;
&lt;th&gt;P1&lt;/th&gt;
&lt;th&gt;P2&lt;/th&gt;
&lt;th&gt;P3&lt;/th&gt;
&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;
&lt;tr&gt;
&lt;td&gt;H1&lt;/td&gt;
&lt;td&gt;(H1 and P1)&lt;/td&gt;
&lt;td&gt;(H1 and P2)&lt;/td&gt;
&lt;td&gt;(H1 and P3)&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;H2&lt;/td&gt;
&lt;td&gt;(H2 and P1)&lt;/td&gt;
&lt;td&gt;(H2 and P2)&lt;/td&gt;
&lt;td&gt;(H2 and P3)&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;H3&lt;/td&gt;
&lt;td&gt;(H3 and P1)&lt;/td&gt;
&lt;td&gt;(H3 and P2)&lt;/td&gt;
&lt;td&gt;(H3 and P3)&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;&lt;/div&gt;

&lt;p&gt;Each event is &lt;strong&gt;equally likely&lt;/strong&gt;, meaning each has a probability of &lt;strong&gt;1/9&lt;/strong&gt;.&lt;/p&gt;

&lt;h3&gt;
  
  
  &lt;strong&gt;Step 2: Categorizing the Event Space&lt;/strong&gt;
&lt;/h3&gt;

&lt;p&gt;Let's break this event space into two cases:  &lt;/p&gt;

&lt;h4&gt;
  
  
  &lt;strong&gt;Case 1: Player initially selects the door with the car&lt;/strong&gt; &lt;em&gt;(x = y)&lt;/em&gt;
&lt;/h4&gt;

&lt;ul&gt;
&lt;li&gt;Events: &lt;strong&gt;(H1, P1), (H2, P2), (H3, P3)&lt;/strong&gt;
&lt;/li&gt;
&lt;li&gt;Probability:&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;P([x=y]) = 1/9 + 1/9 + 1/9 &lt;br&gt;
         = 3/9 &lt;br&gt;
         = 1/3 &lt;/p&gt;

&lt;h4&gt;
  
  
  &lt;strong&gt;Case 2: Player initially selects a door with a goat&lt;/strong&gt; &lt;em&gt;(x ≠ y)&lt;/em&gt;
&lt;/h4&gt;

&lt;ul&gt;
&lt;li&gt;Events: &lt;strong&gt;(H1, P2), (H1, P3), (H2, P1), (H2, P3), (H3, P1), (H3, P2)&lt;/strong&gt;
&lt;/li&gt;
&lt;li&gt;Probability:
&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;P([x!=y]) = 1 - P([x=y])&lt;br&gt;
          = 1 - 1/3&lt;br&gt;
          = 2/3&lt;/p&gt;




&lt;h2&gt;
  
  
  &lt;strong&gt;Step 3: What Happens After Switching?&lt;/strong&gt;
&lt;/h2&gt;

&lt;h3&gt;
  
  
  &lt;strong&gt;Case 1: Player Initially Chose the Car (x = y)&lt;/strong&gt;
&lt;/h3&gt;

&lt;ul&gt;
&lt;li&gt;The host opens a door with a goat.
&lt;/li&gt;
&lt;li&gt;The player switches, he &lt;strong&gt;lose&lt;/strong&gt;.
&lt;/li&gt;
&lt;li&gt;Probability of winning after switching: &lt;strong&gt;0&lt;/strong&gt;.&lt;/li&gt;
&lt;/ul&gt;

&lt;h3&gt;
  
  
  &lt;strong&gt;Case 2: Player Initially Chose a Goat (x ≠ y)&lt;/strong&gt;
&lt;/h3&gt;

&lt;ul&gt;
&lt;li&gt;The host reveals the remaining goat.
&lt;/li&gt;
&lt;li&gt;The player switches, he &lt;strong&gt;wins&lt;/strong&gt;. 🎉
&lt;/li&gt;
&lt;li&gt;Probability of winning after switching: &lt;strong&gt;1&lt;/strong&gt;.
This case is important, so let me give you an example: 
&lt;strong&gt;&lt;u&gt;_ H1 and P2, then host reveals door 3 (neither door 1 nor 2 because 1 has a car and 2 was chosen by the player). So, the player switches to door 1. The only option. Which is a win!_&lt;/u&gt;&lt;/strong&gt;
&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Hence, [x!=y] events followed by a switch will always win. &lt;br&gt;
P(win after switch | [x!=y]) = 1.&lt;/p&gt;

&lt;p&gt;Thus, the overall probability of winning after switching is:&lt;/p&gt;

&lt;p&gt;P(win after switch) = P([x!=y])*P(win after switch | [x!=y]) &lt;br&gt;
                    + P([x=y])*P(win after switch | x=y)&lt;br&gt;
                    = 1*2/3 + 0*1/3&lt;br&gt;
                    = 2/3&lt;/p&gt;

&lt;h3&gt;
  
  
  &lt;strong&gt;Conclusion: Always Switch!&lt;/strong&gt;
&lt;/h3&gt;

&lt;p&gt;If you &lt;strong&gt;always switch&lt;/strong&gt;, you &lt;strong&gt;double your chances&lt;/strong&gt; of winning (from &lt;strong&gt;1/3&lt;/strong&gt; to &lt;strong&gt;2/3&lt;/strong&gt;).  &lt;/p&gt;

&lt;div class="table-wrapper-paragraph"&gt;&lt;table&gt;
&lt;thead&gt;
&lt;tr&gt;
&lt;th&gt;Strategy&lt;/th&gt;
&lt;th&gt;Probability of Winning&lt;/th&gt;
&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;
&lt;tr&gt;
&lt;td&gt;Staying with original choice&lt;/td&gt;
&lt;td&gt;&lt;strong&gt;1/3 (33.33%)&lt;/strong&gt;&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Switching doors&lt;/td&gt;
&lt;td&gt;&lt;strong&gt;2/3 (66.67%)&lt;/strong&gt;&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;&lt;/div&gt;

&lt;p&gt;Just imagine a game, you can win 66.67% times! &lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fdxunfew9kq8aayt0vwou.jpg" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fdxunfew9kq8aayt0vwou.jpg" alt="Image description" width="302" height="167"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;h3&gt;
  
  
  &lt;strong&gt;Intuition&lt;/strong&gt;
&lt;/h3&gt;

&lt;ul&gt;
&lt;li&gt;If your first pick was a goat (which happens &lt;strong&gt;2/3&lt;/strong&gt; of the time), switching gives you the car.
&lt;/li&gt;
&lt;li&gt;If your first pick was a car (&lt;strong&gt;1/3&lt;/strong&gt; of the time), switching makes you lose.
&lt;/li&gt;
&lt;li&gt;Since getting a goat first is more likely, &lt;strong&gt;switching is the best strategy&lt;/strong&gt;.&lt;/li&gt;
&lt;/ul&gt;




&lt;blockquote&gt;
&lt;p&gt;🎯 &lt;strong&gt;Key Takeaway:&lt;/strong&gt; Pay attention to what information is getting revealed and there is a reason why the host revealed a door. &lt;/p&gt;
&lt;/blockquote&gt;




&lt;h2&gt;
  
  
  &lt;strong&gt;Follow-up Question&lt;/strong&gt;
&lt;/h2&gt;

&lt;p&gt;If a player plays &lt;strong&gt;100 rounds&lt;/strong&gt; of this game, what should be their strategy to maximize their wins?  &lt;/p&gt;




&lt;h2&gt;
  
  
  References:
&lt;/h2&gt;

&lt;p&gt;1) Wikipedia&lt;br&gt;
2) A good friends circle&lt;br&gt;
3) Cover image picked up from here: &lt;a href="https://images.app.goo.gl/Mz6LWWvJyxxXsQyT8" rel="noopener noreferrer"&gt;https://images.app.goo.gl/Mz6LWWvJyxxXsQyT8&lt;/a&gt;&lt;/p&gt;

</description>
      <category>probability</category>
    </item>
    <item>
      <title>STOP Debugging using console logs!!!</title>
      <dc:creator>Omi</dc:creator>
      <pubDate>Tue, 25 Feb 2025 11:48:23 +0000</pubDate>
      <link>https://forem.com/ompals/stop-debugging-using-console-logs-2ifc</link>
      <guid>https://forem.com/ompals/stop-debugging-using-console-logs-2ifc</guid>
      <description>&lt;p&gt;It is 2025, almost 13 years since Node.js exists and I have seen people still debugging their backend code using console.log. 🤯😩&lt;/p&gt;

&lt;p&gt;I am experienced in building .NET web APIs applications as well. The Visual Studio IDE (Not VS Code) indeed has some sophisticated tools for debugging, like step into function, next line, come out of function, check running memory usage etc. I enjoyed coding in that phase of my career. &lt;/p&gt;

&lt;p&gt;Recently since I started using Node.js in a project, I always wondered how? How the whole team in this project is missing their debugging console logs in production code? How come no one is using &lt;code&gt;node inspect server.js&lt;/code&gt; ? WHYYY???? (Sorry, I made this sound like an Instagram reel)&lt;/p&gt;

&lt;p&gt;Mentioned below are the steps to use a debugger for Node.js that looks like this: &lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fhhdegfjdlcmtnt561x20.gif" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fhhdegfjdlcmtnt561x20.gif" alt="Image description" width="640" height="480"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Prerequisites&lt;/strong&gt;&lt;br&gt;
The mentioned below software should be installed on your system: &lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Node.js &lt;/li&gt;
&lt;li&gt;Chrome browser &lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Step by step guide&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;1) You should have something to debug. If don't, then use the code sample below and save it in a file called orders.js in your project directory.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// orders.js
let orders = [341, 454, 198, 264, 307];

let totalOrders = 0;

for (let i = 0; i &amp;lt;= orders.length; i++) {
  totalOrders += orders[i];
}

console.log(totalOrders);
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;2) Run the above code using following command in the terminal.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;node orders.js
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;It returned &lt;code&gt;NaN&lt;/code&gt; which is expected. (Since in the last iteration, we did sum + undefined (orders[5])).&lt;/p&gt;

&lt;p&gt;3) To debug this code line by line, run the mentioned below command:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;node inspect orders.js
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This will start a console like this:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;lt; Debugger listening on ws://127.0.0.1:9229/148789b7-6788-40b5-beb1-d15c246dcda7
&amp;lt; For help, see: https://nodejs.org/en/docs/inspector
&amp;lt;
connecting to 127.0.0.1:9229 ... ok
&amp;lt; Debugger attached.
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Wait till &lt;code&gt;&amp;lt; Debugger attached.&lt;/code&gt; appears on your console.&lt;/p&gt;

&lt;p&gt;4) Go to &lt;strong&gt;&lt;u&gt;chrome://inspect&lt;/u&gt;&lt;/strong&gt; on your Chrome browser. This opens chrome devtools. From the log mentioned in above step, Debugger is attached on port &lt;strong&gt;9229&lt;/strong&gt;. You will see the same under localhost section. Refer to the image below: &lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F6i7eldkgb3qpcje9oyr5.jpg" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F6i7eldkgb3qpcje9oyr5.jpg" alt="Image description" width="800" height="506"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;5) Click on &lt;code&gt;inspect&lt;/code&gt; and you will see a familiar looking window! 😃&lt;/p&gt;

&lt;p&gt;Next steps: &lt;br&gt;
Explore the right hand side of this screen which has these features: &lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fqzdfcelgnsye2zhweefy.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fqzdfcelgnsye2zhweefy.png" alt="Image description" width="464" height="554"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;1) Watch&lt;br&gt;
2) Breakpoints&lt;br&gt;
3) Scope&lt;br&gt;
4) Call stack&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Note&lt;/strong&gt;&lt;br&gt;
Debuggers are powerful tools. Obvious human errors are caught in a sight (like in the example given above), but sometimes, you need to use debugger. &lt;/p&gt;

&lt;p&gt;&lt;strong&gt;On a higher note&lt;/strong&gt;&lt;br&gt;
Now that I have made easy for you to debug the code, do not overkill on a bug using this debugger as your go-to solution. Get the overview of the code, understand the pain points like slow running functions, memory usage spiking functions etc and narrow down the scope of your debugging first. &lt;br&gt;
Have some entities to keep a watch on first and also, understand the how Node.js executes the js code in the main thread. Combining your own diagnosis skills along with debuggers will not let AI take-over your job for sure! &lt;/p&gt;

&lt;p&gt;References: &lt;br&gt;
&lt;a href="https://nodejs.org/en/learn/getting-started/debugging#chrome-devtools-55-microsoft-edge" rel="noopener noreferrer"&gt;https://nodejs.org/en/learn/getting-started/debugging#chrome-devtools-55-microsoft-edge&lt;/a&gt;&lt;br&gt;
&lt;a href="https://www.digitalocean.com/community/tutorials/how-to-debug-node-js-with-the-built-in-debugger-and-chrome-devtools" rel="noopener noreferrer"&gt;https://www.digitalocean.com/community/tutorials/how-to-debug-node-js-with-the-built-in-debugger-and-chrome-devtools&lt;/a&gt;&lt;/p&gt;

</description>
      <category>node</category>
      <category>debugging</category>
      <category>inspect</category>
    </item>
    <item>
      <title>Will it catch?🤯</title>
      <dc:creator>Omi</dc:creator>
      <pubDate>Sat, 22 Feb 2025 18:24:52 +0000</pubDate>
      <link>https://forem.com/ompals/nodejs-interview-question-finite-and-infinite-2319</link>
      <guid>https://forem.com/ompals/nodejs-interview-question-finite-and-infinite-2319</guid>
      <description>&lt;p&gt;Was just recovering from last Node.js blocking non-blocking stuff, I come to another JS injury called error-handling with promises. &lt;/p&gt;

&lt;p&gt;This injury was again caused to me by not being able to distinguish between blocking and non-blocking code. &lt;/p&gt;

&lt;p&gt;The below question is from &lt;a href="https://javascript.info/promise-error-handling#tasks" rel="noopener noreferrer"&gt;javascript.info&lt;/a&gt; website.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;What do you think? Will the .catch trigger? Explain your answer.&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;new Promise(function (resolve, reject) {
  setTimeout(() =&amp;gt; {
    throw new Error("Whoops!");
  }, 1000);
}).catch(console.error);
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The hint: Look at the code like this:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;new Promise(function (resolve, reject) 
// try {
{
  setTimeout(() =&amp;gt; {
    throw new Error("Whoops!");
  }, 1000);
})
//} catch {
.catch(console.error);
// }
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Comment down your answer below! &lt;/p&gt;

</description>
      <category>promise</category>
      <category>async</category>
      <category>errors</category>
    </item>
    <item>
      <title>Node.js Interview question: finite and infinite</title>
      <dc:creator>Omi</dc:creator>
      <pubDate>Wed, 19 Feb 2025 07:47:04 +0000</pubDate>
      <link>https://forem.com/ompals/nodejs-interview-question-finite-and-infinite-ki8</link>
      <guid>https://forem.com/ompals/nodejs-interview-question-finite-and-infinite-ki8</guid>
      <description>&lt;p&gt;So recently, I was giving some interviews regarding Node.js and the interviewer asked me the below question: &lt;/p&gt;

&lt;p&gt;The question: Refer to the codebase below and answer: what happens when we hit /infinite followed by a /finite? &lt;br&gt;
Will the /finite gets stuck or will it return &lt;code&gt;Hello World&lt;/code&gt; in response?&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const express = require("express");
const app = express();
const port = 3000;

app.get("/infinite", (req, res) =&amp;gt; {
  while (true) {}
  res.send("Never happens");
});

app.get("/finite", (req, res) =&amp;gt; {
  res.send("Hello World!");
});

app.listen(port, () =&amp;gt; {
  console.log(`Example app listening on port ${port}`);
});

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Answer: It will get stuck. &lt;/p&gt;

&lt;p&gt;The hint: Never block the main thread. This is the basic. But what does it really mean by not to block main thread? &lt;/p&gt;

&lt;p&gt;To understand it, let's twist the above question a bit. Instead of putting a &lt;code&gt;synchronous&lt;/code&gt; infinite loop, we put an &lt;code&gt;asynchronous&lt;/code&gt; timeout of 10 seconds in the /infinite API. Now, the question is, will the finite API respond after 10 seconds or will it respond immediately? &lt;/p&gt;

&lt;p&gt;Code:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const express = require("express");
const app = express();
const port = 3000;

const setTimeoutPromise = () =&amp;gt;
  new Promise((resolve, reject) =&amp;gt; {
    setTimeout(() =&amp;gt; {
      resolve("Timer completed");
    }, 10000);
  });

app.get("/infinite", async (req, res) =&amp;gt; {
  console.log("infinite");
  console.log("timestamp", new Date());
  // while (true) {}
  await setTimeoutPromise();
  res.send("executed after 10 seconds");
});

app.get("/finite", async (req, res) =&amp;gt; {
  console.log("finite");
  console.log("timestamp", new Date());
  res.send("Hello World!");
});

app.listen(port, () =&amp;gt; {
  console.log(`Example app listening on port ${port}`);
});

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Answer: Now, the /finite responds immediately. After completing its 10 seconds, /infinite will respond with "executed after 10 seconds".&lt;/p&gt;

&lt;p&gt;Reason: Javascript (V8 engine) runs the program in a single thread (aka main thread). Even if it is written inside an event listener or in a callback function of an async method (eg. fs.readFile("path/to/file", "", &lt;strong&gt;callback&lt;/strong&gt;)). Node.js will put any Javascript synchronous code in the main thread.  &lt;/p&gt;

&lt;p&gt;&lt;code&gt;while(true) {}&lt;/code&gt; is a synchronous code.&lt;/p&gt;

&lt;p&gt;&lt;code&gt;setTimeout&lt;/code&gt; is an asynchronous code. Simply means, the code requires OS resources (in this case -&amp;gt; timer). Since we have wrapped the setTimeout inside a promise and sending the response only after the promise is fulfilled, the main thread stalls the execution of &lt;code&gt;/infinite&lt;/code&gt; function and make the main thread available. &lt;strong&gt;&lt;em&gt;&lt;u&gt;This is where the Node.js becomes non-blocking.&lt;/u&gt;&lt;/em&gt;&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;At this point, during the 10 seconds of the /infinite, any new event's (in this case, get call for /finite api) javascript code is ready to push into the main thread and execute. &lt;/p&gt;

&lt;p&gt;After the timeout completes, the callback function mentioned inside the setTimeout will again come to the main thread for the javascript code execution. &lt;/p&gt;

&lt;p&gt;Unfortunately, I could not find any sophisticated debugger that tells the developer that, hey! this is synchronous code, this is gonna block the main thread, or hey! this is a non-blocking code and your code will handle another request successfully!!! &lt;/p&gt;

&lt;p&gt;Just have to read and practice through it, make cases by your own and understand between sync and async before jumping into the event-loop! &lt;/p&gt;

&lt;p&gt;Follow up question: &lt;br&gt;
If I modify the setTimeoutPromise like this:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const setTimeoutPromise = () =&amp;gt;
  new Promise((resolve, reject) =&amp;gt; {
    setTimeout(() =&amp;gt; {
      resolve("Timer completed");
      while(true) {} // blocking it here lol! 
    }, 10000);
  });

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;What happens to the finite call that is executed &lt;br&gt;
1) between the 10 seconds &lt;br&gt;
2) after 10 seconds? &lt;/p&gt;

&lt;p&gt;Comment below!&lt;/p&gt;

</description>
      <category>node</category>
      <category>http</category>
      <category>eventloop</category>
      <category>starvation</category>
    </item>
    <item>
      <title>Implementing a basic loading state | useState | Closure</title>
      <dc:creator>Omi</dc:creator>
      <pubDate>Thu, 26 Dec 2024 20:46:37 +0000</pubDate>
      <link>https://forem.com/ompals/implementing-a-basic-loading-state-3nnj</link>
      <guid>https://forem.com/ompals/implementing-a-basic-loading-state-3nnj</guid>
      <description>&lt;h2&gt;
  
  
  How do you create a basic loading state using html, javascript and reactjs hooks?
&lt;/h2&gt;

&lt;p&gt;&lt;strong&gt;Requirements:&lt;/strong&gt; &lt;br&gt;
1) React functional component.&lt;br&gt;
2) It should just return loading text: "Loading".&lt;br&gt;
3) Show the dots being added incrementally (+1) to the end of the loading text every second. &lt;br&gt;
For example: &lt;br&gt;
&lt;code&gt;Loading.&lt;/code&gt; -1s- &lt;code&gt;Loading..&lt;/code&gt; -1s- &lt;code&gt;Loading...&lt;/code&gt; -1s- &lt;code&gt;Loading&lt;/code&gt; &lt;/p&gt;
&lt;h3&gt;
  
  
  Approach:
&lt;/h3&gt;

&lt;p&gt;Decide the static elements. Then add the dynamics (states, hooks etc). As per the &lt;a href="https://react.dev/learn/thinking-in-react" rel="noopener noreferrer"&gt;thinking in React&lt;/a&gt; doc.&lt;/p&gt;
&lt;h4&gt;
  
  
  Static element implementation:
&lt;/h4&gt;

&lt;p&gt;1) Create a functional component that returns "Loading".&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const Loading = () =&amp;gt; {
  const loadingText = "Loading";

  return (
    &amp;lt;div&amp;gt;
      &amp;lt;h2&amp;gt;{loadingText}&amp;lt;/h2&amp;gt;
    &amp;lt;/div&amp;gt;
  );
};

export default Loading;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h4&gt;
  
  
  Dynamics:
&lt;/h4&gt;

&lt;p&gt;1) The number of dots represents a state of the component. So, define a state variable using &lt;code&gt;useState&lt;/code&gt;. Initial value of the state = 1.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const [dots, setDots] = useState(1);
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;And add the dots after loading text&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;{".".repeat(dots)}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;2) A state changes automatically after each second. &lt;code&gt;window.setInterval&lt;/code&gt; can perform this task. Leave the callback function empty for now.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;window.setInterval(() =&amp;gt; {
      // Logic to increment dots
    }, 1000);
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;3) Create a &lt;code&gt;useEffect&lt;/code&gt; hook that only runs once after initial render. Notice the empty array as a second argument. Check this &lt;a href="https://react.dev/reference/react/useEffect#examples-dependencies" rel="noopener noreferrer"&gt;Reactjs doc&lt;/a&gt; to how second arguments behave differently.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;useEffect(() =&amp;gt; {
    window.setInterval(() =&amp;gt; {
      // Logic to increment dots
    }, 1000);
  }, []);
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Till now, the app only shows "Loading.". &lt;br&gt;
Take a pause and think of the logic inside &lt;code&gt;window.setInterval&lt;/code&gt; callback function.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;The obvious looking solution:&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;setDots((dots + 1) % 4);
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;However, the component will only go from &lt;br&gt;
"Loading."-1s-"Loading..". Then it will get stuck. &lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Reason:&lt;/strong&gt; The &lt;code&gt;useEffect's&lt;/code&gt; callback fn is triggered on the initial state of the dots (1) &lt;strong&gt;only&lt;/strong&gt;. &lt;em&gt;Any further state changes in dots state does not affect the &lt;a href="https://www.freecodecamp.org/news/lets-learn-javascript-closures-66feb44f6a44/" rel="noopener noreferrer"&gt;closure&lt;/a&gt; of &lt;code&gt;useEffect's&lt;/code&gt; callback fn.&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;To achieve proper functionality, update it using previous state as per mentioned in the &lt;a href="https://react.dev/reference/react/useState#updating-state-based-on-the-previous-state" rel="noopener noreferrer"&gt;recatjs docs&lt;/a&gt;.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;setDots((dots) =&amp;gt; (dots + 1) % 4);
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The Loading component mounts and unmounts at times. It is a good practice to &lt;a href="https://react.dev/reference/react/useEffect#my-cleanup-logic-runs-even-though-my-component-didnt-unmount" rel="noopener noreferrer"&gt;cleanup&lt;/a&gt; every entities that are created during the useEffect's callback and that is not going to get used anymore. In this case, it is the &lt;code&gt;window.setInterval&lt;/code&gt; definition. &lt;/p&gt;

&lt;p&gt;&lt;em&gt;The cleanup function runs not only during unmount, but before every re-render with changed dependencies.&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;The cleanup logic for useEffect hook can be defined using a callback function that gets returned by the callback function of useEffect. Check the example below:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt; useEffect(() =&amp;gt; {
    const interval = window.setInterval(() =&amp;gt; {
      setDots((dots) =&amp;gt; (dots + 1) % 4);
    }, 1000);

    return () =&amp;gt; {
      window.clearInterval(interval);
    };
  }, []);
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Finally, the implementation of Loading component looks like below:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import { useEffect, useState } from "react";

const Loading = () =&amp;gt; {
  const [dots, setDots] = useState(0); // defined dots state
  const loadingText = "Loading";

  // useEffect hook that gets called on initial render of the Loading component
  useEffect(() =&amp;gt; {
    // Defining interval
    const interval = window.setInterval(() =&amp;gt; {
      // Setting state using a previous state
      setDots((dots) =&amp;gt; (dots + 1) % 4);
    }, 1000);

    // Cleanup logic: 
    return () =&amp;gt; {
      window.clearInterval(interval);
    };
  }, []);

  return (
    &amp;lt;div&amp;gt;
      &amp;lt;h2&amp;gt;
        {loadingText}
        {".".repeat(dots)}
      &amp;lt;/h2&amp;gt;
    &amp;lt;/div&amp;gt;
  );
};

export default Loading;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



</description>
      <category>javascript</category>
      <category>react</category>
      <category>useeffect</category>
      <category>setinterval</category>
    </item>
  </channel>
</rss>
