<?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>DEV Community: Ajay Kumar Verma</title>
    <description>The latest articles on DEV Community by Ajay Kumar Verma (@ajayv1).</description>
    <link>https://dev.to/ajayv1</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%2F473226%2F743f0aad-9ced-40a1-9b5a-13883c9b44f6.jpeg</url>
      <title>DEV Community: Ajay Kumar Verma</title>
      <link>https://dev.to/ajayv1</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://dev.to/feed/ajayv1"/>
    <language>en</language>
    <item>
      <title>How to generate all subarrays in javascript in 2022?</title>
      <dc:creator>Ajay Kumar Verma</dc:creator>
      <pubDate>Wed, 12 Oct 2022 18:46:32 +0000</pubDate>
      <link>https://dev.to/ajayv1/how-to-generate-all-subarrays-in-javascript-in-2022-1jno</link>
      <guid>https://dev.to/ajayv1/how-to-generate-all-subarrays-in-javascript-in-2022-1jno</guid>
      <description>&lt;p&gt;&lt;a href="https://media.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%2Fb184wpdro0fme8zcnp0q.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.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%2Fb184wpdro0fme8zcnp0q.png" alt="How to generate all subarrays in javascript in 2022?"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Hello Readers,&lt;/p&gt;

&lt;p&gt;Interviewers like to ask questions about the subarrays as it gives a clear indication of the logical thinking and aptitude of a candidate.&lt;/p&gt;

&lt;p&gt;Considering the above, we are going to start a new tag MCAIQ (most commonly asked interview questions) on &lt;a href="https://weekendtutorial.com/" rel="noopener noreferrer"&gt;weekendtutorial&lt;/a&gt; that will contain the most frequently asked questions in the interview. This will be your single stop for all such questions and interview preparations.&lt;/p&gt;

&lt;p&gt;we will see how to generate all the subarrays of an array in javascript using iterative and recursive ways both.&lt;/p&gt;




&lt;h2&gt;
  
  
  Generate all subarrays using iteration
&lt;/h2&gt;

&lt;h3&gt;
  
  
  Problem Statement
&lt;/h3&gt;

&lt;p&gt;Given an array, generate all the possible subarrays of the given array using an iterative way.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Input : [1, 2, 3]

Output: [1], [1, 2], [1, 2, 3], [2], [2, 3], [3]

Input: [1, 2]

Output: [1], [1, 2], [2]
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;h3&gt;
  
  
  Implementation
&lt;/h3&gt;


&lt;div class="ltag_gist-liquid-tag"&gt;
  
&lt;/div&gt;






&lt;h2&gt;
  
  
  Generate all subarrays using recursion
&lt;/h2&gt;

&lt;h3&gt;
  
  
  Implementation
&lt;/h3&gt;


&lt;div class="ltag_gist-liquid-tag"&gt;
  
&lt;/div&gt;





&lt;p&gt;I hope you have learned something if you like the article please share it with friends and help &lt;a href="https://weekendtutorial.com/" rel="noopener noreferrer"&gt;weekendtutorial&lt;/a&gt; to grow. This site is run by ads and it is required for it to be alive and grow.&lt;/p&gt;

&lt;p&gt;Read the following articles –&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;&lt;a href="https://weekendtutorial.com/nginx-tutorial/" rel="noopener noreferrer"&gt;Learn Nginx in-depth&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="https://weekendtutorial.com/binary-tree-and-its-traversal-in-javascript/" rel="noopener noreferrer"&gt;Implement binary tree using javascript&lt;/a&gt;&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;This is all for today. Please visit our other articles, and keep learning.&lt;/p&gt;

</description>
      <category>javascript</category>
      <category>programming</category>
      <category>algorithms</category>
      <category>beginners</category>
    </item>
    <item>
      <title>Learn debouncing and throttling in a simple way</title>
      <dc:creator>Ajay Kumar Verma</dc:creator>
      <pubDate>Mon, 26 Sep 2022 10:14:10 +0000</pubDate>
      <link>https://dev.to/ajayv1/learn-debouncing-and-throttling-in-a-simple-way-2e4k</link>
      <guid>https://dev.to/ajayv1/learn-debouncing-and-throttling-in-a-simple-way-2e4k</guid>
      <description>&lt;p&gt;If you’re a frontend developer you must have handled the various events like &lt;code&gt;button clicking&lt;/code&gt;, &lt;code&gt;form submit&lt;/code&gt;, and &lt;code&gt;window scroll events&lt;/code&gt;, etc through &lt;code&gt;event handlers&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;Some events are lightweight and don’t interfere with the &lt;code&gt;UX behavior&lt;/code&gt; but some are just the opposite of it, for instance, it is strongly advised to not attach any event handler on the window &lt;code&gt;scroll event&lt;/code&gt; or &lt;code&gt;resize event&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;The reason is in comparison to other events, depending on the browser and the device the scroll event can fire a lot, which places lots of &lt;code&gt;scroll callbacks&lt;/code&gt; into the &lt;code&gt;callback queue&lt;/code&gt; and &lt;code&gt;call stack&lt;/code&gt;. Thus, the page becomes unresponsive and not scrollable.&lt;/p&gt;

&lt;p&gt;The two widely known techniques that solve the above problem are —&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Debouncing&lt;/li&gt;
&lt;li&gt;Throttling&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Let’s see how debouncing and throttling helps to solve the above problem and other use cases also.&lt;/p&gt;




&lt;h2&gt;
  
  
  What is Debouncing?
&lt;/h2&gt;

&lt;p&gt;Debounce technique can be understood by a &lt;code&gt;timer&lt;/code&gt;. When the button is pressed the timer started. If the button is pressed again before the timer expires, the timer is reset. This ensures that the button can only be registered as being pressed &lt;code&gt;once per debounce period&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--2-kxdGVj--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/5xxiwangsfv5cpn1uhqy.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--2-kxdGVj--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/5xxiwangsfv5cpn1uhqy.png" alt="debounce - grouping the multiple calls to one" width="661" height="133"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Let me take another example, &lt;code&gt;the elevator&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;Imagine you’re in an elevator and the door is about to close. But, just before that another person comes in, the elevator door opens again. Now it waits for another person for a specific time and if no one comes door is closed. So, we see the timer reset on the new call and &lt;code&gt;“group” multiple sequential calls into a single one&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;Other use cases  — &lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;SearchBar &lt;/li&gt;
&lt;li&gt;Autocomplete feature&lt;/li&gt;
&lt;li&gt;Auto-saving user input&lt;/li&gt;
&lt;li&gt;the clicking of a button that makes API calls&lt;/li&gt;
&lt;/ul&gt;

&lt;h3&gt;
  
  
  Implementation of debouncing
&lt;/h3&gt;

&lt;p&gt;Let’s create an &lt;code&gt;index.html&lt;/code&gt; file having an input field.&lt;/p&gt;

&lt;p&gt;On &lt;code&gt;keypress&lt;/code&gt;, we suppose to call an API. Let’s handle this behaviour by debouncing.&lt;/p&gt;


&lt;div class="ltag_gist-liquid-tag"&gt;
  
&lt;/div&gt;


&lt;p&gt;and debounce.js –&lt;/p&gt;


&lt;div class="ltag_gist-liquid-tag"&gt;
  
&lt;/div&gt;


&lt;p&gt;if you check the &lt;code&gt;console&lt;/code&gt;, you will find that the no. of time the event handler called is way less than the actual input size. And thats the big performance boost!&lt;/p&gt;




&lt;h2&gt;
  
  
  What is Throttling?
&lt;/h2&gt;

&lt;p&gt;Throttling technique can be understood by a &lt;code&gt;counter&lt;/code&gt;. When the button is pressed the counter is incremented. Now till the counter reaches a certain threshold all button pressing is ignored. This limits the number of times the button can be registered as being pressed in a given period of time.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s---_iKZqzz--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/av5uconvgyw7wgb93wsf.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s---_iKZqzz--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/av5uconvgyw7wgb93wsf.png" alt="throttle - calling func at a fixed interval" width="880" height="211"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Other use cases — &lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;
&lt;strong&gt;Shooting game&lt;/strong&gt; — Pistol takes 1 sec time between each shot but the user clicks the mouse button multiple times. &lt;/li&gt;
&lt;li&gt;Infinite scrolling&lt;/li&gt;
&lt;/ol&gt;

&lt;h3&gt;
  
  
  Implementation of throttling
&lt;/h3&gt;

&lt;p&gt;Let’s update the above &lt;code&gt;index.html&lt;/code&gt; file with a button.&lt;/p&gt;

&lt;p&gt;On the &lt;code&gt;button click&lt;/code&gt;, we suppose to call an API. Let’s handle this behaviour by throttling.&lt;/p&gt;

&lt;p&gt;throttling.js –&lt;/p&gt;


&lt;div class="ltag_gist-liquid-tag"&gt;
  
&lt;/div&gt;


&lt;p&gt;We can see that button handler will be called at &lt;code&gt;each 500ms&lt;/code&gt; and all the button click within this window is ignored.&lt;/p&gt;




&lt;p&gt;As we have seen the performance benefits of using the &lt;code&gt;debounce and throttle&lt;/code&gt;, based on your use case, you can use it in your code base.&lt;/p&gt;

&lt;p&gt;&lt;em&gt;&lt;strong&gt;Note:&lt;/strong&gt;&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;&lt;code&gt;Underscore and Lodash.js&lt;/code&gt; libraries also have the debounce and throttle method, you can check that as well.&lt;/p&gt;

&lt;p&gt;If you want to know how to create a javascript object, please check –&lt;/p&gt;

&lt;p&gt;&lt;a href="https://weekendtutorial.com/what-is-object-in-javascript-and-how-to-create-it/"&gt;https://weekendtutorial.com/what-is-object-in-javascript-and-how-to-create-it/&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;a href="https://weekendtutorial.com/how-to-implement-binary-heap-in-javascript-in-2022/"&gt;https://weekendtutorial.com/how-to-implement-binary-heap-in-javascript-in-2022/&lt;/a&gt;&lt;/p&gt;

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

&lt;p&gt;&lt;a href="https://johnresig.com/blog/learning-from-twitter/"&gt;Twitter scrolling issue in 2011&lt;/a&gt;&lt;/p&gt;

</description>
    </item>
    <item>
      <title>Binary Heap | How to Implement in Javascript in 2022?</title>
      <dc:creator>Ajay Kumar Verma</dc:creator>
      <pubDate>Thu, 05 May 2022 19:31:25 +0000</pubDate>
      <link>https://dev.to/ajayv1/binary-heap-how-to-implement-in-javascript-in-2022-3dl9</link>
      <guid>https://dev.to/ajayv1/binary-heap-how-to-implement-in-javascript-in-2022-3dl9</guid>
      <description>&lt;p&gt;This article could be considered a complete guide on the binary heap. It contains the definition, its type, applications, and full implementation with an example.&lt;/p&gt;

&lt;h2&gt;
  
  
  Binary Heap
&lt;/h2&gt;

&lt;p&gt;A binary heap is a &lt;code&gt;tree data structure&lt;/code&gt; that has 2 properties  &lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;It should be a perfect binary tree (a.k.a structure-property)&lt;/li&gt;
&lt;li&gt;Each node of the tree should be &lt;code&gt;either ≥ or ≤ than both of its children.&lt;/code&gt; In other words, It should be either Min heap or Max heap. (a.k.a heap property)&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  Perfect Binary Tree
&lt;/h2&gt;

&lt;p&gt;A binary tree that is almost complete, the last level of the tree-filled from left to right.&lt;/p&gt;

&lt;p&gt;e.g tree given in max heap and min heap is an example of a perfect binary tree&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;&lt;em&gt;Note:&lt;/em&gt;&lt;/strong&gt; if you have not read the binary tree before, please checkout&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;p&gt;&lt;a href="https://weekendtutorial.com/binary-tree-and-its-traversal-in-javascript/"&gt;How to implement binary tree in javascript?&lt;/a&gt;&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;a href="https://weekendtutorial.com/binary-tree-the-best-5-coding-questions-you-must-solve/"&gt;Top 5 Basic Must problems in the binary tree&lt;/a&gt;&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  Types of Binary Heap
&lt;/h2&gt;

&lt;p&gt;It is of 2 types — &lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Max Heap&lt;/li&gt;
&lt;li&gt;Min Heap&lt;/li&gt;
&lt;/ol&gt;

