<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Ajay Verma on Medium]]></title>
        <description><![CDATA[Stories by Ajay Verma on Medium]]></description>
        <link>https://medium.com/@ajayverma_5579?source=rss-bb3e50e8fa01------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*nI0HIsAQFKf5DF9PAR6XaQ.jpeg</url>
            <title>Stories by Ajay Verma on Medium</title>
            <link>https://medium.com/@ajayverma_5579?source=rss-bb3e50e8fa01------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 21 Nov 2026 14:53:17 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@ajayverma_5579/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[AbortController — How to cancel ongoing API requests?]]></title>
            <link>https://medium.com/@ajayverma_5579/abortcontroller-how-to-cancel-ongoing-api-requests-b1df3251eec7?source=rss-bb3e50e8fa01------2</link>
            <guid isPermaLink="false">https://medium.com/p/b1df3251eec7</guid>
            <category><![CDATA[frontend]]></category>
            <category><![CDATA[rest-api]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[abortcontroller]]></category>
            <category><![CDATA[web-development]]></category>
            <dc:creator><![CDATA[Ajay Verma]]></dc:creator>
            <pubDate>Sat, 02 Nov 2024 15:13:19 GMT</pubDate>
            <atom:updated>2024-11-02T15:13:19.137Z</atom:updated>
            <content:encoded><![CDATA[<h3>AbortController — How to cancel ongoing API requests?</h3><p>A must-know topic for every frontend developers</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BwtkN10jkRljfy9vqc4-nQ.png" /><figcaption>AbortController — <a href="https://weekendtutorial.com/">https://weekendtutorial.com/</a></figcaption></figure><p>Sometimes need arises to cancel the request if it is taking too long to finish. If a request takes too long to respond then the main thread will be busy — leading to increased CPU usage, degraded performance, and a poor user experience, particularly for users with slower internet connections..</p><h4>What is AbortController?</h4><p><em>AbortController</em> is an interface provided by Javascript Web API. Its purpose is to allow developers to have more control over asynchronous tasks.</p><blockquote>The AbortController interface provides a way to create and control an AbortSignal, which can then be passed to APIs that support it (like fetch). When the abort() method of the AbortController instance is called, the associated AbortSignal notifies any listeners (like a fetch request) to terminate the operation.</blockquote><h4>Implementation in Javascript</h4><pre>// Create controller<br>const abortController = new AbortController();<br><br>// Fetch method<br>fetch(&#39;https://api.api-ninjas.com/v1/randomuser&#39;, { signal: controller.signal })<br>  .then(response =&gt; response.json())<br>  .then(data =&gt; console.log(data))<br>  .catch(error =&gt; {<br>    if (error.name === &#39;AbortError&#39;) {<br>      console.log(&#39;Fetch request was aborted&#39;);<br>    } else {<br>      console.error(&#39;Fetch error:&#39;, error);<br>    }<br>  });<br><br>// abort after 5 seconds<br>setTimeout(() =&gt; controller.abort(), 5000); </pre><h4>Implementing a utility function</h4><pre>function fetchWithAbort (url, delay) {<br>  return new Promise((resolve, reject) =&gt; {<br>    const abortController = new AbortController();<br>    const timerId = null;<br>      <br>    fetch(url, { signal: abortController.signal })<br>      .then(response =&gt; response.json())<br>      .then((data) =&gt; {<br>        clearTimeout(timerId);<br>        console.log(data);<br>        resolve(data);<br>      })<br>      .catch(error =&gt; {<br>        if (error.name === &#39;AbortError&#39;) {<br>          console.log(&#39;Fetch request was aborted&#39;);<br>          reject(new Error(&#39;Fetch aborted due to timeout&#39;));<br>        } else {<br>          console.error(&#39;Fetch error:&#39;, error);<br>          reject(error);<br>        }<br>     });<br><br>     timerId = setTimeout(() =&gt; {<br>       // times up! abort the request<br>       abortController.abort();<br>     }, delay);<br>    <br>  });<br>}</pre><h4>Usage Example</h4><pre>fetchWithAbort(&#39;https://api.api-ninjas.com/v1/randomuser&#39;, 1000)<br>  .then(data =&gt; console.log(data))<br>  .catch(error =&gt; console.error(error.message));</pre><p>This will fetch the data from the specified URL and will abort the request if it takes longer than the specified delay (in milliseconds).</p><p>AbortController is supported in all major modern browsers, including Chrome, Firefox, Safari, Edge, and others. However, older browsers like Internet Explorer do not support it, so a polyfill would be needed for compatibility with these older browsers.</p><p>Please read other articles on my blog <a href="https://weekendtutorial.com/">https://weekendtutorial.com/</a></p><p>Thank you for reading the article!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b1df3251eec7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[React-select — How to use it?]]></title>
            <link>https://medium.com/@ajayverma_5579/react-select-how-to-use-it-6d3f6c98bcae?source=rss-bb3e50e8fa01------2</link>
            <guid isPermaLink="false">https://medium.com/p/6d3f6c98bcae</guid>
            <category><![CDATA[react]]></category>
            <category><![CDATA[front-end-development]]></category>
            <dc:creator><![CDATA[Ajay Verma]]></dc:creator>
            <pubDate>Sat, 02 Dec 2023 07:36:20 GMT</pubDate>
            <atom:updated>2023-12-02T07:36:20.371Z</atom:updated>
            <content:encoded><![CDATA[<h3>React-select — How to use it?</h3><p>React-select is one of the popular plugin for showing the select menu i.e dropdown list.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*iYywpiNL1974Lq05" /><figcaption>react-select from weekendtutorial.com</figcaption></figure><p>If you’re not aware about the &lt;select&gt; element in the html, please visit <a href="https://developer.mozilla.org/en-US/docs/Web/HTML/Element/select">Select element MDN</a> to refresh the memory.</p><p>I was developing one react application where i needed to show a dropdown list which should have the following features –</p><ol><li>searchable dropdown list</li><li>selected item can be cleared and it should be configurable</li><li>if the dropdown is open, clicking anywhere outside should close the dropdown</li><li>select dropdown should be allowed to styled separately</li></ol><p>Implementing this feature along with unit-testing would have taken lots of time, luckily we have react-select which offers the same set of functionality and even more.</p><p>While using it, I have seen one problem, there is no single reference on internet which shows how to use it in minimal code. Official documentation also contains lots of example but they offer usage which looks complex.</p><p>In this post, we are going to create a simple select menu which shows a list of fruits using react-select.</p><h3>React application with react-select</h3><p>let me show you the final result of what we are building –</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/768/0*OhK2JyYQYes9q2r0" /><figcaption>select menu</figcaption></figure><p>To build it you can create the react app locally by using the following commands in terminal –</p><p>1. npx create-react-app react-select-menu (<em>Note: </em>react-select-menu is the project name, you can take any name here.)</p><p>2. install react-select npm packages, npm i react-select</p><p>Now, lets create the data.js file inside the src/ folder. This file will contains the dropdown list data which react-select accepts.</p><pre>// data.js<br><br>const data = [<br>    {label: &#39;Mango&#39;, value: &#39;mango&#39;},<br>    {label: &#39;Apple&#39;, value: &#39;apple&#39;},<br>    {label: &#39;Banana&#39;, value: &#39;banana&#39;},<br>    {label: &#39;Grape&#39;, value: &#39;grape&#39;},<br>    {label: &#39;Orange&#39;, value: &#39;orange&#39;}<br>];<br><br>export default data;</pre><p>Please note that, Select component from react-select accepts the dropdown list that should be an array of objects. If you just have the array of strings, it won’t work.</p><p>That is why the fruit array is an array of objects. Now, lets see the App.js file.</p><pre><br>// App.js<br><br>import { useState } from &quot;react&quot;;<br>import Select from &quot;react-select&quot;;<br>import data from &#39;./data&#39;;<br>const App = () =&gt; {<br> const [favFruit, setFavFruit] = useState(&#39;&#39;);<br>const handleChange = (e) =&gt; {<br> console.log(e);<br> setFavFruit(() =&gt; e?.value || &#39;&#39;);<br> };<br>return (<br> &lt;&gt;<br> &lt;h1&gt;Searchable Select menu&lt;/h1&gt;<br> &lt;Select<br> placeholder=&quot;Select your fav fruit&quot;<br> options={data}<br> isSearchable<br> isClearable<br> name=&quot;fruit&quot;<br> onChange={handleChange}<br> /&gt;<br>{favFruit &amp;&amp; &lt;p&gt;My favourite fruit is {favFruit} &lt;/p&gt;}<br> &lt;/&gt;<br> );<br>};<br>export default App;</pre><p>In App.js, we have taken one state variable which is used to store the currently selected option.</p><p>In Select component, we are passing the following props –</p><ol><li>placeholder — shown when no option is selected</li><li>options — dropdown list from data,</li><li>isSearchable — enable search options</li><li>isClearable — clear the selected options</li><li>onChange — event handler callback</li><li>name — name of the select element</li></ol><p>Thats it, you can see the result after running the command — npm start</p><p>I hope you have understood how can we use the react-select to create the beautiful select dropdown list without much effort.</p><p>You can see the complete code here <a href="https://codesandbox.io/p/sandbox/crimson-bush-lswkyt">https://codesandbox.io/p/sandbox/crimson-bush-lswkyt</a></p><p>To learn more in react, you can check the react tutorials –</p><p><a href="https://weekendtutorial.com/category/frontend/react-js/">https://weekendtutorial.com/category/frontend/react-js/</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6d3f6c98bcae" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Implement Linked List in JavaScript]]></title>
            <link>https://javascript.plainenglish.io/how-to-implement-linkedlist-in-js-64bdc855215c?source=rss-bb3e50e8fa01------2</link>
            <guid isPermaLink="false">https://medium.com/p/64bdc855215c</guid>
            <category><![CDATA[data-structure-algorithm]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[interview-coding-question]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[singly-linked-list]]></category>
            <dc:creator><![CDATA[Ajay Verma]]></dc:creator>
            <pubDate>Wed, 09 Nov 2022 12:58:38 GMT</pubDate>
            <atom:updated>2022-11-14T05:23:05.300Z</atom:updated>
            <content:encoded><![CDATA[<h4>A practical guide on JavaScript linked lists</h4><p>In this article, we will be seeing how to implement linked lists in javascript and various operations of it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zPYXZlPrC7BzDtCgw3h4Fg.png" /></figure><p><em>Note:</em> I have chosen Javascript language (my favorite) to implement it, language is just a medium here, we can implement it in any programming language. The key Idea is the underlying algorithm will always remain the same.</p><p>Before we dive into the coding part, let’s start with the definition of the Linked List.</p><h3>What is Linked List?</h3><p>Def 1 —</p><p>A linked list is a linear data structure where elements are considered as a node that stores data and a pointer to the next node i.e element.</p><p>Def 2 —</p><p>A linked list is a linear data structure where elements are not stored at a contiguous memory location.</p><p>Contiguous memory allocation provides random access i.e direct access. Since array elements are stored in this fashion so accessing any element takes constant time i.e O(1) whereas for the linked list to access any element we have to follow the pointer so it is a sequential access and takes O(n) time.</p><h4>Array vs Linked List</h4><ol><li>Accessing ith element → Array O(1) | LinkedList O(n)</li><li>Insertion &amp; deletion → Array O(n) | Linked List O(1) — for doubly linked list</li><li>Size → Array — fixed | LinkedList — dynamic</li></ol><h3>Linked list Operation</h3><ol><li>Traversal</li><li>Size of the linked list</li><li>Insertion</li><li>Deletion</li><li>Searching</li></ol><h3>Implement Linked List in Javascript</h3><p>Let&#39;s define the constructor function for the Node i.e element of the linked list —</p><pre>function Node(data) {<br>    this.data = data;<br>    this.next = null;<br>}</pre><p>Now, we can define the LinkedList constructor —</p><pre>function LinkedList() {}</pre><p>Let&#39;s add a <strong>create </strong>function in the prototype of the linked list which will take an array of elements and create the linked list.</p><pre>LinkedList.prototype.create = function (arr) {<br>    let head = new Node(arr[0]);<br>    let temp = head;</pre><pre>    for (let i = 1; i &lt; arr.length; i++) {<br>        temp.next = new Node(arr[i]);<br>        temp = temp.next;<br>    }</pre><pre>    // returning head of the linked list<br>    return head;<br>}</pre><p>That&#39;s it, LinkedList is created 😊</p><p>Let&#39;s implement each of the primitive operations.</p><h4>Traverse the linked list</h4><p>Start from the head node and traverse till the end of the list.</p><pre>LinkedList.prototype.traverse = function (head) {<br>    let temp = head;</pre><pre>    while (temp != null) {<br>        console.log(temp.data);<br>        temp = temp.next;<br>    }<br>}</pre><p>TC: O(n)</p><h4>Size of the linked list</h4><p>Returns the count of all elements in the linked list.</p><pre>LinkedList.prototype.size = function (head) {<br>    let temp = head;<br>    let count = 0;</pre><pre>    while (temp != null) {<br>        count++;<br>        temp = temp.next;<br>    }<br>    <br>    return count;<br>}</pre><p>TC: O(n)</p><h4>Insertion in the linked list</h4><p>Insert the element in the linked list at the kth index and returns the updated head</p><pre>LinkedList.prototype.insert = function (head, k, elem) {<br>    <br>    let size = this.size(head);    <br>   <br>    // case 1. if index k is not valid<br>    if (k &lt; 0 || k &gt; size) {<br>        return head;<br>    }</pre><pre>    let newNode = new Node(elem);</pre><pre>    // case 2. insert at beginning<br>    if (k === 0) {<br>        newNode.next = head;<br>        return newNode;<br>    }</pre><pre>    // case 3. insert at kth node<br>    let temp = head;<br>  <br>    for (let i = 0; i &lt; k; i++) {<br>        temp = temp.next;<br>    }<br>  <br>    newNode.next = temp.next;<br>    temp.next = newNode;<br>  <br>    return head;<br>}</pre><p>TC: O(n)</p><h4>Deletion in the linked list</h4><p>Delete the kth index element from the linked list and returns the updated head</p><pre>LinkedList.prototype.delete = function (head, k) {<br>    <br>    let size = this.size(head);    <br>   <br>    // case 1. if index k is not valid<br>    if (k &lt; 0 || k &gt; size) {<br>        return head;<br>    }</pre><pre>    // case 2. deletion at the beginning<br>    let temp = head;</pre><pre>    if (k === 0) {<br>        temp = head.next;<br>        head.next = null;</pre><pre>        return temp;<br>    }</pre><pre>    // case 3. delete kth node<br>    temp = head;<br>  <br>    for (let i = 0; i &lt; k; i++) {<br>        temp = temp.next;<br>    }</pre><pre>    let cur = temp.next; // this element would be deleted<br>    temp.next = temp.next.next; // or cur.next (both are fine)<br>    cur.next = null;<br>  <br>    return head;<br>}</pre><p>TC: O(n)</p><h4>Searching in the linked list</h4><p>Given the head of the linked list and an element, search for the element in the list.</p><pre>LinkedList.prototype.search = function (head, elem) {<br>    let temp = head;<br>    let isFound = false;</pre><pre>    while (temp != null) {<br>        <br>        if (temp.data === elem) {<br>            isFound = true;<br>            break;<br>        }<br>        <br>        temp = temp.next;<br>    }<br>    <br>    return isFound;<br>}</pre><p>TC: O(n)</p><h3>Conclusion</h3><p>Now, you should try to create the LinkedList on your own and implement each of the operations.</p><p>After that, please try the following problems -</p><ol><li>reverse the linked list</li><li>find the middle of the linked list</li><li>find if the cycle is present in the linked list</li></ol><p>I hope you like the article, please share it with your friends. And visit weekendtutorial.com for more such articles.</p><p><em>More content at </em><a href="https://plainenglish.io/"><strong><em>PlainEnglish.io</em></strong></a><em>. Sign up for our </em><a href="http://newsletter.plainenglish.io/"><strong><em>free weekly newsletter</em></strong></a><em>. Follow us on </em><a href="https://twitter.com/inPlainEngHQ"><strong><em>Twitter</em></strong></a>, <a href="https://www.linkedin.com/company/inplainenglish/"><strong><em>LinkedIn</em></strong></a><em>, </em><a href="https://www.youtube.com/channel/UCtipWUghju290NWcn8jhyAw"><strong><em>YouTube</em></strong></a><em>, and </em><a href="https://discord.gg/GtDtUAvyhW"><strong><em>Discord</em></strong></a><em>. Interested in Growth Hacking? Check out </em><a href="https://circuit.ooo/"><strong><em>Circuit</em></strong></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=64bdc855215c" width="1" height="1" alt=""><hr><p><a href="https://javascript.plainenglish.io/how-to-implement-linkedlist-in-js-64bdc855215c">How to Implement Linked List in JavaScript</a> was originally published in <a href="https://javascript.plainenglish.io/">JavaScript in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Generate All Subarrays in JavaScript (2022)]]></title>
            <link>https://javascript.plainenglish.io/how-to-generate-all-subarrays-in-javascript-in-2022-ef830d7ad885?source=rss-bb3e50e8fa01------2</link>
            <guid isPermaLink="false">https://medium.com/p/ef830d7ad885</guid>
            <category><![CDATA[data-structure-algorithm]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[arrays]]></category>
            <dc:creator><![CDATA[Ajay Verma]]></dc:creator>
            <pubDate>Wed, 12 Oct 2022 18:34:18 GMT</pubDate>
            <atom:updated>2022-11-02T02:02:35.704Z</atom:updated>
            <content:encoded><![CDATA[<h4>Learning about subarrays in DSA</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eCE9cyDEEy_66hnh0kZAsA.png" /><figcaption>Subarrays Generation</figcaption></figure><p>Hello Readers,</p><p>Interviewers like to ask questions about the subarrays as it gives a clear indication of the logical thinking and aptitude of a candidate.</p><p>Considering the above, we are going to start a new tag MCAIQ (most commonly asked interview questions) on <a href="https://weekendtutorial.com/">weekendtutorial.com</a> that will contain the most frequently asked questions in the interview. This will be your single stop for all such questions and interview preparations.</p><p>we will see how to generate all the subarrays of an array in javascript using iterative and recursive ways both.</p><h3>Generate all subarrays using iteration</h3><h4>Problem Statement</h4><p>Given an array, generate all the possible subarrays of the given array using an iterative way.</p><pre>Input : [1, 2, 3]<br><br>Output: [1], [1, 2], [1, 2, 3], [2], [2, 3], [3]<br><br>Input: [1, 2]<br><br>Output: [1], [1, 2], [2]</pre><h4>Implementation</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e6002293513b1cd95030d3cd2073e86a/href">https://medium.com/media/e6002293513b1cd95030d3cd2073e86a/href</a></iframe><h3>Generate all subarrays using recursion</h3><h4>Implementation</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/56c3d91ddbf22bb8e1589af7e516e29c/href">https://medium.com/media/56c3d91ddbf22bb8e1589af7e516e29c/href</a></iframe><p>I hope you have learned something if you like the article please share it with friends and help <strong><em>weekendtutorial</em></strong> to grow. This site is run by ads and it is required for it to be alive and grow.</p><p>Read the following articles –</p><ol><li><a href="https://weekendtutorial.com/nginx-tutorial/">Learn Nginx in-depth</a></li><li><a href="https://weekendtutorial.com/binary-tree-and-its-traversal-in-javascript/">Implement binary tree using javascript</a></li></ol><p>This is all for today. Please visit our other articles, and keep learning.</p><p><em>More content at </em><a href="https://plainenglish.io/"><strong><em>PlainEnglish.io</em></strong></a><em>. Sign up for our </em><a href="http://newsletter.plainenglish.io/"><strong><em>free weekly newsletter</em></strong></a><em>. Follow us on </em><a href="https://twitter.com/inPlainEngHQ"><strong><em>Twitter</em></strong></a>, <a href="https://www.linkedin.com/company/inplainenglish/"><strong><em>LinkedIn</em></strong></a><em>, </em><a href="https://www.youtube.com/channel/UCtipWUghju290NWcn8jhyAw"><strong><em>YouTube</em></strong></a><em>, and </em><a href="https://discord.gg/GtDtUAvyhW"><strong><em>Discord</em></strong></a><em>. Interested in Growth Hacking? Check out </em><a href="https://circuit.ooo/"><strong><em>Circuit</em></strong></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ef830d7ad885" width="1" height="1" alt=""><hr><p><a href="https://javascript.plainenglish.io/how-to-generate-all-subarrays-in-javascript-in-2022-ef830d7ad885">How to Generate All Subarrays in JavaScript (2022)</a> was originally published in <a href="https://javascript.plainenglish.io/">JavaScript in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Debounce and Throttle — unboxing js perf]]></title>
            <link>https://javascript.plainenglish.io/debounce-and-throttle-unboxing-js-perf-495fb7c7c214?source=rss-bb3e50e8fa01------2</link>
            <guid isPermaLink="false">https://medium.com/p/495fb7c7c214</guid>
            <category><![CDATA[front-end-development]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[debounce]]></category>
            <category><![CDATA[throttle]]></category>
            <category><![CDATA[javascript-performance]]></category>
            <dc:creator><![CDATA[Ajay Verma]]></dc:creator>
            <pubDate>Sun, 18 Sep 2022 12:09:59 GMT</pubDate>
            <atom:updated>2022-09-27T15:29:32.541Z</atom:updated>
            <content:encoded><![CDATA[<h3>Debounce and Throttle — Unboxing JavaScript Performance</h3><h4>Explaining debouncing and throttling in JavaScript.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8J5H-G0sc7Yu9CNViqlteg.png" /><figcaption>debouncing and throttling — weekendtutorial.com</figcaption></figure><p>If you’re a frontend developer you must have handled the various events like button clicking, form submit, and window scroll events, etc through event handlers.</p><p>Some events are lightweight and don’t interfere with the UX behavior but some are just the opposite of it, for instance, <em>it is strongly advised to not attach any event handler on the window scroll event or resize event.</em></p><p>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 <em>scroll callbacks</em> into the callback queue and call stack. Thus, the page becomes unresponsive and not scrollable.</p><p>The two widely known techniques that solve the above problem are —</p><ol><li>Debouncing</li><li>Throttling</li></ol><h4>Debounce —</h4><p>Debounce technique can be understood by a timer. When the button is pressed the timer starts. 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 once per debounce period.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kGA4cm03j8Ae1MO2huvO3Q.png" /><figcaption>debounce</figcaption></figure><p>Let me take another example, <strong><em>the elevator</em></strong></p><p>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 “group” multiple sequential calls into a single one.</p><p>Other use cases —</p><ol><li>SearchBar — Don’t want to search every time user presses the key? Want to search when the user stopped typing for 1 sec. Use debounce 1 sec on key press.</li><li>Autocomplete feature</li><li>Auto-saving user input</li><li>Clicking of button that makes API calls</li></ol><p>You can check out the code:</p><p>Create the index.html file -</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/abc9968e77edc2aaf46d7c2eee9b6e51/href">https://medium.com/media/abc9968e77edc2aaf46d7c2eee9b6e51/href</a></iframe><p>and debounce.js —</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e6433d5ba8d8099b947c08eeea8795d9/href">https://medium.com/media/e6433d5ba8d8099b947c08eeea8795d9/href</a></iframe><p>If you check the console, you will find that the no. of time the event handler called is way less than the actual input size. And that&#39;s the big performance boost!</p><h4>Throttling —</h4><p>Throttling technique can be understood by a counter. 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.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YmLmoHZbQBe0lLCGhWZPFg.png" /><figcaption>Throttle</figcaption></figure><p>Other use cases —</p><ol><li>Shooting game — Pistol takes 1 sec time between each shot but the user clicks the mouse multiple times. Use throttle on mouse click.</li><li>Infinite scrolling</li></ol><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ddc5b879e08f97c969de67d47ae2a6ab/href">https://medium.com/media/ddc5b879e08f97c969de67d47ae2a6ab/href</a></iframe><p>Similarly here too, the button handler will be called at each 500ms and all the button click within this window is ignored.</p><p>As we have seen the performance benefits of using the debounce and throttle, based on your use case, you can use it in your code base.</p><p><strong><em>Note:</em></strong></p><p><strong>Underscore</strong> and <strong>Lodash.js</strong> libraries also have the debounce and throttle method, you can check that as well.</p><p>Please read other articles on my blog <a href="https://weekendtutorial.com/">https://weekendtutorial.com/</a></p><p><em>More content at </em><a href="https://plainenglish.io/"><strong><em>PlainEnglish.io</em></strong></a><em>. Sign up for our </em><a href="http://newsletter.plainenglish.io/"><strong><em>free weekly newsletter</em></strong></a><em>. Follow us on </em><a href="https://twitter.com/inPlainEngHQ"><strong><em>Twitter</em></strong></a>, <a href="https://www.linkedin.com/company/inplainenglish/"><strong><em>LinkedIn</em></strong></a><em>, </em><a href="https://www.youtube.com/channel/UCtipWUghju290NWcn8jhyAw"><strong><em>YouTube</em></strong></a><em>, and </em><a href="https://discord.gg/GtDtUAvyhW"><strong><em>Discord</em></strong></a><em>. Interested in Growth Hacking? Check out </em><a href="https://circuit.ooo/"><strong><em>Circuit</em></strong></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=495fb7c7c214" width="1" height="1" alt=""><hr><p><a href="https://javascript.plainenglish.io/debounce-and-throttle-unboxing-js-perf-495fb7c7c214">Debounce and Throttle — unboxing js perf</a> was originally published in <a href="https://javascript.plainenglish.io/">JavaScript in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Implement Binary Heap in JavaScript in 2022?]]></title>
            <link>https://javascript.plainenglish.io/how-to-implement-binary-heap-in-javascript-in-2022-6069402351d1?source=rss-bb3e50e8fa01------2</link>
            <guid isPermaLink="false">https://medium.com/p/6069402351d1</guid>
            <category><![CDATA[algorithms]]></category>
            <category><![CDATA[binary-heap]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[coding]]></category>
            <dc:creator><![CDATA[Ajay Verma]]></dc:creator>
            <pubDate>Thu, 28 Apr 2022 06:30:55 GMT</pubDate>
            <atom:updated>2022-05-06T02:03:39.952Z</atom:updated>
            <content:encoded><![CDATA[<h4>A complete guide on binary heap data structure</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DyrEJ_iUYrwCA3UHY7u4Bg.png" /><figcaption>image by weekendtutorial.com</figcaption></figure><h4>Binary Heap</h4><p>A binary heap is a tree data structure that has 2 properties —</p><ol><li>It should be a <em>perfect binary tree </em><strong><em>(a.k.a structure-property)</em></strong></li><li>Each node of the tree should be either ≥ or ≤ than both of its children. In other words, It should be <strong>either Min heap or Max heap.</strong> (<strong><em>a.k.a heap property</em></strong>)</li></ol><h4>Perfect binary tree</h4><p>A binary tree that is almost complete, the last level of the tree filled from left to right.</p><p>e.g tree given in max heap and min heap is an example of a perfect binary tree.</p><p><strong><em>Note: if you have not read the binary tree before, please checkout</em></strong></p><ol><li><a href="https://weekendtutorial.com/binary-tree-and-its-traversal-in-javascript/">How to implement binary tree in JavaScript?</a></li><li><a href="https://weekendtutorial.com/binary-tree-the-best-5-coding-questions-you-must-solve/">Top 5 Basic Must problems in the binary tree</a></li></ol><h4>Types of Binary Heap</h4><p>A binary heap is of 2 types —</p><ol><li>Max Heap</li><li>Min Heap</li></ol><h4>Max Heap</h4><p>A binary heap where each node of the tree is ≥ than both of its children. Thus the root of the tree would be maximum among all of the nodes.</p><p>e.g below tree is an example of a Max heap:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/351/1*RvItG3S67zOm-dIfIOGB9A.png" /><figcaption>Binary Max Heap</figcaption></figure><h4>Min Heap</h4><p>A binary heap where each node of the tree is ≤ than both of its children. Thus the root of the tree would be minimum among all of the nodes.</p><p>e.g below tree is an example of a Min heap:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/351/1*dTuVseEh_SwYzImQDHBgXw.png" /><figcaption>Binary Min Heap</figcaption></figure><h4>Representation of Binary Heap</h4><p>A binary heap can be represented by the list of tree nodes as well as by an Array. In this article, we will only focus on the Array representation of binary heap.</p><p>Key points to note here are —</p><ol><li>the root of the tree is Arr[0]</li><li>for any index i,</li></ol><pre>Parent index = (i-1)/2</pre><pre>Left child index = 2 * i + 1</pre><pre>Right Child index = 2 * i + 2</pre><h4>Application of Binary Heap</h4><ol><li>Heap Sort</li><li>Priority Queue</li><li>Graph Algorithms (Dijkstra— Shortest Path algorithm, Prims — MST)</li><li>Problems where you need to keep finding min after every iteration e.g</li></ol><p>a) <a href="https://leetcode.com/problems/kth-largest-element-in-an-array">Kth Largest element in the array</a></p><p>b)<a href="https://leetcode.com/problems/task-scheduler"> Task Scheduler</a></p><p>c) <a href="https://leetcode.com/problems/maximum-product-of-two-elements-in-an-array">Maximum Product of 2 elements in an array</a></p><p>This is the complete list — <a href="https://leetcode.com/tag/heap-priority-queue/">Heap Problems</a></p><h4>Binary Min Heap Implementation in JavaScript</h4><p>&lt;script src=”<a href="https://gist.github.com/ajayv1/82bea3c569b80fc4c8cbb82b65505d7a.js">https://gist.github.com/ajayv1/82bea3c569b80fc4c8cbb82b65505d7a.js</a>&quot;&gt;&lt;/script&gt;</p><p><strong>Usage (</strong>both approaches result in valid binary min heap<strong>)</strong></p><p><strong>Approach 1:</strong> Insert the array elements one by one in the heap. Heap <strong>insert</strong> function calls function <strong>heapifyUp</strong> internally.</p><pre>let pq = new PriorityQueue();</pre><pre>let arr = [80,70,40,20,10,60,50,30];</pre><pre>for (let i = 0; i &lt; arr.length; i++) {<br>    pq.insert(arr[i]);<br>}</pre><pre>console.log(&#39;Heap using approach 1&#39;, pq);</pre><p><strong>Approach 2: </strong>Insert complete array elements in the heap (by calling the <strong>build_heap</strong> function). Heap function <strong>Build_heap</strong> calls function <strong>heapify</strong> which will heapify the whole heap.</p><pre>let pr = new PriorityQueue();</pre><pre>pr.build_heap(arr);</pre><pre>console.log(&#39;Heap using approach 2&#39;, pr);</pre><p><strong>Result</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nMwie7X3oKVamayepdz3MQ.png" /><figcaption>Binary Min Heap</figcaption></figure><h4>Binary Max Heap Implementation in JavaScript</h4><p>&lt;script src=”<a href="https://gist.github.com/ajayv1/11fb38ca7c53e0979fcbcf14501684dc.js">https://gist.github.com/ajayv1/11fb38ca7c53e0979fcbcf14501684dc.js</a>&quot;&gt;&lt;/script&gt;</p><p><strong>Usage (</strong>both approaches result in valid binary max heap<strong>)</strong></p><p><strong>Approach 1:</strong> Insert the array elements one by one in the heap. Heap <strong>insert</strong> function calls function <strong>heapifyUp</strong> internally.</p><pre>let pq = new BinaryMaxHeap();</pre><pre>let arr = [80,70,40,20,10,60,50,30];</pre><pre>for (let i = 0; i &lt; arr.length; i++) {<br>    pq.insert(arr[i]);<br>}</pre><pre>console.log(&#39;Heap using approach 1&#39;, pq);</pre><p><strong>Approach 2: </strong>Insert complete array elements in the heap (by calling the <strong>build_heap</strong> function). Heap function <strong>Build_heap</strong> calls function <strong>heapify</strong> which will heapify the whole heap.</p><pre>let pr = new BinaryMaxHeap();</pre><pre>pr.build_heap(arr);</pre><pre>console.log(&#39;Heap using approach 2&#39;, pr);</pre><p><strong>Result</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9Q6Ib09KbZdqnMNny2kiuQ.png" /><figcaption>Using Binary Max Heap</figcaption></figure><h4>Summary</h4><p>There are plenty of practical problems that will be solved easily by the binary heap data structure. It is a must one for all computer science grads.</p><p>In many programming languages, the binary heap is provided natively but knowing the core implementation and building a custom one is real learning.</p><p>The code in this article (which is written in JavaScript) can be imported to other programming languages of your choice.</p><p>Try to build it in the programming language you preferred.</p><p>For all the latest posts and articles, please visit the website <a href="https://weekendtutorial.com/">https://weekendtutorial.com/</a></p><p>Keep learning, and stay safe.</p><p><em>More content at</em><strong><em> </em></strong><a href="https://plainenglish.io/"><strong><em>PlainEnglish.io</em></strong></a><em>. Sign up for our </em><a href="http://newsletter.plainenglish.io/"><strong><em>free weekly newsletter</em></strong></a><em>. Follow us on </em><a href="https://twitter.com/inPlainEngHQ"><strong><em>Twitter</em></strong></a><em> and </em><a href="https://www.linkedin.com/company/inplainenglish/"><strong><em>LinkedIn</em></strong></a><em>. Join our </em><a href="https://discord.gg/GtDtUAvyhW"><strong><em>community Discord</em></strong></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6069402351d1" width="1" height="1" alt=""><hr><p><a href="https://javascript.plainenglish.io/how-to-implement-binary-heap-in-javascript-in-2022-6069402351d1">How to Implement Binary Heap in JavaScript in 2022?</a> was originally published in <a href="https://javascript.plainenglish.io/">JavaScript in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Integrate Google ReCaptcha v3 Correctly in 2022?]]></title>
            <link>https://javascript.plainenglish.io/hahow-to-integrate-google-recaptcha-v3-correctly-in-2022-15a4fd186d7?source=rss-bb3e50e8fa01------2</link>
            <guid isPermaLink="false">https://medium.com/p/15a4fd186d7</guid>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[google]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Ajay Verma]]></dc:creator>
            <pubDate>Wed, 06 Apr 2022 09:07:41 GMT</pubDate>
            <atom:updated>2022-04-08T11:08:51.600Z</atom:updated>
            <content:encoded><![CDATA[<h4>A solution to prevent email spamming.</h4><p>Google Recaptcha is one of the industry-standard methods that solve the email spamming problem.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*zlbymJaj6yKLnUhT" /><figcaption>Google Recaptcha</figcaption></figure><h4>What is Email Spamming?</h4><p>Email spam a.k.a `junk emails` 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.</p><p>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.</p><p><strong>E.g.</strong> the places which is the source of the email spam –</p><ol><li>Login, signup and reset password forms on the site</li><li>the comment and contact us section in a blog</li></ol><p>There are <strong>4 types of Google ReCaptcha</strong> –</p><figure><img alt="Types of Google ReCaptcha" src="https://cdn-images-1.medium.com/max/1023/0*qNIjUOqlnHTeSnx5" /></figure><p>In this article, we are going to integrate the google ReCaptcha v3 which is the latest.</p><p>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.</p><h3>Steps to Integrate Google Recaptcha V3</h3><h4>Step 1. Register your website on the ReCaptcha admin</h4><p>First of all, we need to register the website on the <a href="https://www.google.com/recaptcha/admin/site/">ReCaptcha admin console</a>.</p><p>It looks like this –</p><figure><img alt="ReCaptcha Admin Console" src="https://cdn-images-1.medium.com/max/1024/0*ipzAMnRMLLB3cjnf" /></figure><h3>Step 2. Client-Side Integration</h3><p>After registering the website on the admin console, note down the reCAPTCHA keys.</p><p>e.g.<br>In the above image, you must be seeing the reCaptcha Keys.</p><p><strong>ReCaptcha gives 2 keys –</strong></p><p><strong>1. Site Key —</strong> this is the public key and is used in client-side integration.<br><strong>2. Secret Key —</strong> this is the private key and can’t be exposed to anyone. This should be safely stored in your backend server.</p><p>Let’s start with the client-side integration –</p><h4>1. Load the JavaScript API with your site key</h4><pre>&lt;script src=&quot;https://www.google.com/recaptcha/api.js?render=&lt;site_key&gt;&quot;&gt;&lt;/script&gt;</pre><p>in the above, you will pass the actual Recaptcha Site Key in the place of &lt;site_key&gt;</p><p>e.g if the Recaptcha Site Key is <strong>sdfjhjk124jkhk</strong></p><p>you will pass it as <strong>?render=sdfjhjk124jkhk</strong></p><h4>2. Call `grecaptcha.execute` on each action you wish to protect</h4><pre>&lt;script&gt;<br>    function onClick(e) {<br>        e.preventDefault();<br>        grecaptcha.ready(function() {<br>            grecaptcha.execute(&#39;reCAPTCHA_site_key&#39;, {action: &#39;submit&#39;}).then(function(token) {<br>                // Add your logic to submit to your backend server here.<br>            });<br>        });<br>    }<br>&lt;/script&gt;</pre><p>Whichever input box you wish to protect, it could be your signup, login, or some other field, you need to update the click handler for that, similar to above.</p><p>You can see the above code, we pass the actual Recaptcha site key and one callback function to the grecaptcha.execute function.</p><p>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.</p><h4>3. Send the token immediately to your backend with the request to verify</h4><p>This will trigger the server-side flow.</p><h3>Step 2. Server-Side Integration</h3><p>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 google site-verify api.</p><p>The google site-verify API returns a score that is between 0.0 to 1.0. We also set one threshold score default of 0.5 up to which score we will allow users to make requests.</p><p>If the score is less than the threshold score we can say that the user is not human and it’s a bot. If the score is &gt;threshold score then the user is human and the actual functionality of click is allowed.</p><h4>Request endpoint</h4><figure><img alt="Recaptcha Request endpoint" src="https://cdn-images-1.medium.com/max/1024/0*gQVqZTzBsgerxqd4" /></figure><h4>Site Verify Response</h4><p>The response is a JSON object.</p><figure><img alt="site response" src="https://cdn-images-1.medium.com/max/1024/0*MOSv-On5sDeosWF2" /></figure><h3>Challenge</h3><p>On StackOverflow, I was searching for something regarding ReCaptcha and found out most of the people are implementing it incorrectly.</p><p>They are getting the score from the server-side and comparing the score and threshold on the client-side which is completely wrong.</p><p><strong>e.g. Below implementation is wrong</strong></p><pre>&lt;script&gt;<br>    function onClick(e) {<br>        e.preventDefault();<br>        grecaptcha.ready(function() {<br>            grecaptcha.execute(&#39;reCAPTCHA_site_key&#39;, {action: &#39;submit&#39;}).then(function(token) {<br>                var score = fetchScoreFromAPI(token);<br>                if (score &gt; THRESHOLD_SCORE) {<br>                    callCommentApi();<br>                }<br>            });<br>        });<br>    }<br>&lt;/script&gt;</pre><p>The above is incorrect due to –</p><ol><li>the client never does the validation</li><li>Attackers can easily manipulate the score and see the comment API endpoint and flood it with unsolicited emails.</li></ol><p><strong>Here is the correct implementation –</strong></p><pre>&lt;script&gt;<br>    function onClick(e) {<br>        e.preventDefault();<br>        grecaptcha.ready(function() {<br>            grecaptcha.execute(&#39;reCAPTCHA_site_key&#39;, {action: &#39;submit&#39;}).then(function(token) {<br>                callCommentAPI(token);<br>            });<br>        });<br>    }<br>&lt;/script&gt;<br><br>// At server side<br>function callCommentAPI(token){<br>    var score = fetchScoreFromAPI(token);<br>    if (score &gt; THRESHOLD_SCORE) {<br>        // execute logic for comment API<br>    }<br>}</pre><p>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.</p><p>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.</p><h3>Summary</h3><p>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.</p><p>If you like the article, please share this and <strong>follow me</strong>.</p><p>Please read my other popular articles –</p><ol><li><a href="https://weekendtutorial.com/nginx-tutorial/">Nginx Tutorial</a></li><li><a href="https://weekendtutorial.com/browser-storage-in-detail-part-1/">Browser Storage</a></li></ol><p>That’s all for now, let’s meet next time soon.</p><p><em>More content at </em><a href="https://plainenglish.io/"><strong><em>PlainEnglish.io</em></strong></a><em>. Sign up for our </em><a href="http://newsletter.plainenglish.io/"><strong><em>free weekly newsletter</em></strong></a><em>. Follow us on </em><a href="https://twitter.com/inPlainEngHQ"><strong><em>Twitter</em></strong></a><em> and </em><a href="https://www.linkedin.com/company/inplainenglish/"><strong><em>LinkedIn</em></strong></a><em>. Join our </em><a href="https://discord.gg/GtDtUAvyhW"><strong><em>community Discord</em></strong></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=15a4fd186d7" width="1" height="1" alt=""><hr><p><a href="https://javascript.plainenglish.io/hahow-to-integrate-google-recaptcha-v3-correctly-in-2022-15a4fd186d7">How to Integrate Google ReCaptcha v3 Correctly in 2022?</a> was originally published in <a href="https://javascript.plainenglish.io/">JavaScript in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Refactor the Global Variables in JavaScript?]]></title>
            <link>https://javascript.plainenglish.io/how-to-refactor-the-global-variables-in-javascript-9dc2d3fa7e6c?source=rss-bb3e50e8fa01------2</link>
            <guid isPermaLink="false">https://medium.com/p/9dc2d3fa7e6c</guid>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[refactor]]></category>
            <category><![CDATA[design-patterns]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Ajay Verma]]></dc:creator>
            <pubDate>Mon, 21 Mar 2022 18:49:54 GMT</pubDate>
            <atom:updated>2022-03-23T04:39:00.519Z</atom:updated>
            <content:encoded><![CDATA[<h4>A deeper dive into the namespace pattern to refactor the global variables.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mLoTD0jouaTknya3h8Sq9g.jpeg" /><figcaption>Javascript by Unsplash</figcaption></figure><p>We all have heard or read that globals are bad practices. Polluting the code space with multiple globals leads to unmanageable and unpredictable code.</p><p>It is always advisable to keep the globals in check and have it as minimum as possible.</p><p>In this part, we will be discussing one approach that will reduce the global variables with much ease.</p><p>Suppose in your codebase the following globals are present:</p><pre>// Constructors<br>function X() {}<br>function Y() {}</pre><pre>// global vars<br>var res = 1;</pre><pre>// global objects<br>var module1 = {<br>   a: 1,<br>   b: 2<br>};</pre><pre>var module2 = {};<br>module2.a = 10;<br>module2.b = 20;</pre><pre>var module3 = {};</pre><p>In the above block, we have<strong><em> 6 global variables</em></strong>. Now, we can refactor this code to have only one global object, and all the constructors, variables, and objects will be part of it.</p><p>Ideally, all codebases should thrive to have a single global variable. Having multiple globals are bad because of many reasons — e.g</p><ol><li>they could be modified accidentally and are error-prone.</li><li>Also, it may cause name collision with your code or 3rd party library</li></ol><h3>Solution</h3><p>Refactored code:</p><pre>// Global object<br>var APP = APP || {};</pre><pre>// Constructors<br>APP.X = function () {};<br>APP.Y = function () {};</pre><pre>// variables<br>APP.res = 1;</pre><pre>// objects<br>APP.modules.module1 = {a: 1, b: 2};</pre><pre>APP.modules.module2 = {};<br>APP.modules.module2.a = 10;<br>APP.modules.module2.b = 20;</pre><pre>APP.modules.module3 = {};</pre><p>There is a problem with the code e.g if you want to use the below:</p><pre>var module1 = APP.modules.module1;</pre><p>You have to make 3 checks like below:</p><pre>var module1 = APP &amp;&amp; APP.modules &amp;&amp; APP.modules.module1;</pre><p>And this is kind of irritating.</p><p>To solve this we need to have a handy function that deals with the namespacing part. Let&#39;s call this function ‘namespace()’ and use it like this:</p><pre>APP.namespace(‘APP.modules.module1’) </pre><p>Which is equivalent to:</p><pre>var APP = {<br>   modules: {<br>      module1: {<br>      }<br>   }<br>};</pre><h3>Implementation of namespace() function</h3><pre>var APP = APP || {};</pre><pre>APP.namespace = function (str) {<br>  var parts = str.split(&#39;.&#39;),<br>      parent = APP;</pre><pre>  // remove the redundant global<br>  if (parts[0] === &#39;APP&#39;) {<br>      parts = parts.slice(1);<br>  }</pre><pre>  for (var i = 0; i &lt; parts.length; i++) {<br>      if (typeof parent[parts[i]] === &#39;undefined&#39;) {<br>          parent[parts[i]] = {};<br>      }<br>      parent = parent[parts[i]]; <br>  }</pre><pre>  return parent;<br>}</pre><p>Let&#39;s test the above:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*a41KfRgIk3SIz98Ua26n0A.png" /><figcaption>creating nested objects with namespace pattern</figcaption></figure><p>We can see that:</p><pre>APP.namespace(‘APP.modules.module1’)</pre><p>The above code gives the desired result and also passing the APP (the top global object in the namespace) is redundant. We can achieve the same by passing just modules.module1</p><pre>APP.namespace(‘modules.module1’)</pre><p>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!</p><p><em>More content at</em><strong><em> </em></strong><a href="https://plainenglish.io/"><strong><em>PlainEnglish.io</em></strong></a><em>. Sign up for our </em><a href="http://newsletter.plainenglish.io/"><strong><em>free weekly newsletter</em></strong></a><em>. Follow us on </em><a href="https://twitter.com/inPlainEngHQ"><strong><em>Twitter</em></strong></a><em> and </em><a href="https://www.linkedin.com/company/inplainenglish/"><strong><em>LinkedIn</em></strong></a><em>. Join our </em><a href="https://discord.gg/GtDtUAvyhW"><strong><em>community Discord</em></strong></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9dc2d3fa7e6c" width="1" height="1" alt=""><hr><p><a href="https://javascript.plainenglish.io/how-to-refactor-the-global-variables-in-javascript-9dc2d3fa7e6c">How to Refactor the Global Variables in JavaScript?</a> was originally published in <a href="https://javascript.plainenglish.io/">JavaScript in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[5 Coding Problems on Binary Tree that You Need to Solve]]></title>
            <link>https://javascript.plainenglish.io/the-best-5-coding-questions-you-must-solve-in-binary-tree-1f760c9f70a9?source=rss-bb3e50e8fa01------2</link>
            <guid isPermaLink="false">https://medium.com/p/1f760c9f70a9</guid>
            <category><![CDATA[data-structures]]></category>
            <category><![CDATA[algorithms]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[coding]]></category>
            <dc:creator><![CDATA[Ajay Verma]]></dc:creator>
            <pubDate>Sun, 13 Mar 2022 15:19:13 GMT</pubDate>
            <atom:updated>2022-03-23T05:13:54.045Z</atom:updated>
            <content:encoded><![CDATA[<h4>A series on data structure coding problems — The most commonly asked interview problems on binary tree.</h4><p>In this article, we will see the top 5 most commonly asked interview problems on the binary tree.</p><p>If you’re preparing for the job interviews for the position of software engineer/software developer or any role related to programming, you have to have a strong grasp of the data structures.</p><p><strong>Non-linear</strong> data structures like Trees, Graphs are favorite topics from the interviewer’s point of view. This blog is about the binary tree data structure.</p><p>We have just started the <em>interview problem series</em> where we will see the top interview question that is asked in almost every interview. Along with the problems, we will also provide <em>the solution in detail</em> so that it can be clearer to you.</p><p><em>Note: If you have not read this, please do it first </em><a href="https://weekendtutorial.com/binary-tree-and-its-traversal-in-javascript/">Binary Tree — How to implement using Javascript in 2022?</a></p><p>One strong suggestion though — <strong><em>Try the problems by yourself first.</em></strong> Once you’ve exhausted all the options and nothing working out only then check the solution. Believe me, practicing this will boost your confidence.</p><p>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.</p><h3>List of problems</h3><ol><li>Size of the binary tree (i.e count of all nodes)</li><li>Height of the binary tree</li><li>The maximum node in the binary tree</li><li>The minimum node in the binary tree</li><li>Sum of all nodes in the binary tree</li></ol><h3>Problem 1. Size of the binary tree</h3><p>The size of the binary tree is the total number of nodes present in the tree.</p><p>for example, the size of the below tree is 8</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/451/0*ZhnD5cjdyo18T9nQ" /></figure><p><strong>Size of tree = size of left subtree + size of right subtree + 1</strong></p><pre>function size(root) {<br>   if (root === null) return 0;<br><br>   return size(root.left) + size(root.right) + 1;<br>}</pre><p>TC: O(N) ~ have to visit each node of the tree at most once<br>SC: O(N) ~ in case of skewed tree</p><h2>2. Height of the binary tree</h2><p>The height of the tree is the distance of the farthest leaf node from the root node of the tree.</p><p>for example, the height of the below tree is 4</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/451/0*NvUE0ZZQsMkMelgb" /></figure><p><strong>Height of tree = Max(Height of left subtree, Height of right subtree) + 1</strong></p><pre>function height(root) {<br>   if (root === null) return 0;</pre><pre>   return Math.max(height(root.left), height(root.right)) + 1;<br>}</pre><p>TC: O(N) ~ have to visit each node of the tree at most once<br>SC: O(N) ~ in case of skewed tree</p><h2>3. The maximum node in the binary tree</h2><p>The maximum node can be either root node or will be from the left or right subtree.</p><p>If we take the maximum of the above 3, the result will be the maximum node in the tree.</p><p>for example, the maximum of the below tree is 80</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/451/0*jqg7SrFTvd57ypV7" /></figure><p><strong>Largest node of tree = <br>Max(Largest in left subtree, Largest in right subtree, root.data)</strong></p><pre>function largest(root) {<br>   if (root === null) return 0;</pre><pre>   return Math.max(<br>        largest(root.left),<br>        largest(root.right),<br>        root.data<br>    );<br>}</pre><p>TC: O(N) ~ have to visit each node of the tree at most once<br>SC: O(N) ~ in case of skewed tree</p><h2>4. The minimum node in the binary tree</h2><p>The minimum node can be either root node or will be from the left or right subtree.</p><p>If we take the minimum of the above 3, the result will be the minimum node in the tree.</p><p>for example, the minimum of the below tree is 10</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/451/0*idIebxR7mISXrhd_" /></figure><p><strong>Smallest node of tree = <br>Min(Smallest in left subtree, Smallest in right subtree, root.data)</strong></p><pre>function smallest(root) {<br>   if (root === null) return 0;</pre><pre>   return Math.min(<br>        smallest(root.left),<br>        smallest(root.right),<br>        root.data<br>    );<br>}</pre><p>TC: O(N) ~ have to visit each node of the tree at most once<br>SC: O(N) ~ in case of skewed tree</p><h2>5. Sum of all nodes in the binary tree</h2><p>To find the sum of all the nodes of the tree we need to visit each node using any tree traversal method. In this, I’m using postorder traversal.</p><p>For example, the maximum of the below tree is 360.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/451/0*kD0IuBXgKIgThAnM" /></figure><p><strong>sumTree = sumTree(left subtree) + sumTree(right subtree) + root.data</strong></p><pre>function sumTree(root) {<br>   if (root === null) return 0;</pre><pre>   return sumTree(root.left) + sumTree(root.right) + root.data;<br>}</pre><p>TC: O(N) ~ have to visit each node of the tree at most once<br>SC: O(N) ~ in case of skewed tree</p><h2>Summary</h2><p>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.</p><p>Please stay along with the <a href="https://weekendtutorial.com/"><strong>weekendTutorial</strong></a> and medium for the latest articles.</p><p><strong><em>It would encourage me to write more if you follow me here, I would really appreciate it.</em></strong></p><p>Thank you for reading this. Let’s meet next time.</p><p><em>More content at</em><strong><em> </em></strong><a href="https://plainenglish.io/"><strong><em>PlainEnglish.io</em></strong></a><em>. Sign up for our </em><a href="http://newsletter.plainenglish.io/"><strong><em>free weekly newsletter</em></strong></a><em>. Follow us on </em><a href="https://twitter.com/inPlainEngHQ"><strong><em>Twitter</em></strong></a><em> and </em><a href="https://www.linkedin.com/company/inplainenglish/"><strong><em>LinkedIn</em></strong></a><em>. Join our </em><a href="https://discord.gg/GtDtUAvyhW"><strong><em>community Discord</em></strong></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1f760c9f70a9" width="1" height="1" alt=""><hr><p><a href="https://javascript.plainenglish.io/the-best-5-coding-questions-you-must-solve-in-binary-tree-1f760c9f70a9">5 Coding Problems on Binary Tree that You Need to Solve</a> was originally published in <a href="https://javascript.plainenglish.io/">JavaScript in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[JavaScript Objects in Depth: A Comprehensive Guide for Beginners]]></title>
            <link>https://javascript.plainenglish.io/objects-in-javascript-344af1e5a081?source=rss-bb3e50e8fa01------2</link>
            <guid isPermaLink="false">https://medium.com/p/344af1e5a081</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[objects-in-javascript]]></category>
            <category><![CDATA[frontend-developer]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[web-development]]></category>
            <dc:creator><![CDATA[Ajay Verma]]></dc:creator>
            <pubDate>Wed, 02 Mar 2022 05:07:24 GMT</pubDate>
            <atom:updated>2022-03-04T04:03:00.093Z</atom:updated>
            <content:encoded><![CDATA[<h4>A deep dive into the JavaScript core.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*B7Ky05wDai-DtLkEmyG_XQ.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@afgprogrammer?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Mohammad Rahmani</a> on unsplash</figcaption></figure><p>This is one of the core concepts in JavaScript that needs to be mastered.</p><h3>What is Object in JavaScript?</h3><p>An object in JavaScript is simply a map containing the key-value pairs. It is pretty much similar to:</p><ol><li>struct in C</li><li>HashMap in java</li><li>unordered_map in c++</li><li>dictionary in python</li></ol><p>So, if you’re coming from the above programming language, understanding JavaScript objects and constructors will be a piece of cake for you.</p><p><strong><em>Note:-</em></strong> Sometimes Object is also referred to as <strong><em>“associative arrays”</em></strong> in other programming languages.</p><p>The value of a key can be a function, array, object, or any other primitive. If the value of a key is a primitive or any other object (PS: an array is also an object in JavaScript) then it&#39;s called <strong><em>properties</em></strong><em> </em>but if it&#39;s a function then it&#39;s called <strong><em>method</em></strong>.</p><p>For example,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*p5EMD9atWbopmy1MQXHpCw.png" /><figcaption>Person Object</figcaption></figure><p>In the above code, a person is an object which has keys <strong><em>sayHello</em></strong> and <strong><em>friends</em></strong> with value as function and arrays respectively.</p><p>You probably have heard that —</p><p>Almost everything is an object in JavaScript. So the question now arising is — what are the remaining ones that aren’t an object? <strong>Ans</strong> — Primitives</p><h3>Primitive</h3><p>A primitive (primitive value, primitive data type) is data that is not an object and doesn’t have any methods. There are 7 primitive data types — string, number, big int, boolean, undefined, symbol, and null.</p><p>All primitives are immutable i.e they can be replaced but can’t be altered. Let&#39;s understand this with an example:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iCqDZMRI-BfU3Ty-8uCGoQ.png" /><figcaption>Primitive — immutability example</figcaption></figure><h3>How to Create an Object in JavaScript?</h3><p>Creating an object at the beginning may seem odd but once you are used to it, you will love it.</p><p>The object syntax is wrapped by curly braces. And the key-value pair separated by a colon with a trailing comma is added inside the object.</p><pre>var obj = { <br> name: ‘xyz’, <br> age: 26<br>}</pre><p>we can also create an empty object and add properties as we go.</p><pre>var obj = {}; // empty or blank object<br>obj.name = ‘xyz’;<br>obj.age = 26;</pre><p>Both object declarations are the same.</p><p>In the next part, we will see the other ways to create an object in detail.</p><p>If you like my article, please follow me on Medium.</p><p><em>More content at </em><a href="https://plainenglish.io/"><strong><em>PlainEnglish.io</em></strong></a><em>. Sign up for our </em><a href="http://newsletter.plainenglish.io/"><strong><em>free weekly newsletter</em></strong></a><em>. Follow us on </em><a href="https://twitter.com/inPlainEngHQ"><strong><em>Twitter</em></strong></a><em> and </em><a href="https://www.linkedin.com/company/inplainenglish/"><strong><em>LinkedIn</em></strong></a><em>. Join our </em><a href="https://discord.gg/GtDtUAvyhW"><strong><em>community Discord</em></strong></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=344af1e5a081" width="1" height="1" alt=""><hr><p><a href="https://javascript.plainenglish.io/objects-in-javascript-344af1e5a081">JavaScript Objects in Depth: A Comprehensive Guide for Beginners</a> was originally published in <a href="https://javascript.plainenglish.io/">JavaScript in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>