&lt;h2&gt;
  
  
  Max Heap
&lt;/h2&gt;

&lt;p&gt;A BH where each node of the tree is &lt;code&gt;≥ (greater than or equal to) than both of its children.&lt;/code&gt; Thus the root of the tree would be maximum among all of the nodes.&lt;/p&gt;

&lt;p&gt;e.g below tree is an example of a Max heap&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--RRpp8wip--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/76qi1mww3a5ekezot3gp.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--RRpp8wip--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/76qi1mww3a5ekezot3gp.png" alt="Max Heap" width="351" height="321"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;h2&gt;
  
  
  Min Heap
&lt;/h2&gt;

&lt;p&gt;A BH where each node of the tree is &lt;code&gt;≤ (smaller than or equal to) than both of its children.&lt;/code&gt; Thus the root of the tree would be minimum among all of the nodes.&lt;/p&gt;

&lt;p&gt;e.g below tree is an example of a Min heap&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--jGMuvOX1--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/d6f1eturzcc3ptd8rqir.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--jGMuvOX1--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/d6f1eturzcc3ptd8rqir.png" alt="Min Heap" width="351" height="321"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;h2&gt;
  
  
  Representation of Binary Heap
&lt;/h2&gt;

&lt;p&gt;A BH can be represented by the list of tree nodes as well by an Array. In this article, we will only focus on the Array representation of it.&lt;/p&gt;

&lt;p&gt;Key points to note here are — &lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;p&gt;the root of the tree is arr[0]&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;for any index i,&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;ol&gt;
&lt;li&gt;parent index = ( i – 1 ) / 2&lt;/li&gt;
&lt;li&gt;left child index = 2 * i + 1&lt;/li&gt;
&lt;li&gt;right child index = 2 * i + 2 &lt;/li&gt;
&lt;/ol&gt;

&lt;h2&gt;
  
  
  Application of Heap
&lt;/h2&gt;

&lt;ol&gt;
&lt;li&gt;Heap Sort&lt;/li&gt;
&lt;li&gt;Priority Queue&lt;/li&gt;
&lt;li&gt;Graph Algorithms (Dijkstra— Shortest Path algorithm, Prims — MST)&lt;/li&gt;
&lt;li&gt;Problems where you need to keep finding min after every iteration e.g&lt;/li&gt;
&lt;/ol&gt;

&lt;ul&gt;
&lt;li&gt;&lt;a href="https://leetcode.com/problems/kth-largest-element-in-an-array"&gt;Kth Largest element in the array&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="https://leetcode.com/problems/task-scheduler"&gt;Task Scheduler&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="https://leetcode.com/problems/maximum-product-of-two-elements-in-an-array"&gt;Maximum Product of 2 elements in an array&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Here is the complete list  of problems on BH — &lt;a href="https://leetcode.com/tag/heap-priority-queue/"&gt;Heap Problems&lt;/a&gt;&lt;/p&gt;

&lt;h2&gt;
  
  
  Binary Max Heap Implementation in Javascript
&lt;/h2&gt;


&lt;div class="ltag_gist-liquid-tag"&gt;
  
&lt;/div&gt;


&lt;h2&gt;
  
  
  Usage
&lt;/h2&gt;

&lt;p&gt;&lt;strong&gt;Approach 1:&lt;/strong&gt; Insert the array elements one by one in the heap. Heap insert function calls function &lt;code&gt;heapifyUp&lt;/code&gt; internally.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;let pq = new BinaryMaxHeap();

let arr = [80,70,40,20,10,60,50,30];

for (let i = 0; i &amp;lt; arr.length; i++) {
    pq.insert(arr[i]);
}

console.log('Heap using approach 1', pq);
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;


&lt;p&gt;&lt;strong&gt;Approach 2:&lt;/strong&gt; Insert complete array elements in the heap (by calling the build_heap function).&lt;/p&gt;

&lt;p&gt;Heap function build_heap calls function &lt;code&gt;heapify which heapify the whole heap.&lt;/code&gt;&lt;br&gt;
&lt;/p&gt;
&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;let pr = new BinaryMaxHeap();

pr.build_heap(arr);

console.log('Heap using approach 2', pr);
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;


&lt;p&gt;&lt;strong&gt;&lt;em&gt;Note:-&lt;/em&gt;&lt;/strong&gt; Both Approaches results in the valid binary max heap. Resulting heap ordering could be same or different.&lt;/p&gt;
&lt;h2&gt;
  
  
  Result
&lt;/h2&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--_lHvln05--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/g26idj12g62epg3cwyhw.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--_lHvln05--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/g26idj12g62epg3cwyhw.png" alt="Testing Binary Max Heap" width="880" height="1080"&gt;&lt;/a&gt;&lt;/p&gt;
&lt;h2&gt;
  
  
  Binary Min Heap Implementation in Javascript
&lt;/h2&gt;


&lt;div class="ltag_gist-liquid-tag"&gt;
  
&lt;/div&gt;



&lt;h2&gt;
  
  
  Usage
&lt;/h2&gt;

&lt;p&gt;&lt;strong&gt;Approach 1:&lt;/strong&gt; Insert the array elements one by one in the heap. Heap insert function calls function &lt;code&gt;heapifyUp&lt;/code&gt; internally.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;let pq = new PriorityQueue();

let arr = [80,70,40,20,10,60,50,30];

for (let i = 0; i &amp;lt; arr.length; i++) {
    pq.insert(arr[i]);
}

console.log('Heap using approach 1', pq);
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Approach 2:&lt;/strong&gt; Insert complete array elements in the heap (by calling the build_heap function).&lt;/p&gt;

&lt;p&gt;Heap function build_heap calls function &lt;code&gt;heapify which heapify the whole heap.&lt;/code&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;let pr = new PriorityQueue();

pr.build_heap(arr);

console.log('Heap using approach 2', pr);
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;&lt;em&gt;Note:-&lt;/em&gt;&lt;/strong&gt; Both Approaches results in the valid binary min heap. Resulting heap ordering could be same or different.&lt;/p&gt;

&lt;h2&gt;
  
  
  Result
&lt;/h2&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--BaAWs6NN--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/zxe34r7d5dumnroapyti.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--BaAWs6NN--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/zxe34r7d5dumnroapyti.png" alt="Binary Min Heap Testing" width="880" height="1100"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;h2&gt;
  
  
  Summary
&lt;/h2&gt;

&lt;p&gt;There are plenty of practical problems that will be solved easily by the &lt;code&gt;binary heap data structure.&lt;/code&gt; It is a must one for all computer science grads. &lt;/p&gt;

&lt;p&gt;In many programming languages, it is provided natively but knowing the core implementation and building a custom one is real learning.&lt;/p&gt;

&lt;p&gt;The code in this article (which is written in javascript) can be imported to other programming languages of your choice.&lt;/p&gt;

&lt;p&gt;Try to build it in the programming language you preferred. &lt;/p&gt;

&lt;p&gt;Keep learning, and stay safe.&lt;/p&gt;

</description>
    </item>
    <item>
      <title>How to integrate Google ReCaptcha v3 correctly in 2022?</title>
      <dc:creator>Ajay Kumar Verma</dc:creator>
      <pubDate>Tue, 12 Apr 2022 08:53:15 +0000</pubDate>
      <link>https://dev.to/ajayv1/how-to-integrate-google-recaptcha-v3-correctly-in-2022-27a8</link>
      <guid>https://dev.to/ajayv1/how-to-integrate-google-recaptcha-v3-correctly-in-2022-27a8</guid>
      <description>&lt;p&gt;A solution to prevent email spamming.&lt;/p&gt;

&lt;p&gt;Google Recaptcha is one of the industry-standard methods that solve the email spamming problem.&lt;/p&gt;

&lt;h2&gt;
  
  
  What is Email Spamming?
&lt;/h2&gt;

&lt;p&gt;Email spam a.k.a &lt;code&gt;junk emails&lt;/code&gt; refers to uninvited emails, usually sent to a large list of recipient email users. This recipient’s email addresses are stolen or purchased by attackers for money theft or commercial purpose depending on what attackers want.&lt;/p&gt;

&lt;p&gt;These emails most of the time have hidden malware that was not supposed to open and if someone opens their mail and clicks the links will become a victim of these attackers.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;e.g.&lt;/strong&gt; &lt;/p&gt;

&lt;p&gt;the places which is the source of the email spam –&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Login, signup and reset password forms on the site&lt;/li&gt;
&lt;li&gt;Comment and contact us section in a blog&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;There are &lt;strong&gt;4 types of Google ReCaptcha&lt;/strong&gt; –&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.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%2F73db5ofnyupsz6g9gz1b.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.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%2F73db5ofnyupsz6g9gz1b.png" alt="Google Recaptcha"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;In this article, we are going to integrate the google ReCaptcha v3 which is the latest.&lt;/p&gt;

&lt;p&gt;If you’re already using Google Recaptcha v2 and you want to move to Google Recaptcha v3, you can read the Google documentation for the same, it is pretty straightforward.&lt;/p&gt;




&lt;h2&gt;
  
  
  Steps to Integrate Google Recaptcha V3
&lt;/h2&gt;

&lt;p&gt;&lt;strong&gt;Step 1. Register your website on recaptcha admin&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;First of all, we need to register the website on the ReCaptcha admin console.&lt;/p&gt;

&lt;p&gt;It looks like this –&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.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%2Fgnxfc96jfhslyl4gacoc.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.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%2Fgnxfc96jfhslyl4gacoc.png" alt="Recpatcha Dashboard"&gt;&lt;/a&gt;&lt;/p&gt;




&lt;p&gt;&lt;strong&gt;Step 2. Client-Side Integration&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;After registering the website on the admin console, note down the reCAPTCHA keys.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;e.g.&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;In the above image, you must be seeing the reCaptcha Keys.&lt;/p&gt;

&lt;p&gt;ReCaptcha gives 2 keys –&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;
&lt;strong&gt;Site Key&lt;/strong&gt; – this is the public key and is used in client-side integration.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Secret Key&lt;/strong&gt; – this is the private key and can’t be exposed to anyone. This should be safely stored in your backend server.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Let’s start with the &lt;code&gt;client-side integration&lt;/code&gt; –&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;1. Load the JavaScript API with your site key&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;&amp;lt;script src="https://www.google.com/recaptcha/api.js?render=&amp;lt;site_key&amp;gt;"&amp;gt;&amp;lt;/script&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;in the above, you will pass the actual &lt;code&gt;Recaptcha Site Key&lt;/code&gt; in the place of &lt;code&gt;&amp;lt;site_key&amp;gt;&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;e.g if the Recaptcha Site Key is &lt;strong&gt;sdfjhjk124jkhk&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;you will pass it as &lt;strong&gt;?render=sdfjhjk124jkhk&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;2. Call &lt;code&gt;grecaptcha.execute&lt;/code&gt; on each action you wish to protect&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;&amp;lt;script&amp;gt;
    function onClick(e) {
        e.preventDefault();
        grecaptcha.ready(function() {
            grecaptcha.execute('reCAPTCHA_site_key', {action: 'submit'}).then(function(token) {
                // Add your logic to submit to your backend server here.
            });
        });
    }
&amp;lt;/script&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Whichever input box you wish to protect, it could be your &lt;code&gt;signup, login or some other field&lt;/code&gt;, you need to update the click handler for that, similar to above.&lt;/p&gt;

&lt;p&gt;You can see the above code, we pass the actual &lt;code&gt;Recaptcha site key&lt;/code&gt; and one callback function to the &lt;code&gt;grecaptcha.execute&lt;/code&gt; function. &lt;/p&gt;

&lt;p&gt;When the callback is executed, we get the token in it. And this token immediately needs to be passed to the backend server for fetching the user score.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;3. Send the token immediately to your backend with the request to verify&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;This will trigger the server-side flow.&lt;/p&gt;




&lt;p&gt;&lt;strong&gt;Step 3. Server-Side Integration&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;With the token passed by the client and with the Recaptcha Secret Key that was already stored at the server-side, the backend will make the call to &lt;code&gt;google site-verify api&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;The google site-verify API returns a &lt;code&gt;score&lt;/code&gt; that is between &lt;code&gt;0.0 to 1.0&lt;/code&gt;. We also set one &lt;code&gt;threshold score default of 0.5&lt;/code&gt; up to which score we will allow users to make requests.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;If the score is less than the threshold score we can say that the user is not human and it’s a bot. 
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;





&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;If the score is &amp;gt;threshold score then the user is human and the actual functionality of click is allowed.
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Request end point&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.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%2Fqypw0l9a42qiq11v7pzy.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.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%2Fqypw0l9a42qiq11v7pzy.png" alt="Request end point"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Site Verify Response&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;The response is a JSON object.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.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%2Fcd1xz0ytnnkxu52dakkp.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.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%2Fcd1xz0ytnnkxu52dakkp.png" alt="Response"&gt;&lt;/a&gt;&lt;/p&gt;




&lt;h2&gt;
  
  
  Challenge
&lt;/h2&gt;

&lt;p&gt;On StackOverflow, I was searching for something and found out most of the people are implementing it incorrectly.&lt;/p&gt;

&lt;p&gt;They are getting the score from server-side and comparing the score and threshold on the client-side which is completely wrong. &lt;/p&gt;

&lt;p&gt;&lt;strong&gt;e.g. Below implementation is wrong&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;&amp;lt;script&amp;gt;
    function onClick(e) {
        e.preventDefault();
        grecaptcha.ready(function() {
            grecaptcha.execute('reCAPTCHA_site_key', {action: 'submit'}).then(function(token) {
                var score = fetchScoreFromAPI(token);
                if (score &amp;gt; THRESHOLD_SCORE) {
                    callCommentApi();
                }
            });
        });
    }
&amp;lt;/script&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The above is incorrect due to –&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;the client never does the validation&lt;/li&gt;
&lt;li&gt;Attackers can easily manipulate the score and see the comment API endpoint and flood it with unsolicited emails.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;&lt;strong&gt;Here is the correct implementation –&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;&amp;lt;script&amp;gt;
    function onClick(e) {
        e.preventDefault();
        grecaptcha.ready(function() {
            grecaptcha.execute('reCAPTCHA_site_key', {action: 'submit'}).then(function(token) {
                callCommentAPI(token);
            });
        });
    }
&amp;lt;/script&amp;gt;

// At server side
function callCommentAPI(token){
    var score = fetchScoreFromAPI(token);
    if (score &amp;gt; THRESHOLD_SCORE) {
        // execute logic for comment API
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;So, we have just passed the token to the existing API and the validation is done at the server-side which is the more secure and correct way of doing it.&lt;/p&gt;

&lt;p&gt;Also, you can notice that even if the comment API URL is exposed to the public but it won’t get spammed as it first checks the score.&lt;/p&gt;




&lt;h2&gt;
  
  
  Summary
&lt;/h2&gt;

&lt;p&gt;I hope you have learned something new. Let me know if you think you can solve it differently or if something is wrong with the article. &lt;/p&gt;

&lt;p&gt;Please read my other popular articles –&lt;/p&gt;

&lt;p&gt;&lt;a href="https://weekendtutorial.com/nginx-tutorial/" rel="noopener noreferrer"&gt;Nginx Tutorial&lt;/a&gt;&lt;br&gt;
&lt;a href="https://weekendtutorial.com/browser-storage-in-detail-part-1/" rel="noopener noreferrer"&gt;Browser Storage&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;That’s all for now, let’s meet next time soon.&lt;/p&gt;

</description>
      <category>javascript</category>
      <category>webdev</category>
      <category>tutorial</category>
      <category>html</category>
    </item>
    <item>
      <title>How to Refactor the global variables in javascript?</title>
      <dc:creator>Ajay Kumar Verma</dc:creator>
      <pubDate>Mon, 21 Mar 2022 19:03:02 +0000</pubDate>
      <link>https://dev.to/ajayv1/how-to-refactor-the-global-variables-in-javascript-482k</link>
      <guid>https://dev.to/ajayv1/how-to-refactor-the-global-variables-in-javascript-482k</guid>
      <description>&lt;p&gt;A deeper dive into the namespace pattern to refactor the global variables.&lt;/p&gt;

&lt;p&gt;We all have heard or read that globals are bad practices.&lt;/p&gt;

&lt;p&gt;Polluting the code space with multiple globals leads to unmanageable and unpredictable code. It is always advisable to keep the globals in check and have it as minimum as possible.&lt;/p&gt;

&lt;p&gt;In this part, we will be discussing one approach that will reduce the global variables with much ease.&lt;/p&gt;

&lt;p&gt;Suppose in your codebase the following globals are present —&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// Constructors
function X() {}
function Y() {}

// global vars
var res = 1;

// global objects
var module1 = {
   a: 1,
   b: 2
};

var module2 = {};
module2.a = 10;
module2.b = 20;

var module3 = {};
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In the above block, we have &lt;strong&gt;&lt;em&gt;6 global variables&lt;/em&gt;&lt;/strong&gt;. Now, we can refactor this code to have only one global object, and all the constructors, variables, and objects will be part of it.&lt;/p&gt;

&lt;p&gt;Ideally, all codebases should thrive to have a single global variable. &lt;/p&gt;

&lt;p&gt;Having multiple globals are bad because of many reasons — &lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;they could be modified accidentally and are error-prone.&lt;/li&gt;
&lt;li&gt;also, it may cause name collision with your code or 3rd party library&lt;/li&gt;
&lt;/ol&gt;

&lt;h2&gt;
  
  
  Solution —
&lt;/h2&gt;

&lt;p&gt;Refactored code —&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// Global object
var APP = APP || {};

// Constructors
APP.X = function () {};
APP.Y = function () {};

// variables
APP.res = 1;

// objects
APP.modules.module1 = {a: 1, b: 2};
APP.modules.module2 = {};
APP.modules.module2.a = 10;
APP.modules.module2.b = 20;
APP.modules.module3 = {};
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;There is a problem with the code e.g if you want to use the below&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;var module1 = APP.modules.module1;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;you have to make 3 checks 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;var module1 = APP &amp;amp;&amp;amp; APP.modules &amp;amp;&amp;amp; APP.modules.module1;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;and this is kind of irritating.&lt;/p&gt;

&lt;p&gt;To solve this we need to have a handy function that deals with the &lt;code&gt;namespacing&lt;/code&gt; part. &lt;/p&gt;

&lt;p&gt;Let's call this function &lt;code&gt;‘namespace()’&lt;/code&gt; and use it 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;APP.namespace(‘APP.modules.module1’) 
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;which is equivalent to —&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;var APP = {
   modules: {
      module1: {
      }
   }
};

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

&lt;/div&gt;



&lt;h2&gt;
  
  
  Implementation of namespace() function
&lt;/h2&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;var APP = APP || {};

APP.namespace = function (str) {
  var parts = str.split('.'),
      parent = APP;

  // remove the redundant global
  if (parts[0] === 'APP') {
      parts = parts.slice(1);
  }

  for (var i = 0; i &amp;lt; parts.length; i++) {
      if (typeof parent[parts[i]] === 'undefined') {
          parent[parts[i]] = {};
      }
      parent = parent[parts[i]]; 
  }

  return parent;
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Let's test the above.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--Hi6I4uPf--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/f6qd3f93pyq2kc3dtgog.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--Hi6I4uPf--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/f6qd3f93pyq2kc3dtgog.png" alt="Refactoring global variables" width="880" height="431"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;We can see that —&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;APP.namespace(‘APP.modules.module1’)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;gives the desired result and also passing the &lt;code&gt;APP (the top global object in the namespace)&lt;/code&gt; is redundant. We can achieve the same by passing just &lt;code&gt;modules.module1&lt;/code&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;APP.namespace(‘modules.module1’)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;






&lt;p&gt;Let me know if you like the namespace pattern. If you like my article, please follow me. Thanks for reading the article, See you soon!&lt;/p&gt;

</description>
      <category>javascript</category>
      <category>webdev</category>
      <category>beginners</category>
      <category>tutorial</category>
    </item>
    <item>
      <title>Binary Tree | the best 5 coding questions you must solve</title>
      <dc:creator>Ajay Kumar Verma</dc:creator>
      <pubDate>Thu, 10 Mar 2022 19:55:55 +0000</pubDate>
      <link>https://dev.to/ajayv1/binary-tree-the-best-5-coding-questions-you-must-solve-4nle</link>
      <guid>https://dev.to/ajayv1/binary-tree-the-best-5-coding-questions-you-must-solve-4nle</guid>
      <description>&lt;p&gt;In this article, we will see the top 5 most commonly asked interview problems on binary tree.&lt;/p&gt;

&lt;p&gt;If you’re preparing for the job interviews for the position of &lt;code&gt;software engineer/software developer&lt;/code&gt; or any role related to programming, you have to have a strong grasp of the data structures.&lt;/p&gt;

&lt;p&gt;&lt;code&gt;Non-linear&lt;/code&gt; data structures like &lt;code&gt;Trees&lt;/code&gt;, &lt;code&gt;Graphs&lt;/code&gt; are favorite topics from the interviewer’s point of view. This blog is about the binary tree data structure.&lt;/p&gt;

&lt;p&gt;We have just started the interview problem series where we will see the top interview question that is asked in almost every interview. Along with the problems, we will also provide the solution in detail so that it can be clearer to you.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;&lt;em&gt;Note:&lt;/em&gt;&lt;/strong&gt; If you have not read this, please do it first &lt;a href="https://weekendtutorial.com/binary-tree-and-its-traversal-in-javascript/"&gt;Binary Tree — How to implement using Javascript in 2022?&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;One strong suggestion though — &lt;strong&gt;&lt;em&gt;Try the problems by yourself first.&lt;/em&gt;&lt;/strong&gt; &lt;/p&gt;

&lt;p&gt;Once you’ve exhausted all the options and nothing working out only then check the solution. Believe me, practicing this will boost your confidence.&lt;/p&gt;

&lt;p&gt;You will find that most of the time, you have almost reached the solution. Later this will be programmed in your mind and you’ll be able to find the approaches and reach the solution without any hint or help.&lt;/p&gt;

&lt;h2&gt;
  
  
  List of problems
&lt;/h2&gt;

&lt;ol&gt;
&lt;li&gt;Size of the binary tree (i.e count of all nodes)&lt;/li&gt;
&lt;li&gt;Height of the binary tree&lt;/li&gt;
&lt;li&gt;The maximum node in the binary tree&lt;/li&gt;
&lt;li&gt;The minimum node in the binary tree&lt;/li&gt;
&lt;li&gt;Sum of all nodes in the binary tree&lt;/li&gt;
&lt;/ol&gt;

&lt;h2&gt;
  
  
  Problem 1. Size of the binary tree
&lt;/h2&gt;

&lt;p&gt;The size of the binary tree is the total number of nodes present in the tree.&lt;/p&gt;

&lt;p&gt;for example, the size of the below tree is 8&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--pRK634wz--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/xuxmilu4f7a88hfnu8dt.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--pRK634wz--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/xuxmilu4f7a88hfnu8dt.png" alt="Tree" width="451" height="361"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;Size of tree = size of left subtree + size of right subtree + 1&lt;br&gt;
&lt;/p&gt;
&lt;/blockquote&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;function size(root) {
   if (root === null) return 0;

   return size(root.left) + size(root.right) + 1;
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;TC: O(N) ~ have to visit each node of the tree at most once&lt;br&gt;
SC: O(N) ~ in case of skewed tree&lt;/p&gt;


&lt;h2&gt;
  
  
  2. Height of the binary tree
&lt;/h2&gt;

&lt;p&gt;The height of the tree is the distance of the farthest leaf node from the root node of the tree.&lt;/p&gt;

&lt;p&gt;for example, the height of the below tree is 4&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--pRK634wz--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/xuxmilu4f7a88hfnu8dt.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--pRK634wz--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/xuxmilu4f7a88hfnu8dt.png" alt="Tree" width="451" height="361"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;Height of tree = Max(Height of left subtree, Height of right subtree) + 1&lt;br&gt;
&lt;/p&gt;


&lt;/blockquote&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;function height(root) {
   if (root === null) return 0;
   return Math.max(height(root.left), height(root.right)) + 1;
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;TC: O(N) ~ have to visit each node of the tree at most once&lt;br&gt;
SC: O(N) ~ in case of skewed tree&lt;/p&gt;


&lt;h2&gt;
  
  
  3. The maximum node in the binary tree
&lt;/h2&gt;

&lt;p&gt;The maximum node can be either root node or will be from the left or right subtree.&lt;/p&gt;

&lt;p&gt;If we take the maximum of the above 3, the result will be the maximum node in the tree.&lt;/p&gt;

&lt;p&gt;for example, the maximum of the below tree is 80&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--pRK634wz--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/xuxmilu4f7a88hfnu8dt.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--pRK634wz--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/xuxmilu4f7a88hfnu8dt.png" alt="Tree" width="451" height="361"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;Largest node of tree =&lt;br&gt;
Max(Largest in left subtree, Largest in right subtree, root.data)&lt;br&gt;
&lt;/p&gt;


&lt;/blockquote&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;function largest(root) {
   if (root === null) return 0;
   return Math.max(
        largest(root.left),
        largest(root.right),
        root.data
    );
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;TC: O(N) ~ have to visit each node of the tree at most once&lt;br&gt;
SC: O(N) ~ in case of skewed tree&lt;/p&gt;


&lt;h2&gt;
  
  
  4. The minimum node in the binary tree
&lt;/h2&gt;

&lt;p&gt;The minimum node can be either root node or will be from the left or right subtree.&lt;/p&gt;

&lt;p&gt;If we take the minimum of the above 3, the result will be the minimum node in the tree.&lt;/p&gt;

&lt;p&gt;for example, the minimum of the below tree is 10&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--pRK634wz--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/xuxmilu4f7a88hfnu8dt.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--pRK634wz--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/xuxmilu4f7a88hfnu8dt.png" alt="Tree" width="451" height="361"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;Smallest node of tree =&lt;br&gt;
Min(Smallest in left subtree, Smallest in right subtree, root.data)&lt;br&gt;
&lt;/p&gt;


&lt;/blockquote&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;function smallest(root) {
   if (root === null) return 0;
   return Math.min(
        smallest(root.left),
        smallest(root.right),
        root.data
    );
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;TC: O(N) ~ have to visit each node of the tree at most once&lt;br&gt;
SC: O(N) ~ in case of skewed tree&lt;/p&gt;


&lt;h2&gt;
  
  
  5. Sum of all nodes in the binary tree
&lt;/h2&gt;

&lt;p&gt;To sum all the nodes of the tree we need to visit each node using any tree traversal method. In this, I’m using postorder traversal.&lt;/p&gt;

&lt;p&gt;for example, the maximum of the below tree is 360&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--pRK634wz--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/xuxmilu4f7a88hfnu8dt.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--pRK634wz--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/xuxmilu4f7a88hfnu8dt.png" alt="Tree" width="451" height="361"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;sumTree = sumTree(left subtree) + sumTree(right subtree) + root.data&lt;br&gt;
&lt;/p&gt;


&lt;/blockquote&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;function sumTree(root) {
   if (root === null) return 0;
   return sumTree(root.left) + sumTree(root.right)+root.data;
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;TC: O(N) ~ have to visit each node of the tree at most once&lt;br&gt;
SC: O(N) ~ in case of skewed tree&lt;/p&gt;




&lt;h2&gt;
  
  
  Summary
&lt;/h2&gt;

&lt;p&gt;We have seen the most common problems that are asked in the interviews. We will come up with more problems that will cover the entire tree data structure.&lt;/p&gt;

&lt;p&gt;Please stay along with the &lt;a href="https://weekendtutorial.com/"&gt;weekendTutorial&lt;/a&gt; and medium for the latest articles.&lt;/p&gt;

&lt;p&gt;It would encourage me to write more if you follow me here, I would really appreciate it.&lt;/p&gt;

&lt;p&gt;Thank you for reading this, Let’s meet next time.&lt;/p&gt;

</description>
      <category>dsa</category>
      <category>javascript</category>
      <category>tree</category>
      <category>algorithms</category>
    </item>
    <item>
      <title>Binary Tree – How to implement using Javascript in 2022?</title>
      <dc:creator>Ajay Kumar Verma</dc:creator>
      <pubDate>Sat, 19 Feb 2022 19:55:55 +0000</pubDate>
      <link>https://dev.to/ajayv1/binary-tree-how-to-implement-using-javascript-in-2022-1ead</link>
      <guid>https://dev.to/ajayv1/binary-tree-how-to-implement-using-javascript-in-2022-1ead</guid>
      <description>&lt;p&gt;In this article, we will read about the binary tree in detail. We will see how to build and traverse it in javascript.&lt;/p&gt;

&lt;h2&gt;
  
  
  Tree data structure
&lt;/h2&gt;

&lt;p&gt;A tree is a non-linear data structure that follows some hierarchy. It is a collection of the tree nodes.&lt;/p&gt;

&lt;p&gt;A tree node stores the information about its node value, its left child address, and right child address.&lt;/p&gt;

&lt;p&gt;In a tree, a tree node can have multiple children.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--Vii3WyTP--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ijop4shy8u22mx87js7s.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--Vii3WyTP--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ijop4shy8u22mx87js7s.png" alt="Binary Tree" width="451" height="361"&gt;&lt;/a&gt;&lt;/p&gt;




&lt;h2&gt;
  
  
  Basic Terminology in Tree
&lt;/h2&gt;

&lt;p&gt;Before diving into the code, let’s understand the basic terminologies –&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;root&lt;/strong&gt; – root is the &lt;code&gt;topmost node&lt;/code&gt; of the tree e.g 10 is the root node in the above picture.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;siblings&lt;/strong&gt; – The children of the parent are siblings to each other e.g 20 &amp;amp; 30 are siblings as both are children of node 10.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;cousins&lt;/strong&gt; – uncles’ children are cousins to ourselves e.g node 30 is the uncle of nodes 40 &amp;amp; 50. Hence, nodes 40, 50, 60, and 70 are all cousins.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;height of a node&lt;/strong&gt; – Distance from the &lt;code&gt;current node to the farthest leaf&lt;/code&gt; e.g Height(20) = 2 because 80 is the farthest leaf from node 20.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;depth of a node&lt;/strong&gt; – distance from the root to the node e.g depth(20) = 1 &lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;Height of entire tree = Height of the root node&lt;/p&gt;

&lt;p&gt;Depth of entire tree = Height of entire tree&lt;/p&gt;
&lt;/blockquote&gt;




&lt;h2&gt;
  
  
  Binary Tree data structure
&lt;/h2&gt;

&lt;p&gt;A binary tree is a tree where a tree node can have 0, 1, or 2 children at most.&lt;/p&gt;

&lt;h3&gt;
  
  
  How to Implement binary tree in Javascript?
&lt;/h3&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;function TreeNode(data) {
  this.data = data;
  this.left = null;
  this.right = null;
}

function createTree() {
  let root = new TreeNode(10);

  root.left = new TreeNode(20);
  root.right = new TreeNode(30);

  root.left.left = new TreeNode(40);
  root.left.right = new TreeNode(50);

  root.right.left = new TreeNode(60);
  root.right.right = new TreeNode(70);

  root.left.left.right = new TreeNode(80);

  return root;
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  How to traverse a binary tree?
&lt;/h3&gt;

&lt;p&gt;Traversal means visiting each node of the binary tree.&lt;/p&gt;

&lt;p&gt;There are 3 ways to traverse a binary tree –&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Preorder traversal&lt;/li&gt;
&lt;li&gt;Inorder traversal&lt;/li&gt;
&lt;li&gt;Postorder traversal&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;There is one more traversal &lt;code&gt;Level Order traversal&lt;/code&gt; that is not in the scope of this article. We will read that when we solve the &lt;code&gt;Left View, Right View of the binary tree&lt;/code&gt;, etc.&lt;/p&gt;




&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--UN9XFTAn--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/7mpcjvqlnqhcd8bqrkim.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--UN9XFTAn--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/7mpcjvqlnqhcd8bqrkim.png" alt="Binary Tree" width="451" height="361"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;h3&gt;
  
  
  Preorder Traversal (using recursion)
&lt;/h3&gt;

&lt;p&gt;It traverses the tree in the following fashion – &lt;code&gt;data Left Right&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;The preorder traversal for the above tree is – &lt;code&gt;10 20 40 80 50 30 60 70&lt;/code&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;function preOrder(root) {
  if (root === null) return;

  // print the node data
  console.log(root.data);

  // goto left
  preOrder(root.left);

  // goto right
  preOrder(root.right);
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Time Complexity:&lt;/strong&gt; O(n) (each tree node is processed once)&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Space Complexity:&lt;/strong&gt; O(h) h is the height. of the tree. &lt;/p&gt;

&lt;h3&gt;
  
  
  Preorder Traversal (without recursion)
&lt;/h3&gt;

&lt;p&gt;The recursive one was pretty simple but if you’re going to apply for a software developer position you might be asked to traverse the tree iteratively i.e without recursion.&lt;/p&gt;

&lt;p&gt;We would be using one &lt;code&gt;stack&lt;/code&gt; to remember the previous node and one &lt;code&gt;array&lt;/code&gt; to store the answer.&lt;/p&gt;

&lt;p&gt;To solve this, think of the preorder formula – &lt;code&gt;data left right&lt;/code&gt; and visualize it.&lt;/p&gt;

&lt;p&gt;Consider an example with just 3 nodes –&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;       5

   /       \
 10        15
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;&lt;code&gt;Preorder for this is – 5 10 15&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;Now, after processing node 5, next will be node 10. If we are using a stack and pushing the left and right node of the current node, then the right node will be pushed first and then the left one because we need to traverse left children first.&lt;/p&gt;

&lt;p&gt;If you understood this, the implementation will be easier to understand.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;function preOrder(root) {

  let ans = [];

  if (root === null) return ans;

  // push root into stack
  let stack = [root];

  // loop while stack is not empty
  while (stack.length) {

    let cur = stack.pop();

    // push the node data to ans
    ans.push(cur.data);

    // push right node into stack
    if (cur.right) {
      stack.push(cur.right);
    }

    // push left node into stack
    // as it pushed last so will be pop first
    // i.e this ensures data left right ordering
    if (cur.left) {
      stack.push(cur.left);
    }

  }

  return ans;
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Time Complexity:&lt;/strong&gt; O(n) (each tree node is processed once)&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Space Complexity:&lt;/strong&gt; O(h) + O(n) ~= O(n) h is the height of the tree.&lt;/p&gt;




&lt;h3&gt;
  
  
  Inorder Traversal (using recursion)
&lt;/h3&gt;

&lt;p&gt;It traverses the tree in the following fashion – &lt;code&gt;Left data Right&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;The &lt;code&gt;inorder traversal&lt;/code&gt; for the above tree is – &lt;code&gt;40 80 20 50 10 60 30 70&lt;/code&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;function inOrder(root) {
  if (root === null) return;

  // goto left
  inOrder(root.left);

  // print the node data
  console.log(root.data);

  // goto right
  inOrder(root.right);
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Time Complexity:&lt;/strong&gt; O(n) (each tree node is processed once)&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Space Complexity:&lt;/strong&gt; O(h) h is the height. of the tree.&lt;/p&gt;

&lt;h3&gt;
  
  
  Inorder Traversal (without recursion)
&lt;/h3&gt;

&lt;p&gt;Inorder formula: &lt;code&gt;left data right&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;From the formula, we will follow below steps —&lt;/p&gt;

&lt;p&gt;Step1: We will go to the left and keep pushing every node into the stack.&lt;/p&gt;

&lt;p&gt;Step2: Pop the stack top element&lt;/p&gt;

&lt;p&gt;Step3: goto right and follow Step1&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;function inOrder(root) {

  let ans = [];

  if (root === null) return ans;

  // push root into stack
  let stack = [];

  let cur = root;

  // loop while stack is not empty
  while (cur || stack.length) {

    // goto left
    while(cur) {
      stack.push(cur);
      cur = cur.left;
    }

    // push the node data to ans
    cur = stack.pop();
    ans.push(cur.data);

    // push right node into stack
    cur = cur.right;

  }

  return ans.reverse();
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Time Complexity:&lt;/strong&gt; O(n) (each tree node is processed once)&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Space Complexity:&lt;/strong&gt; O(h) + O(n) ~= O(n) h is the height of the tree.&lt;/p&gt;




&lt;h3&gt;
  
  
  Postorder Traversal (using recursion)
&lt;/h3&gt;

&lt;p&gt;It traverses the tree in the following fashion – &lt;code&gt;Left Right data&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;The postorder traversal for the above tree is – &lt;code&gt;80 40 50 20 60 70 30 10&lt;/code&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;function postOrder(root) {
  if (root === null) return;

  // goto left
  postOrder(root.left);

  // goto right
  postOrder(root.right);

  // print the node data
  console.log(root.data);
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Time Complexity:&lt;/strong&gt; O(n) (each tree node is processed once)&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Space Complexity:&lt;/strong&gt; O(h) h is the height. of the tree.&lt;/p&gt;

&lt;h3&gt;
  
  
  Postorder Traversal (without recursion)
&lt;/h3&gt;

&lt;p&gt;Let’s think of the preorder traversal solution again. This is similar to that.&lt;/p&gt;

&lt;p&gt;preorder formula: &lt;code&gt;data left right&lt;/code&gt;&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;Let's see how can we reach to postorder from the preorder. &lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;Now, &lt;code&gt;reverse the left and right position&lt;/code&gt;, the formula will become &lt;code&gt;data right left&lt;/code&gt; &lt;/p&gt;

&lt;p&gt;And if we &lt;code&gt;reverse the entire formula&lt;/code&gt;, the final formula will become – &lt;code&gt;left right data&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;which is the formula for the &lt;code&gt;postorder traversal&lt;/code&gt;.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;function postOrder(root) {

  let ans = [];

  if (root === null) return ans;

  // push root into stack
  let stack = [root];

  // loop while stack is not empty
  while (stack.length) {

    let cur = stack.pop();

    // push the node data to ans
    ans.push(cur.data);

    // push left node into stack
    if (cur.left) {
      stack.push(cur.left);
    }

    // push right node into stack
    if (cur.right) {
      stack.push(cur.right);
    }
  }

  return ans.reverse();
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Time Complexity:&lt;/strong&gt; O(n) (each tree node is processed once)&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Space Complexity:&lt;/strong&gt; O(h) + O(n) ~= O(n) h is the height of the tree.&lt;/p&gt;




&lt;h3&gt;
  
  
  Conclusion
&lt;/h3&gt;

&lt;p&gt;We have seen the &lt;code&gt;implementation of the binary tree in javascript and its traversal preorder, inorder, and postorder in both recursive and non-recursive ways&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;The idea of this article is to give you consolidated knowledge all at once. From the interview point of view, the non-recursive traversals are very important.&lt;/p&gt;

&lt;p&gt;If you like my article, please &lt;a href="https://www.buymeacoffee.com/ajayv"&gt;buy me a coffee&lt;/a&gt;! &lt;/p&gt;

&lt;p&gt;I'm also on &lt;a href="https://medium.com/@ajayverma_5579"&gt;medium&lt;/a&gt;, please follow me there.&lt;/p&gt;

&lt;p&gt;Thanks for reading the article!&lt;/p&gt;

</description>
      <category>dsa</category>
      <category>javascript</category>
      <category>tree</category>
      <category>algorithms</category>
    </item>
    <item>
      <title>Browser Storage In detail – part 1</title>
      <dc:creator>Ajay Kumar Verma</dc:creator>
      <pubDate>Tue, 08 Feb 2022 20:29:19 +0000</pubDate>
      <link>https://dev.to/ajayv1/browser-storage-in-detail-part-1-4j1e</link>
      <guid>https://dev.to/ajayv1/browser-storage-in-detail-part-1-4j1e</guid>
      <description>&lt;p&gt;Every web developer needs to understand the in and out of &lt;code&gt;browser storage&lt;/code&gt; because this is the prerequisite for making a website and knowing how it works behind the scene.&lt;/p&gt;

&lt;p&gt;It is hard to imagine a website without any storage as every modern website, be it a social website or a big e-commerce website, or just a plain blog static website needs to store something, hence this topic becomes more critical to understand.&lt;/p&gt;

&lt;p&gt;There are a few important keywords coming in the article at multiple places. So, please follow the below definition for those terms –&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;Session&lt;/strong&gt; – session is a browser tab, which is alive if the tab is open and dead when it is closed.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;Static website&lt;/strong&gt; – a website that has the static hardcoded content which doesn’t change much&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;Dynamic website&lt;/strong&gt; – a website where the content of the website is coming dynamically&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;Client&lt;/strong&gt; – a client is a machine that makes the request (from the browser) to the server for some resources&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;Server&lt;/strong&gt; – a server is also a machine that serves the client request&lt;/p&gt;&lt;/li&gt;
&lt;/ol&gt;




&lt;h2&gt;
  
  
  Why do we need browser storage?
&lt;/h2&gt;

&lt;p&gt;One question that would be popping be in your mind is why do we need to store anything. The reason for storage are –&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Data Persistence&lt;/li&gt;
&lt;li&gt;Authentication&lt;/li&gt;
&lt;li&gt;To speed up the application&lt;/li&gt;
&lt;li&gt;Accessibility with low network&lt;/li&gt;
&lt;/ol&gt;

&lt;h3&gt;
  
  
  Data persistence
&lt;/h3&gt;

&lt;p&gt;Sometimes we want to persist some data throughout the session or even when the session ends in the storage for example user state or user-id in a &lt;code&gt;session&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;Based on the user-id in the &lt;code&gt;session storage&lt;/code&gt;, we can say whether the user is logged in or not.&lt;/p&gt;

&lt;p&gt;Most of the applications might be built on the logic when the user hits the login button then post login you keep the user-id from the response in the session storage.&lt;/p&gt;

&lt;p&gt;Now, if the user refreshes the tab, you still want to be logged in, and that will be achieved through the user-id.&lt;/p&gt;

&lt;p&gt;Keeping the user-id in the session is not a problem unless it’s been validated on the backend with each Node or service API request. If the user-id has tampered i.e not correct service APIs can log out the user.&lt;/p&gt;

&lt;p&gt;This is just one use case, there are many where we may require storage for Data persistence.&lt;/p&gt;

&lt;h3&gt;
  
  
  Authentication
&lt;/h3&gt;

&lt;p&gt;Suppose you are building a simple application that supports login. To implement it,&lt;/p&gt;

&lt;p&gt;Store the email and password in the local store and if matches allow the user to log in.&lt;/p&gt;

&lt;p&gt;Thus, storage is helpful in the authentication.&lt;/p&gt;

&lt;h3&gt;
  
  
  Speed up the application
&lt;/h3&gt;

&lt;p&gt;Storing the images and videos or a big API response will speed up the website as it won’t go again to download the image or video or make the API call for the same response again.&lt;/p&gt;

&lt;p&gt;Many companies use the above to save the extra &lt;strong&gt;&lt;em&gt;second&lt;/em&gt;&lt;/strong&gt; that costs for the resources which can be stored.&lt;/p&gt;

&lt;h3&gt;
  
  
  Accessibility with offline/low Network
&lt;/h3&gt;

&lt;p&gt;As most of the places on the planet earth are still with low internet or offline mostly, to target those users, companies are trying to serve their website even in offline mode. &lt;/p&gt;

&lt;p&gt;And it is possible using the &lt;code&gt;service workers, cache storage, and IndexedDB&lt;/code&gt;. I’ll try to write one tutorial that will cover the above later.&lt;/p&gt;

&lt;p&gt;Now it should be clear why we need the storage.&lt;/p&gt;




&lt;p&gt;Before we dive into the client-side storage, we need to revisit the definition of static and dynamic websites –&lt;/p&gt;

&lt;h2&gt;
  
  
  Dynamic Website
&lt;/h2&gt;

&lt;p&gt;Here, the client makes the request to the server for the data to be placed inside the &lt;code&gt;HTML&lt;/code&gt;, once the server gives the data to the client this HTML file gets served.&lt;/p&gt;

&lt;p&gt;The data is stored in the server using some kind of database (i.e &lt;code&gt;server-side storage&lt;/code&gt;) and the server with the help of some server-side code, fetches the data and sends it to the client.&lt;/p&gt;

&lt;p&gt;As data is dynamic and website depends on it, it is known as &lt;code&gt;dynamic websites&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--EhQUiuJH--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/b1d42fk11k3z6krijk0b.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--EhQUiuJH--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/b1d42fk11k3z6krijk0b.png" alt="Dynamic Website" width="701" height="324"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;h2&gt;
  
  
  Static website (using Browser storage behind the scene)
&lt;/h2&gt;

&lt;p&gt;Everything is the same as a dynamic website except the data is stored in the browser (&lt;strong&gt;&lt;em&gt;client-side storage&lt;/em&gt;&lt;/strong&gt; i.e browser storage) through Javascript API. With the help of these Javascript APIs data could be fetched whenever needed.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--dYcpvKOo--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/mkmfsc0ldhl92icdwjjn.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--dYcpvKOo--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/mkmfsc0ldhl92icdwjjn.png" alt="Static Website" width="521" height="121"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;In most cases, both the storage client-side and server-side are used together.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;&lt;em&gt;Note :-&lt;/em&gt;&lt;/strong&gt;&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;&lt;p&gt;There is a size limit on the &lt;code&gt;client-side storage&lt;/code&gt; though, it depends on the browser and user settings but approx. 5MB is the limit on the local storage.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;It is advisable to not store the sensitive data in the &lt;code&gt;client-side storage&lt;/code&gt; because they are less secure and could be easily manipulated.&lt;/p&gt;&lt;/li&gt;
&lt;/ol&gt;




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

&lt;p&gt;This is where the first part concludes. Please wait for the next part, stay tuned!&lt;/p&gt;

&lt;p&gt;If interested in building an application please read &lt;a href="https://weekendtutorial.com/build-a-quote-generator-using-javascript/"&gt;How to Build a Quote Generator using Javascript&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Please follow me on – &lt;a href="https://medium.com/@ajayverma_5579"&gt;medium.com&lt;/a&gt; also for more articles!&lt;/p&gt;

</description>
      <category>javascript</category>
      <category>webdev</category>
      <category>html</category>
      <category>beginners</category>
    </item>
    <item>
      <title>Learn Nginx and its basics in 2022</title>
      <dc:creator>Ajay Kumar Verma</dc:creator>
      <pubDate>Sat, 05 Feb 2022 08:46:53 +0000</pubDate>
      <link>https://dev.to/ajayv1/learn-nginx-and-its-basics-in-2022-4ddb</link>
      <guid>https://dev.to/ajayv1/learn-nginx-and-its-basics-in-2022-4ddb</guid>
      <description>&lt;p&gt;A few weeks ago, I had to do a complex redirect of a request e.g if the request coming to &lt;code&gt;nginx&lt;/code&gt; has a specific query param or is coming from a specific host then internally redirect to a different path. &lt;/p&gt;

&lt;p&gt;I had completed my logic and was certain about its working but as the saying goes — &lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;Your software will eventually fail unless it's verified with all the edge cases.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;However, due to our system dependency, I cannot merge the code to staging dev for testing as in case of &lt;code&gt;nginx&lt;/code&gt; failure, it will block other developers to write/test their node API or client code.&lt;/p&gt;

&lt;p&gt;So, to mitigate this, I have set up the &lt;code&gt;nginx&lt;/code&gt; in my local computer and did thorough testing. Once it’s fine locally, the code is ready to be pushed in staging for further testing. This way I save lots of time without hampering others' work.&lt;/p&gt;

&lt;p&gt;In this article, I’ll walk through the basics of &lt;code&gt;nginx&lt;/code&gt;, installation, and set up locally, setting up logs, and a few others.&lt;/p&gt;

&lt;p&gt;Let’s start with the definition of &lt;code&gt;nginx&lt;/code&gt;.&lt;/p&gt;

&lt;h2&gt;
  
  
  What is Nginx?
&lt;/h2&gt;

&lt;p&gt;&lt;code&gt;Nginx&lt;/code&gt; is a short form of &lt;em&gt;&lt;code&gt;engine x&lt;/code&gt;&lt;/em&gt; is an &lt;code&gt;HTTP&lt;/code&gt; and &lt;code&gt;reverse proxy server&lt;/code&gt;. It is heavily used as a load balancer and serves static files, sometimes even complete static websites like the company’s blog hosted on Nginx!.&lt;/p&gt;

&lt;h3&gt;
  
  
  Load balancer
&lt;/h3&gt;

&lt;p&gt;In simple terms, the Load balancer is like a middle man sitting in between the concerned parties e.g assume A is the list of clients and B is the list of the servers then —&lt;/p&gt;

&lt;h4&gt;
  
  
  Case 1: With No Load Balancer
&lt;/h4&gt;

&lt;p&gt;All incoming requests would be going to just one server which in the worst case, makes it hang or crash. You probably have heard the term &lt;em&gt;&lt;code&gt;Node API or Service API is down&lt;/code&gt;&lt;/em&gt; which means the box or the server serving that API request is hung or crashed due to request overload or OutOfMemory etc. Thus making the UX unresponsive.&lt;/p&gt;

&lt;h4&gt;
  
  
  Case 2: With Load Balancer
&lt;/h4&gt;

&lt;p&gt;All incoming requests will have to go through the Load Balancer. It maintains the routing table and gets notification if any of the boxes or server goes down (through polling). &lt;/p&gt;

&lt;p&gt;It efficiently distributes the network requests across servers and if one server goes down it redirects the requests to others servers that are online. Thus, maintaining the availability of the server always online.&lt;/p&gt;




&lt;h2&gt;
  
  
  Nginx Configuration File
&lt;/h2&gt;

&lt;p&gt;This file is a &lt;em&gt;&lt;code&gt;tree-like&lt;/code&gt;&lt;/em&gt; structure and contains the instructions in the form of rules/blocks.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;# main context (outside any other context i.e global context)

# event context
event {
  worker_connections 1024;
}

#http context
http {

  # server context 
  server {
     # code goes here
  }
  server {
     # another server context, code goes here
  }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Before we dive into creating our own web server, let's learn the &lt;code&gt;Nginx&lt;/code&gt; configuration file structure in a crisp mode -&lt;/p&gt;

&lt;h3&gt;
  
  
  Main Context —
&lt;/h3&gt;

&lt;p&gt;The &lt;code&gt;main context a.k.a. global context&lt;/code&gt; is the topmost context and all other contexts are part of it e.g &lt;code&gt;Event context, HTTP context&lt;/code&gt;. It is used to configure details that affect the entire application on a granular level.&lt;/p&gt;

&lt;h3&gt;
  
  
  Event Context —
&lt;/h3&gt;

&lt;p&gt;Event Context is contained within the &lt;code&gt;Main context&lt;/code&gt;. It deals with connection handling in general. All the directives defined within this context deals with how worker processes should handle the incoming connections.&lt;/p&gt;

&lt;h3&gt;
  
  
  The HTTP Context —
&lt;/h3&gt;

&lt;p&gt;This is the sibling of the &lt;code&gt;Event context&lt;/code&gt; and written side-by-side of the event context rather than nested. This context will hold the majority of the configurations if we are using Nginx as a web server or reverse proxy.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;&lt;em&gt;Note:-&lt;/em&gt;&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;There can only be one &lt;code&gt;Event context and HTTP context&lt;/code&gt; within the &lt;code&gt;nginx&lt;/code&gt; configuration.&lt;/p&gt;

&lt;p&gt;Later in the article, We will see 2 more contexts — server context and location context.&lt;/p&gt;




&lt;h2&gt;
  
  
  How to install Nginx in macOS?
&lt;/h2&gt;

&lt;p&gt;If you are not using brew then install it first. Open your terminal and do the followings —&lt;/p&gt;

&lt;p&gt;install brew&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;/bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)"
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Once the brew is installed, do&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;brew install nginx
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Once nginx is installed, you can verify it by&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;nginx -v
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Above should print &lt;code&gt;nginx version: nginx/&amp;lt;some version number&amp;gt;&lt;/code&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;e.g.
nginx version: nginx/1.21.0
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Once nginx is installed, the brew will create the nginx folder at the below location -&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;/usr/local/etc/nginx
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;the default &lt;code&gt;nginx.conf&lt;/code&gt; will look 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;events {
  worker_connections 1024;
}

http {
  server {
    listen       8080;
    server_name  localhost;
    location / {
      root   html;
      index  index.html index.htm;
    }
  }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;To start the &lt;code&gt;nginx services&lt;/code&gt; do the following —&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;nginx 
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;if there is any error it will be logged in the terminal, to test if it is serving the default HTML file, hit the URL -&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;http://localhost:8080
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;and to stop it —&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;nginx -s stop
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;






&lt;h2&gt;
  
  
  How to serve files from a different location?
&lt;/h2&gt;

&lt;p&gt;Let's modify the &lt;code&gt;nginx.conf&lt;/code&gt; file to read the HTML file from a different location —&lt;/p&gt;

&lt;p&gt;First, create a folder that contains the HTML file &lt;code&gt;index.html&lt;/code&gt; (with below content) that you want to serve e.g I’ve created &lt;code&gt;nginx-poc&lt;/code&gt; inside the Download folder.&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;!DOCTYPE html&amp;gt;
&amp;lt;html lang="en"&amp;gt;
&amp;lt;head&amp;gt;
    &amp;lt;meta charset="UTF-8"&amp;gt;
    &amp;lt;meta http-equiv="X-UA-Compatible" content="IE=edge"&amp;gt;
    &amp;lt;meta name="viewport" content="width=device-width, initial-scale=1.0"&amp;gt;
    &amp;lt;title&amp;gt;Document&amp;lt;/title&amp;gt;
&amp;lt;/head&amp;gt;
&amp;lt;body&amp;gt;
    &amp;lt;h1&amp;gt;This is index html file from nginx-poc folder&amp;lt;/h1&amp;gt;
&amp;lt;/body&amp;gt;
&amp;lt;/html&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Copy the complete path of this folder that will be the &lt;code&gt;root&lt;/code&gt; and open the &lt;code&gt;nginx.conf&lt;/code&gt; to update it&lt;/p&gt;

&lt;p&gt;using vim editor or nano or any other way you prefer to open the file (e.g nano) —&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;nano /usr/local/etc/nginx/nginx.conf
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;and update the root location&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;events {
  worker_connections 1024;
}

http {
  server {
    listen       8080;
    server_name  localhost;
    location / {
      root   /Users/Download/nginx-poc;
      index  index.html index.htm;
    }
  }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Now stop the &lt;code&gt;nginx&lt;/code&gt; and start it again to see the updated changes. Hit the localhost URL with port &lt;code&gt;8080&lt;/code&gt; -&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.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%2Fypx0f0obhdo7si0a54kv.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.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%2Fypx0f0obhdo7si0a54kv.png" alt="Nginx Serving HTML from different location"&gt;&lt;/a&gt;&lt;/p&gt;




&lt;h2&gt;
  
  
  How to do Url redirection?
&lt;/h2&gt;

&lt;p&gt;Sometimes, the need may arise for URL redirection when the existing resource is moved to a different location. Let’s see how can we achieve this —&lt;/p&gt;

&lt;p&gt;Create a &lt;code&gt;js&lt;/code&gt; folder and a few js files in it inside the nginx-poc folder —&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;|-- nginx-poc
| |-- index.html
| |-- js
| | |-- a.js
| | |-- b.js
| | |-- c.js
| | |-- b-latest.js
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;a href="https://media.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%2Fxfyxgc5rpdie63mglvm7.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.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%2Fxfyxgc5rpdie63mglvm7.png" alt="Folder structure"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Just have one simple &lt;code&gt;console.log(&amp;lt;filename&amp;gt;)&lt;/code&gt; inside each js file -&lt;/p&gt;

&lt;p&gt;e.g for a.js&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;console.log('serving a.js');
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;for b-latest.js&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;console.log('serving b-latest.js');
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;and so on.&lt;/p&gt;

&lt;p&gt;Let’s say the file &lt;code&gt;b.js&lt;/code&gt; is no longer useful and we want to serve the &lt;code&gt;b-latest.js&lt;/code&gt; in place of it. Of course, we can say that wherever our anchor link is pointing to &lt;code&gt;b.js&lt;/code&gt; we’ll replace it with the &lt;code&gt;b-latest.js&lt;/code&gt;, but it has 2 issues -&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;It is time-consuming and is error-prone.&lt;/li&gt;
&lt;li&gt;The old URL will give the 404 and that's something we should thrive to reduce. Ideally, there shouldn’t be any 404 redirects, it should be kept as low as possible.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;One simple solution would be to do it from &lt;code&gt;nginx&lt;/code&gt; internal redirect —&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;events {
  worker_connections 1024;
}

http {
  server {
    listen       8080;
    server_name  localhost;

    root   /Users/Download/nginx-poc;

    location /js {
      rewrite /js/b.js /js/b-latest.js break;
    }

    location / {
      # root   /Users/Download/nginx-poc;
      index  index.html index.htm;
    }
  }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Let me go through each change to make it clearer —&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;Commented root in location / —&lt;/strong&gt; This is moved to the server context. Adding the root to the server context makes it available for all the location contexts within it.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;Added location context to handle the /js request —&lt;/strong&gt; This request will handle all the request coming from &lt;code&gt;/js, /js/*&lt;/code&gt; i.e request for &lt;code&gt;/js/b.js&lt;/code&gt; will fall in this location. We are rewriting the request URL internally from &lt;code&gt;/js/b.js&lt;/code&gt; to &lt;code&gt;/js/b-latest.js&lt;/code&gt; and then we are adding a &lt;code&gt;break&lt;/code&gt; which means no more parsing of any other rewrite!&lt;/p&gt;&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;&lt;strong&gt;&lt;em&gt;Note:—&lt;/em&gt;&lt;/strong&gt;&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;&lt;p&gt;The &lt;code&gt;server context&lt;/code&gt; is a child of the &lt;code&gt;HTTP context&lt;/code&gt;. There could be multiple server contexts, unlike event and HTTP context which are allow allowed once.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;The &lt;code&gt;location context&lt;/code&gt; is a child of the &lt;code&gt;server context&lt;/code&gt;. Similar to server context, multiple location contexts are allowed. They are the ones where actual handling of the incoming request is done.&lt;/p&gt;&lt;/li&gt;
&lt;/ol&gt;




&lt;h2&gt;
  
  
  How to add custom logs?
&lt;/h2&gt;

&lt;p&gt;Logs are really important, they are needed to test our logic. In case any issue comes in production code, we can easily debug by seeing the &lt;code&gt;nginx logs&lt;/code&gt;. Let me show you how can we set it up locally so that we can test and view the complete logic along with logs in localhost.&lt;/p&gt;

&lt;p&gt;By default, &lt;code&gt;nginx&lt;/code&gt; has 2 types of logs — &lt;code&gt;access log and error log&lt;/code&gt;&lt;/p&gt;

&lt;h3&gt;
  
  
  Access log —
&lt;/h3&gt;

&lt;p&gt;This logs the visitor's activity e.g requested URL, IP addresses, host, referrer, etc. If a request is served successfully it will log in access.log file.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;access_log &amp;lt;location of log file&amp;gt; log_format;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In &lt;code&gt;log_format&lt;/code&gt;, we can add what data we want to log but just a note, it is an optional thing. &lt;/p&gt;

&lt;p&gt;One important point to remember is log_format must be placed under the &lt;code&gt;HTTP context&lt;/code&gt; otherwise it will throw an error.&lt;/p&gt;

&lt;p&gt;e.g.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Syntax - 

log_format &amp;lt;log_format_name&amp;gt; string;

log_format custom '$remote_addr - $remote_user [$time_local] '
'"$request" "$uri" $status $body_bytes_sent ''"$http_referer" "$http_user_agent" "$gzip_ratio"';
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;a href="https://media.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%2Fq93w3htz2e0wvctahib1.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.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%2Fq93w3htz2e0wvctahib1.png" alt="Sample Nginx Access log"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;h3&gt;
  
  
  Error log —
&lt;/h3&gt;

&lt;p&gt;This logs each glitch and Syslog i.e if a request was not served by any means it will be recorded in the &lt;code&gt;error.log&lt;/code&gt; file.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Syntax -

error_log &amp;lt;location of error.log file&amp;gt; &amp;lt;error-severity-level&amp;gt;

error_log /usr/local/etc/nginx/logs/error.log notice;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Configuration file after adding the logs —&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;events {
  worker_connections 1024;
}

http {
  log_format custom '$remote_addr - $remote_user [$time_local] '
      '"$request" "$uri" $status $body_bytes_sent '
      '"$http_referer" "$http_user_agent" "$gzip_ratio"';

  server {

     listen       80;

     server_name  localhost;

     root   /Users/Downloads/nginx-poc;

     access_log /usr/local/etc/nginx/logs/acess.log custom;
     error_log /usr/local/etc/nginx/logs/error.log notice;
     rewrite_log on;

     location /js {
       rewrite /js/b.js /js/b-latest.js break;
     }

     location / {
       index  index.html index.htm;
     }
   }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The &lt;code&gt;rewrite_log&lt;/code&gt; should be &lt;strong&gt;ON&lt;/strong&gt; to record the internal redirect. Also, &lt;code&gt;notice&lt;/code&gt; severity level means it is just a notice which can be simply ignored i.e nothing serious.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.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%2Fnzru4qgo92ln43c3rpot.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.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%2Fnzru4qgo92ln43c3rpot.png" alt="Nginx error.log logging the redirect"&gt;&lt;/a&gt;&lt;/p&gt;




&lt;h2&gt;
  
  
  How to handle query params?
&lt;/h2&gt;

&lt;p&gt;It may arise a case when we want to internally redirect the request based on query parameters. Let’s see how can we implement the below 3 cases in the &lt;code&gt;nginx.conf&lt;/code&gt; file —&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;events {
  worker_connections 1024;
}

http {
  log_format custom '$remote_addr - $remote_user [$time_local] '
      '"$request" "$uri" $status $body_bytes_sent '
      '"$http_referer" "$http_user_agent" "$gzip_ratio"';

  server {

     listen       80;

     server_name  localhost;

     root   /Users/Downloads/nginx-poc;

     access_log /usr/local/etc/nginx/logs/acess.log custom;
     error_log /usr/local/etc/nginx/logs/error.log notice;
     rewrite_log on;

     location /js {
       if ($query_string ~* "latest=true") {
         rewrite /js/b.js /js/b-latest.js break;
       }

       if ($query_string ~* "latest=false") {
         rewrite /js/b.js /js/c.js  break;
       }

       rewrite /js/b.js /js/a.js break;
     }

     location / {
       index  index.html index.htm;
     }
   }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  Case 1 —
&lt;/h3&gt;

&lt;p&gt;request is for &lt;code&gt;b.js&lt;/code&gt; → serve &lt;code&gt;b-latest.js&lt;/code&gt; iff query params have &lt;code&gt;latest=true&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.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%2Fbcf2pwcx3c1atmcqq7sq.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.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%2Fbcf2pwcx3c1atmcqq7sq.png" alt="serve b-latest.js case 1 when query param latest is true"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;h3&gt;
  
  
  Case 2 —
&lt;/h3&gt;

&lt;p&gt;request is for &lt;code&gt;b.js&lt;/code&gt; → serve &lt;code&gt;c.js&lt;/code&gt; iff query params have &lt;code&gt;latest=false&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.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%2Fgso0f3iqy73k4ablz2yq.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.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%2Fgso0f3iqy73k4ablz2yq.png" alt="serve c.js case 2 when query param latest is false"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;h3&gt;
  
  
  Case 3 —
&lt;/h3&gt;

&lt;p&gt;request is for &lt;code&gt;b.js&lt;/code&gt; → serve &lt;code&gt;a.js&lt;/code&gt; default&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.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%2Fuxlon3e0663lsqhz5xyu.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.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%2Fuxlon3e0663lsqhz5xyu.png" alt="No Query param"&gt;&lt;/a&gt;&lt;/p&gt;




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

&lt;p&gt;Nginx is not just it, and can’t be covered in just one article. But, I hope this will let you get started to know more. With the local setup, It becomes really handy when you want to test your &lt;code&gt;nginx&lt;/code&gt; logic locally before deploying it to your staging or production.&lt;/p&gt;

&lt;p&gt;I really hope you like the article, if yes, please follow me and if possible &lt;a href="https://www.buymeacoffee.com/ajayv" rel="noopener noreferrer"&gt;buy me a coffee&lt;/a&gt;. This article is originally published on my &lt;a href="https://weekendtutorial.com" rel="noopener noreferrer"&gt;website&lt;/a&gt;, keep visiting that also for regular updates.&lt;/p&gt;

&lt;p&gt;Thank You! Stay tuned for more articles.&lt;/p&gt;

</description>
      <category>webdev</category>
      <category>nginx</category>
      <category>node</category>
      <category>javascript</category>
    </item>
    <item>
      <title>Switch statements in javascript – How to refactor?</title>
      <dc:creator>Ajay Kumar Verma</dc:creator>
      <pubDate>Sun, 30 Jan 2022 20:18:17 +0000</pubDate>
      <link>https://dev.to/ajayv1/switch-statements-in-javascript-how-to-refactor-5gl8</link>
      <guid>https://dev.to/ajayv1/switch-statements-in-javascript-how-to-refactor-5gl8</guid>
      <description>&lt;p&gt;The Switch statements are perfectly nice and majorly used in the other traditional language like &lt;code&gt;C, C++, and Java&lt;/code&gt;.&lt;/p&gt;

&lt;h2&gt;
  
  
  Why Switch statement?
&lt;/h2&gt;

&lt;p&gt;The switch statement executes different actions based on the different conditions. Of course, we can solve the above with an &lt;code&gt;if-else&lt;/code&gt; ladder but that will make the program too much clumsy. Also, the &lt;code&gt;if-else&lt;/code&gt; ladder is advisable only if you have a max of &lt;code&gt;3 conditions&lt;/code&gt; to check.&lt;/p&gt;

&lt;p&gt;&lt;code&gt;Javascript&lt;/code&gt; has the switch statement but if you’re interested in &lt;code&gt;python&lt;/code&gt; then just as a side information &lt;code&gt;python doesn’t have the switch statement but it achieves the same with the dictionary mapping&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;Since the &lt;code&gt;dictionary mapping&lt;/code&gt; is similar to object creation in javascript, taking the inspiration from python, we can replace the switch statement with multiple objects which is not a bad idea. This will keep the code &lt;code&gt;simple and maintainable&lt;/code&gt; in long run.&lt;/p&gt;

&lt;p&gt;Let’s see the most occurred examples which we must have faced in our coding career -&lt;/p&gt;




&lt;h2&gt;
  
  
  Example 1
&lt;/h2&gt;

&lt;p&gt;Write a code that returns the todays’ day in string e.g Sunday&lt;/p&gt;

&lt;h3&gt;
  
  
  using the switch statement
&lt;/h3&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;let day = new Date().getDay(); 
switch (day) {
  case 0:
    day = "Sunday";
    break;
  case 1:
    day = "Monday";
    break;
  case 2:
     day = "Tuesday";
    break;
  case 3:
    day = "Wednesday";
    break;
  case 4:
    day = "Thursday";
    break;
  case 5:
    day = "Friday";
    break;
  case 6:
    day = "Saturday";
}
console.log(day); // for 30/01/2022 it will return Sunday
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h4&gt;
  
  
  Output verification from console.log
&lt;/h4&gt;

&lt;p&gt;&lt;a href="https://media.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%2Fgfk6i0tiyrkep95b965n.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.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%2Fgfk6i0tiyrkep95b965n.png" alt="using Switch"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;h3&gt;
  
  
  without switch i.e Refactored code
&lt;/h3&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const day = new Date().getDay();
const dayMapper = {
    0: "Sunday",
    1: "Monday",
    2: "Tuesday",
    3: "Wednesday",
    4: "Thursday",
    5: "Friday",
    6: "Saturday"
};
if (dayMapper.hasOwnProperty(day)) {
  console.log(dayMapper[day]); // Sunday
} else {
  console.log("Something went wrong");
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h4&gt;
  
  
  Output verification from console.log
&lt;/h4&gt;

&lt;p&gt;&lt;a href="https://media.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%2Fqidkw6tc4dk9d483h12t.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.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%2Fqidkw6tc4dk9d483h12t.png" alt="without Switch"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;This is the most basic example, lets's see one more common but complex example&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;UseCase:&lt;/strong&gt; Suppose we have to send a &lt;code&gt;GA event&lt;/code&gt; for a page e.g for the Home page we will be sending the event label as Page name + its current layout name.&lt;/p&gt;

&lt;p&gt;The catch is the page name is coming from the data attribute in DOM.&lt;/p&gt;

&lt;p&gt;Let me explain it further with an example -&lt;/p&gt;

&lt;p&gt;we need to return the (&lt;code&gt;Page name_Layout name&lt;/code&gt;) following for the page name found in the data attribute&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;homePage -&amp;gt; Home_index
productPage -&amp;gt; Product_pdp
blogPage -&amp;gt; Blog_blog
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;






&lt;h2&gt;
  
  
  Example 2
&lt;/h2&gt;

&lt;p&gt;Assume &lt;code&gt;HTML&lt;/code&gt; which has the page name stored in data attribute is written as -&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;HTML for homepage:
&amp;lt;div id="my-div" data-page-name="homepage"&amp;gt;&amp;lt;/div&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  using the switch statement
&lt;/h3&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;let pageName = document.querySelector('#my-div').dataset.pageName;
let page;
let layout;
let ans;
switch (pageName) {
  case "homepage":
    page = "Home";
    layout = "index";
    break;
  case "productpage":
    page = "Product";
    layout = "pdp";
    break;
  case "blogpage":
    page = "Blog";
    layout = "blog";
    break;
}
ans = page + '_' + layout;
console.log(ans);
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h4&gt;
  
  
  Output verification from console.log
&lt;/h4&gt;

&lt;p&gt;&lt;a href="https://media.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%2Fg8cuoztvjj7iqj0okd24.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.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%2Fg8cuoztvjj7iqj0okd24.png" alt="page mapper using switch"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;h3&gt;
  
  
  without switch i.e Refactored code
&lt;/h3&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;let pageName = document.querySelector('#my-div').dataset.pageName;
let dataPageMapper = {
  homepage: 'Home',
  productpage: 'Product',
  blogpage: 'Blog' 
};
let pageLayoutMapper = {
  home: 'index',
  product: 'pdp',
  blog: 'blog' 
};
let page = dataPageMapper.hasOwnProperty(pageName) &amp;amp;&amp;amp; dataPageMapper[pageName];
let layout = pageLayoutMapper[page.toLowerCase()];
let ans = page + '_' + layout;
console.log(ans);
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h4&gt;
  
  
  Output verification from console.log
&lt;/h4&gt;

&lt;p&gt;&lt;a href="https://media.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%2Fzq691g4lpzbnnzwm0or5.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.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%2Fzq691g4lpzbnnzwm0or5.png" alt="page mapper with no switch"&gt;&lt;/a&gt;&lt;/p&gt;

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

&lt;p&gt;Above one is the cleaner way to do it. If in the future, we have more pages available we just need to make the entries in the mapper objects, that's it.&lt;/p&gt;

&lt;p&gt;But with a &lt;code&gt;switch statement&lt;/code&gt;, it will be a long ladder of statements and if you forgot to add the break statement then you will fall into the famous switch pitfalls.&lt;/p&gt;

&lt;p&gt;Let me know your thoughts like how you handle the switch thing in your code.&lt;/p&gt;

&lt;p&gt;If you like my article, you can &lt;a href="https://www.buymeacoffee.com/ajayv" rel="noopener noreferrer"&gt;buy me a coffee&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Please also check my other articles on my website &lt;a href="https://weekendtutorial.com" rel="noopener noreferrer"&gt;https://weekendtutorial.com&lt;/a&gt;&lt;/p&gt;

&lt;h2&gt;
  
  
  Edit
&lt;/h2&gt;

&lt;p&gt;In &lt;code&gt;Example 1&lt;/code&gt; -&lt;/p&gt;

&lt;p&gt;Since array is also an object so we could optimise the code further -&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const dayNum = new Date().getDay();
const days = [
    "Sunday",
    "Monday",
    "Tuesday",
    "Wednesday",
    "Thursday",
    "Friday",
    "Saturday"
];
console.log(days[dayNum]); // Sunday
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In &lt;code&gt;Example 2&lt;/code&gt; -&lt;/p&gt;

&lt;p&gt;We could have club the object 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;let pageName = document.querySelector('#my-div').dataset.pageName;
let dataPageMapper = {
  homepage: {
     page: 'Home',
     layout: 'index'
  },
  productpage: {
     page: 'Product',
     layout: 'pdp'
  },
  blogpage: {
     page: 'Blog',
     layout: 'blog'
  } 
};

let pageObj = dataPageMapper.hasOwnProperty(pageName) &amp;amp;&amp;amp; dataPageMapper[pageName];

let ans = pageObj.page + '_' + pageObject.layout;
console.log(ans);
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Above is also fine, but actual example was taken considering the possibility of when the clubbing the object is least feasible. &lt;/p&gt;

&lt;p&gt;Of course, if the object are coming from different files or place, we can still create another by clubbing them but that will introduce another problem viz. &lt;code&gt;code duplicacy&lt;/code&gt; which should be avoided.&lt;/p&gt;

</description>
      <category>javascript</category>
      <category>webdev</category>
      <category>beginners</category>
      <category>tutorial</category>
    </item>
    <item>
      <title>Build a Quote Generator using Javascript</title>
      <dc:creator>Ajay Kumar Verma</dc:creator>
      <pubDate>Fri, 28 Jan 2022 16:48:42 +0000</pubDate>
      <link>https://dev.to/ajayv1/build-a-quote-generator-using-javascript-39mb</link>
      <guid>https://dev.to/ajayv1/build-a-quote-generator-using-javascript-39mb</guid>
      <description>&lt;p&gt;As part of our weekend tutorial, we will build a Quote generator using Javascript this time. &lt;/p&gt;

&lt;p&gt;Before we implement it, let’s have a glimpse of the final version of what we will make –&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--USQV5HmU--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/eayz3ax26l553lu4iopk.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--USQV5HmU--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/eayz3ax26l553lu4iopk.png" alt="Quote Generator" width="880" height="416"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;This Quote Generator application has the following feature –&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;A button when clicked generate the Quote&lt;/li&gt;
&lt;li&gt;A Twitter button when clicked put the quote to Twitter&lt;/li&gt;
&lt;/ol&gt;




&lt;h2&gt;
  
  
  Project Directory Structure
&lt;/h2&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;|-- quote-generator
| |-- css
| | |-- style.css
| |-- js
| | |-- main.js
| |-- index.html
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;


&lt;p&gt;After you’ve created the above directories in your local machine, please follow along.&lt;/p&gt;


&lt;h2&gt;
  
  
  Quote Generator Implementation
&lt;/h2&gt;

&lt;p&gt;Let’s implement the index.html code first.&lt;/p&gt;
&lt;h3&gt;
  
  
  index.html
&lt;/h3&gt;


&lt;div class="ltag_gist-liquid-tag"&gt;
  
&lt;/div&gt;



&lt;p&gt;At the head of the above HTML file, we have included the quote-specific CSS and font awesome icon CSS (this is for the quote and Twitter icon).&lt;/p&gt;

&lt;p&gt;And in the body of the HTML, a quote-container div is added which will hold the quoted content, quote author, Twitter button, and New Quote button.&lt;/p&gt;

&lt;p&gt;On click of the New Quote button, the next quote will be generated through AJAX request, and its code is written in the main.js file which has been added at the bottom of the body in the HTML file.&lt;/p&gt;

&lt;h3&gt;
  
  
  style.css
&lt;/h3&gt;


&lt;div class="ltag_gist-liquid-tag"&gt;
  
&lt;/div&gt;


&lt;p&gt;We are using the Montserrat google font which is added at the top of the CSS file. Quote Container div in the body is centered using the flex.&lt;/p&gt;

&lt;p&gt;Rest other CSS codes are self-explanatory.&lt;/p&gt;

&lt;h3&gt;
  
  
  main.js
&lt;/h3&gt;


&lt;div class="ltag_gist-liquid-tag"&gt;
  
&lt;/div&gt;


&lt;p&gt;The above code is written in vanilla javascript. Let me explain each function in detail –&lt;/p&gt;

&lt;h4&gt;
  
  
  tweetQuote
&lt;/h4&gt;

&lt;p&gt;This function is responsible for tweeting the quote on Twitter. It calls the tweeter intent API with quoted text and quote-author as a query param.&lt;/p&gt;

&lt;h4&gt;
  
  
  fetchQuote
&lt;/h4&gt;

&lt;p&gt;This is an async function that is responsible for fetching the quotes and returning the promise for the quotes.&lt;/p&gt;

&lt;p&gt;Click listener is bound over the Twitter button and New Quote button which calls the above functions respectively.&lt;/p&gt;




&lt;h2&gt;
  
  
  Challenges
&lt;/h2&gt;

&lt;p&gt;To show the next quote on click of the New Quote button, we need to have the quotes list beforehand otherwise UX will be really bad. &lt;/p&gt;

&lt;p&gt;Now once the API response is received i.e quotes are available, you will feel like storing it to avoid hitting the API again and again on click of the button.&lt;/p&gt;

&lt;p&gt;&lt;code&gt;Storing the response is not necessary, yes, you heard it right!&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;To solve the above without making a request on each button click, we can &lt;code&gt;cache the promise&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;&lt;code&gt;A promise is stateful, and as soon as it’s fulfilled, its value cannot be changed. You can use .then() multiple times to get its contents, and you’ll get the same result every time.&lt;/code&gt;&lt;/p&gt;




&lt;p&gt;So, with &lt;code&gt;quotesPromise.then&lt;/code&gt; we will be getting the quotes list each time and there we pick a random quote that is shown on the quote container.&lt;/p&gt;

&lt;p&gt;That is all in this tutorial. If you like the article please share it with your friends and community.&lt;/p&gt;

&lt;p&gt;Learning Data structure? read my other article — &lt;a href="https://dev.to/ajayv1/reverse-stack-using-javascript-4fmm"&gt;How to implement the stack and reverse it in javascript?&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Check out more such articles and tutorials on &lt;a href="https://weekendtutorial.com/"&gt;https://weekendtutorial.com/&lt;/a&gt;&lt;/p&gt;

</description>
      <category>javascript</category>
      <category>webdev</category>
      <category>beginners</category>
      <category>tutorial</category>
    </item>
    <item>
      <title>Reverse Stack using Javascript</title>
      <dc:creator>Ajay Kumar Verma</dc:creator>
      <pubDate>Sun, 09 Jan 2022 11:50:43 +0000</pubDate>
      <link>https://dev.to/ajayv1/reverse-stack-using-javascript-4fmm</link>
      <guid>https://dev.to/ajayv1/reverse-stack-using-javascript-4fmm</guid>
      <description>&lt;p&gt;In this article, I would like to discuss about the stack data structure. &lt;/p&gt;

&lt;h2&gt;
  
  
  1. What is Stack?
&lt;/h2&gt;

&lt;p&gt;Stack is a linear data structure which works on a principle of &lt;strong&gt;Last in First Out&lt;/strong&gt; (popularly known as LIFO). &lt;/p&gt;

&lt;p&gt;If you know about the recursion where program has to go deep (in downwards) and build the solution upward, stack is the obvious choice for it. &lt;/p&gt;

&lt;p&gt;Other problems where Stack suited the most -&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Checking if parenthesis or balanced or not&lt;/li&gt;
&lt;li&gt;Reversing array using stack&lt;/li&gt;
&lt;li&gt;expression computation&lt;/li&gt;
&lt;/ul&gt;




&lt;h2&gt;
  
  
  2. How to create Stack in Javascript?
&lt;/h2&gt;

&lt;p&gt;Stack have following primitive operation -&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;push(val)&lt;/li&gt;
&lt;li&gt;pop()&lt;/li&gt;
&lt;li&gt;peek()&lt;/li&gt;
&lt;li&gt;is_empty()&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Lets define the object prototype of Stack -&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;function Stack() {
  this.arr = [];
  this.top = 0;
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;arr -  an array which holds the stack item&lt;br&gt;
top - a pointer which points to the top of stack&lt;/p&gt;


&lt;h3&gt;
  
  
  push(val)
&lt;/h3&gt;

&lt;p&gt;push function take val and insert it to the top of stack&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Stack.prototype.push = function (val) {
  this.arr[this.top] = val;
  this.top = this.top + 1;
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;






&lt;h3&gt;
  
  
  pop()
&lt;/h3&gt;

&lt;p&gt;pop remove the top element of the stack, also returned it&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Stack.prototype.pop = function () {
  if (this.is_empty()) {
    throw new Error("Underflow, stack is empty");
  }

  var topEl = this.arr[this.top - 1];

  this.top = this.top - 1;
  this.arr.pop();

  return topEl;
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;






&lt;h3&gt;
  
  
  peek()
&lt;/h3&gt;

&lt;p&gt;peek function doesn't delete the data from the stack, instead it just return the top of the stack&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Stack.prototype.peek = function () {
  if (this.is_empty()) {
    throw new Error("Underflow, stack is empty");
  }

  return this.arr[this.top - 1]; 

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

&lt;/div&gt;






&lt;h3&gt;
  
  
  is_empty()
&lt;/h3&gt;

&lt;p&gt;is_empty function returns true if the stack is empty else false&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Stack.prototype.is_empty = function () {
  return this.top === 0;
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;






&lt;p&gt;Lets put all the code together -&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;function Stack() {
  this.arr = [];
  this.top = 0;
}

Stack.prototype.push = function (val) {
  this.arr[this.top] = val;
  this.top = this.top + 1;
}

Stack.prototype.pop = function () {
  if (this.is_empty()) {
    throw new Error("Underflow, stack is empty");
  }

  var topEl = this.arr[this.top - 1];

  this.top = this.top - 1;
  this.arr.pop();

  return topEl;
}

Stack.prototype.is_empty = function () {
  return this.top === 0;
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;






&lt;h2&gt;
  
  
  3. How to reverse stack?
&lt;/h2&gt;

&lt;h3&gt;
  
  
  Approach 1 - Modify original Stack
&lt;/h3&gt;

&lt;p&gt;Pop element from stack one by one and store in new string, this new string will be the reverse of original string.&lt;/p&gt;

&lt;p&gt;Let's create a reverse function which reverse the stack and return the reverse string.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Stack.prototype.reverse = function () {
  if (this.is_empty()) {
    throw new Error("Underflow, stack is empty");
  }

  var revStr = '';

  while(!this.is_empty()) {
    revStr += this.pop();
  }

  return revStr;
}


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

&lt;/div&gt;






&lt;h3&gt;
  
  
  Approach 2 - Keep original Stack as it is
&lt;/h3&gt;

&lt;p&gt;Since, with the above implementation, we have the reference of the stack &lt;code&gt;arr&lt;/code&gt; which have the stack data. Now with &lt;code&gt;top&lt;/code&gt; pointer we can loop over &lt;code&gt;arr&lt;/code&gt; and process the stack and store the reverse string and return.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Stack.prototype.reverseAlternate = function () {
  if (this.is_empty()) {
    throw new Error("Underflow, stack is empty");
  }

  var revStr = '';

  for (var i = this.top - 1; i &amp;gt;= 0; i--) {
    revStr += this.arr[i];
  }

  return revStr;
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;






&lt;p&gt;Combining all code together with example -&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;function Stack() {
  this.arr = [];
  this.top = 0;
}

Stack.prototype.push = function (val) {
  this.arr[this.top] = val;
  this.top = this.top + 1;
}

Stack.prototype.pop = function () {
  if (this.is_empty()) {
    throw new Error("Underflow, stack is empty");
  }

  var topEl = this.arr[this.top - 1];

  this.top = this.top - 1;
  this.arr.pop();

  return topEl;
}

Stack.prototype.is_empty = function () {
  return this.top === 0;
}

Stack.prototype.reverse = function () {
  if (this.is_empty()) {
    throw new Error("Underflow, stack is empty");
  }

  var revStr = '';

  for (var i = this.top - 1; i &amp;gt;= 0; i--) {
    revStr += this.arr[i];
  }

  return revStr;
}

Stack.prototype.reverseV1 = function () {
  if (this.is_empty()) {
    throw new Error("Underflow, stack is empty");
  }

  var revStr = '';

  while(!this.is_empty()) {
    revStr += this.pop();
  }

  return revStr;
}

var stack = new Stack();

stack.push('a');
stack.push('b');
stack.push('c');

console.log(stack.reverse()); // cba
console.log(stack.reverseV1()); // cba
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;TC - O(n) to process stack&lt;br&gt;
SC - O(n) for storing the reverse string&lt;/p&gt;

&lt;p&gt;&lt;a href="https://github.com/ajayv1/dsa/blob/main/stack.js"&gt;Github Link&lt;/a&gt;&lt;/p&gt;

</description>
      <category>javascript</category>
      <category>datastructure</category>
      <category>programming</category>
      <category>algorithms</category>
    </item>
  </channel>
</rss>
