<?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 Aditya Gannavarapu on Medium]]></title>
        <description><![CDATA[Stories by Aditya Gannavarapu on Medium]]></description>
        <link>https://medium.com/@adityakashyap_36551?source=rss-fd80535c97b9------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*MdLhY0aXHSKGPCfX</url>
            <title>Stories by Aditya Gannavarapu on Medium</title>
            <link>https://medium.com/@adityakashyap_36551?source=rss-fd80535c97b9------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 21 Nov 2026 20:55:30 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@adityakashyap_36551/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[Autocomplete: Optimisation using Trie Structures]]></title>
            <link>https://medium.com/@adityakashyap_36551/autocomplete-optimisation-using-trie-structures-528cf85ef6f5?source=rss-fd80535c97b9------2</link>
            <guid isPermaLink="false">https://medium.com/p/528cf85ef6f5</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[es6]]></category>
            <category><![CDATA[ui]]></category>
            <category><![CDATA[trie]]></category>
            <category><![CDATA[data-structures]]></category>
            <dc:creator><![CDATA[Aditya Gannavarapu]]></dc:creator>
            <pubDate>Sat, 26 Oct 2024 04:04:42 GMT</pubDate>
            <atom:updated>2024-10-26T04:06:55.980Z</atom:updated>
            <content:encoded><![CDATA[<p>While developers often rely on linear search to implement autocomplete functionality, to truly level up, every JavaScript developer should be familiar with the Trie data structure. Tries are specifically optimised for prefix-based searches, making them ideal for autocomplete tasks by significantly reducing search time and enhancing performance. Although understanding Tries can sometimes be a bit challenging, I’ll break down the concepts as simply as possible in this article.</p><p><strong>What will we cover in this article:</strong></p><ul><li>Trie data structure.</li><li>Insert</li><li>Search</li><li>Find by prefix(recursion)</li><li>Time and space complexity and edge over liner search.</li></ul><h3><strong>Trie data structure</strong></h3><p>The Trie data structure is composed of two key elements:</p><ol><li><strong>TrieNode</strong>: Each node is an object that maps to different keys.</li></ol><ul><li><strong>Children</strong>: TrieNode has a children object where we map each unique key(each character of a word). for example “BOB”</li><li><strong>EndofWord</strong>: endOfWord is a flag which notifies the end of a word.</li></ul><p><strong>2. Trie</strong>: This is the primary structure that contains the root node, serving as the starting point for the data organisation.</p><ul><li><strong>Root</strong> : root is the first instance of TrieNode which gets the data structure flowing. We keep on following the chain of children. and try to add a TrieNode for each subsequnt character forming a parent child relationship.()</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-hzc_xktMTffGBkaxq21qw.png" /><figcaption>Trie data structures children parent relationship.</figcaption></figure><pre><br>class TrieNode{<br>    constructor(){<br>        // each node will have a map of each character<br>        this.children = {};<br>        // this fkag indicates the end of the word<br>        this.endOfWord = false;<br>    }<br>}</pre><pre>class Trie{<br>    constructor(){<br>        this.root = new TrieNode()<br>    }<br>   /// functionalities to follow<br>}</pre><h3>Insert</h3><ul><li>Insert functionality oinserts the word in the trie data structure.</li><li>It iterates over each character of the word and create a network of children where each child point to another TrieNode.</li><li>once the entire iteration is complete we mark endOfWord as an indication that at this state a word exists.</li><li>this flag will be crucial in word extraction.</li></ul><pre>insert(word){<br>        let node = this.root;<br>        for(let i of word){<br>            if(!node.children[i]){<br>                node.children[i] = new TrieNode()<br>            }<br>            node = node.children[i]<br>        }<br>        node.endOfWord = true;<br>    }</pre><h3><strong>Search</strong></h3><ul><li>Search functionality search’s the word in the trie data structure.</li><li>It iterates over each character and create a network of children where each child point to another TrieNode.</li><li>Once the entire iteration is complete check if endOfWord is true.</li><li>If endOfWord is true we return true.</li><li>If we skip any character, straightaway return false.</li></ul><pre>search(word){<br>        let node = this.root;<br>// iterate each character of the word<br>        for(let i of word){<br>            if(!node.children[i]){<br>//if not found return false<br>                return false<br>            }<br>            node = node.children[i]<br>        }<br>        return node.endOfWord;<br>    }</pre><h3>Find By Prefix</h3><ul><li>This is a recursive implementation of the above mentioned search function.</li><li>Once we search the prefix word, we gather all the children which have endOfWord as true. we do it using a helper function which is a recursive function.</li><li>On each recursion we check if we reached endofWord, if yes we push the word into a resultant array.</li><li>At the end we return the resultant array.</li></ul><pre>findAllWordsWithPrefix(word){<br>        let node = this.root, res = [];<br>        // iterate each character of the word<br>        for(let i of word){<br>            if(!node.children[i]){<br>                // return empty array if word not found<br>                return res;<br>            }<br>            node = node.children[i]<br>        }<br>        // if you find the prefix word call helper<br>        return this.collectionHelepr(node, word, res)<br>    } <br><br>collectionHelepr(node, word, res){<br>        // base condition <br>        // if reached the end push into the res[]<br>        if(node.endOfWord){<br>            res.push(word)<br>        }<br>        // iterate each key of the child of the prefix word.<br>        for(let i in node.children){<br>            //return recursive result<br>            return this.collectionHelepr(node.children[i], word+i, res)<br>        }<br>        // return resultant array<br>        return res;<br>   } </pre><h3>Putting it together</h3><pre>class TrieNode{<br>    constructor(){<br>        this.children = {};<br>        this.endOfWord = false;<br>    }<br>}<br><br>class Trie{<br>    constructor(){<br>        this.root = new TrieNode();<br>    }<br>    <br>    insert(word){<br>        let node = this.root;<br>        for(let i of word){<br>            if(!node.children[i]){<br>                node.children[i] = new TrieNode();<br>            }<br>            node = node.children[i];<br>        }<br>        node.endOfWord = true;<br>    }<br>    <br>    search(word){<br>        let node = this.root;<br>        for(let i of word){<br>            if(!node.children[i]){<br>                return false;<br>            }<br>            node = node.children[i];<br>        }<br>        return node.endOfWord;<br>    }<br>    <br>    findAllWordsWithPrefix(word){<br>        let node = this.root, res = [];<br>        for(let i of word){<br>            if(!node.children[i]){<br>                return res;<br>            }<br>            node = node.children[i];<br>        }<br>        return this.collectionHelepr(node,word, res);<br>    }<br>    <br>    <br>    collectionHelepr(node, word, res){<br>        if(node.endOfWord){<br>            res.push(word)<br>        }<br>        for(let i in node.children){<br>            return this.collectionHelepr(node.children[i], word+i, res)<br>        }<br>        return res;<br>    } <br>}<br><br>let s = new Trie()<br>s.insert(&quot;ad&quot;);<br>s.insert(&quot;adi&quot;);<br>s.insert(&quot;adit&quot;);<br>s.insert(&quot;adity&quot;);<br>s.insert(&quot;aditya&quot;);<br>console.log(s.search(&quot;joe&quot;)); // false<br>console.log(s.findAllWordsWithPrefix(&quot;root&quot;)) // [] <br>console.log(s.findAllWordsWithPrefix(&quot;ad&quot;)) // [ &#39;ad&#39;, &#39;adi&#39;, &#39;adit&#39;, &#39;adity&#39;, &#39;aditya&#39; ]<br></pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1012/1*_FabgA2iRrhSNhBvh2wSVg.png" /><figcaption>output for the above code</figcaption></figure><h3><strong>Time and space complexity and edge over linear search.</strong></h3><ul><li>The complexity of liner search would be O(m*n) where the m is the length of each word and n is the list of words.</li><li>However, the complexity significantly reduces to O(m) in case of a trie data structure as you traverse down the word following the next child element.</li></ul><h3>Summary</h3><p>In this Article, we learnt about one of the complex data structures Trie and how it could be leveraged to complete the auto search functionality. Because of the efficiency trie data structure is preferred over liner search for functionalities like autocomplete, sequence matching, data deduplication and even neural language processing.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=528cf85ef6f5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building Custom setTimeout and clearTimeout.]]></title>
            <link>https://medium.com/@adityakashyap_36551/building-custom-settimeout-and-cleartimeout-d8011fffc3bf?source=rss-fd80535c97b9------2</link>
            <guid isPermaLink="false">https://medium.com/p/d8011fffc3bf</guid>
            <category><![CDATA[functional-programming]]></category>
            <category><![CDATA[es6]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[data-structures]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Aditya Gannavarapu]]></dc:creator>
            <pubDate>Fri, 11 Oct 2024 23:33:00 GMT</pubDate>
            <atom:updated>2024-10-15T12:10:55.181Z</atom:updated>
            <content:encoded><![CDATA[<p>In JavaScript, we rely heavily on asynchronous programming since it is single-threaded. As developers, we frequently use functions like setTimeout and clearTimeout to handle delays and time-based actions without blocking the main thread. These functions allow JavaScript to maintain its non-blocking, asynchronous nature by scheduling tasks to be executed in the future while continuing with other operations.</p><p>In this article, we will explore how setTimeout achieves asynchronicity and also how to implement custom versions of setTimeout and clearTimeout.</p><p><strong>What will we cover in this article</strong>:</p><ul><li>requestAnimationFrame.</li><li>SetTimeout implementation.</li><li>clearTimeout implementation.</li></ul><h3><strong>RequestAnimationFrame:</strong></h3><p>requestAnimationFrame is a highly efficient JavaScript method that prompts the browser to run a callback before the next screen repaint. By syncing with the display&#39;s refresh rate (usually 60 FPS), it ensures smooth animations and is more effective for animations than setTimeout or setInterval.</p><p>Use cases:</p><ol><li>If you want to have fading effects like screen resize.</li><li>Have a smooth scrolls animations.</li><li>Some sort of custom throttle or debouce.</li></ol><p><strong><em>For our custom implementation of setTimeoutAnd clearTimeout we would use requestAnimationFrame in a recursive way.</em></strong></p><h3><strong>SetTimeout Custom implementation.</strong></h3><ul><li><strong>Functionality</strong>: setTimeout is a function that instructs the JavaScript engine to execute a callback function after a specified time interval.</li><li><strong>Parameters/ Arguments</strong>: the first is the callback function, and the second is the time interval (in milliseconds).</li><li><strong>Asynchronous behaviour</strong>: setTimeout is a browser-provided function that operates asynchronously. It sits in the task queue (I’ll cover the difference between micro and macro queues in a future article) and is executed after the specified interval has passed.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bkFKje9_fnhD4HFXIi3CXA.png" /><figcaption>Custom Implementation of setTimeout</figcaption></figure><pre>function customSetTimeout = (cb, interval) =&gt; {<br>    // counter to capture the time lapse <br>    let startTime = Date.now()<br>    let execute = (...args) =&gt; {<br>        //actual time when function execution starts.<br>        let currTime = Date.now()<br>        // if the difference between currentime and actual started time is greater than interval <br>        // execute the callback<br>        if(currTime-startTime&gt;=interval){<br>            //eecute call back with arguments.<br>            cb(...args)<br>        } else {<br>            //continue executing excute intile the time is met to trigger callback<br>            requestAnimationFrame(() =&gt; execute(...args))<br>        }<br>    }<br>    //ensures that the function starts checking the time only when the browser is ready to repaint<br>    requestAnimationFrame(execute);//Start the execution loop<br><br>}</pre><h3><strong>ClearTimeout Custom Implementation.</strong></h3><ul><li>We would try to refactor the above implementation of customSetTimeout to conver it to custom clearTimeout.</li><li>We would introduce a flag which, based on this false when set to true we no more execute the callback wiht arguments.</li><li>We would return set the flag to true immediately so that the cb never gets called.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ecLHfGCMqqdlcCskqTUaiw.png" /><figcaption>Custom Implementation of setTimeout</figcaption></figure><pre>function customCancelTimeout (cb, interval){<br>    // counter to capture the time lapse<br>    let cancelFlag = false;<br>    let startTime = Date.now()<br>    let execute = (...args) =&gt; {<br>        //actual time when function execution starts.<br>        let currTime = Date.now();<br>        // if the difference between currentime and actual started time is greater than interval <br>        // execute the callback<br>        if(!cancelFlag &amp;&amp; currTime-startTime&gt;=interval){<br>            //eecute call back with arguments.<br>            cb(...args)<br>        } else if (!isCancelled){<br>            //continue executing excute intile the time is met to trigger callback<br>            requestAnimationFrame(() =&gt; execute(...args))<br>        }<br>    }<br>    //ensures that the function starts checking the time only when the browser is ready to repaint<br>    requestAnimationFrame(execute);<br>    //immediately setthe cancel flag and return.<br>    return () =&gt; {<br>        cancelFlag = true;<br>    }<br>}<br><br>let test = customCancelTimeout(() =&gt; {console.log(&quot;custom timeout&quot;)}, 2000)<br>test();</pre><p><strong>Conclusion</strong></p><p>In this article, we looked at how to create custom versions of setTimeout and clearTimeout. We also talked about using requestAnimationFrame to make recursive calls for smoother animations.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d8011fffc3bf" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[N-Queens Solver: Recursive Backtracking Approach]]></title>
            <link>https://medium.com/@adityakashyap_36551/n-queens-solver-recursive-backtracking-approach-4ef317fc0482?source=rss-fd80535c97b9------2</link>
            <guid isPermaLink="false">https://medium.com/p/4ef317fc0482</guid>
            <category><![CDATA[react]]></category>
            <category><![CDATA[backtracking]]></category>
            <category><![CDATA[recursion]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Aditya Gannavarapu]]></dc:creator>
            <pubDate>Sat, 17 Aug 2024 04:54:50 GMT</pubDate>
            <atom:updated>2024-08-17T15:21:21.799Z</atom:updated>
            <content:encoded><![CDATA[<p>N-queen is a puzzle to place n-queens on a n x n chessboard board such that no queens can attack each other. <em>Let’s play chess programatically ofcourse in our favourite language Javascript.</em></p><h3>Content:</h3><ol><li>Rules of N-queen.</li><li>Recursion and backtracking.</li><li>Pseudo Code for N-Queen</li><li>Programming in JS</li><li>Conclusion.</li></ol><h3><strong>Rules of N-Queen:</strong></h3><p>Place the queens keeping following things in mind:</p><ol><li>NO two Queens should be in same row.</li><li>NO two Queens should be in same column.</li><li>NO two Queens should be in same diagonal(both upward diagonal/ downward diagonal).</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*47EPdG97mWyxbQdvX0eJAw.png" /><figcaption>Rules in a nutshell.</figcaption></figure><h3>Recursion and Backtracking the core of N-queen:</h3><ol><li>Since we plan to keep the queens on each row and column and check possible results. This process involves checking up multiple combinations of board with all(4) placed queens.</li><li>Whenever we have to test out multiple combinations the best bet is recursions.</li><li>Recursion stack naturally inherits backtracking, whenever recursion is finished the next step stack Data structure performs is a pop put in other words backtracking.</li><li>However, if during the recursion we find a particular solution is no feasible we back track and remove the placed value. Thus back tracking to the previous state.</li></ol><h3>Pseudo :</h3><ol><li>Since the input is just an integer N we need to place N queens on n*n chess board.</li><li>Create a n*n chess board which is a 2-D matrix.</li><li>Initialise the resultant array i.e res, this wil be our Data struture to store results.</li><li>Initialise the column to 0 as we start left to right. With this we just need to check the feasibility on left (for same row), diagonally left upwards , diagonally left downward.</li><li>We can skip diagonally upwards(right) and diagonally downwards(right) as we started from left to right and we know right values on board is always empty. We are only concerned with diagonally left upwards , diagonally left downward.</li><li>Write a helper function(recursive) which helps you recursively place the different values of “Q” on the board.</li><li>After each succesfull placement increment the col++ and call the next recursion with new column number(0 =&gt; n-1).</li><li>Continue until we reach column n( n === 4) and then terminate which is also the base condition for recursion.</li><li>Incase a value fails we use the backtracking and re-write the value as zeros state which is “.”.</li></ol><h3><strong>Javascript Program</strong></h3><pre>// n queen<br><br>let n = 4<br><br>function nQueen(n){<br>    //create an empty chess board of 4*4.<br>    let board = new Array(n).fill().map(() =&gt; new Array(n).fill(&quot;.&quot;));<br>    // this will the resultan array which stores the result.<br>    let res = []<br>    // recursively call the a helper util we get a resultant array<br>    return helper(board, n, res, 0);<br>}<br><br>function helper(board, n, res, col){<br>    //base termination condition when column === 4 <br>    if(col === n){<br>        //cloning a deep copy<br>        res.push(JSON.parse(JSON.stringify(board)))<br>        // return result;<br>        return res;<br>    }<br>    for(let row=0; row&lt;n; row++){<br>        // write a function which checks the feasibility<br>        if(isFeasible(row, col, board, n)){<br>            // try keeping a value &quot;Q&quot;<br>            board[row][col] = &quot;Q&quot;<br>            // try for the next column<br>            // continue this recursively until we hit the last column<br>            helper(board, n, res, col+1)<br>            // backtrack and replace the &quot;Q&quot; with &quot;.&quot;(zero state as this result is no longer valid)<br>            board[row][col] = &quot;.&quot;<br>        }<br>    }<br>    /// return result<br>    return res;<br>}<br><br>function isFeasible(row, col, board, n){<br>    let i = row, j = col;<br>    // traverse to the left of the board and check if we have any instance of &quot;Q&quot;<br>    while(j&gt;=0){<br>        if(board[i][j]!== &quot;Q&quot;){<br>            j--<br>        } else {<br>            // return false if we get any instance of Q<br>            return false<br>        }<br>    }<br>    <br>    //traverse diagonally left upwards and check if we have any instance of &quot;Q&quot;<br>     i = row, j = col;<br>     while(i&gt;=0 &amp;&amp; j&gt;=0){<br>        if(board[i][j]!== &quot;Q&quot;){<br>            i--;<br>            j--<br>        }else {<br>            // return false if we get any instance of Q<br>            return false<br>        }<br>    }<br>    // traverse diagonally left downwards and check if we have any instance of &quot;Q&quot;<br>     i = row, j = col;<br>     <br>      while(i&lt;n &amp;&amp; j&gt;=0){<br>        if(board[i][j]!== &quot;Q&quot;){<br>            i++;<br>            j--<br>        }else {<br>            // return false if we get any instance of Q<br>            return false<br>        }<br>    }<br>    return true;<br>}<br><br><br>console.log(nQueen(n))<br><br><br></pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Z2vWzzkVPHVnbNVhuJh7tA.png" /><figcaption>Output where no Queen can attack the other queen as per the rules.</figcaption></figure><h3><strong>Conclusion</strong>:</h3><p>N-queen is a puzzle which can we easily solved using recursion and back tracking. This not only helps you to under stand recursion and its benefits but also gives you an idea of the backtracking functionality which is comes out of box for the recursion stack.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4ef317fc0482" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Sudoku Solver : Recursion & Backtracking]]></title>
            <link>https://medium.com/@adityakashyap_36551/sudoku-solver-recursion-backtracking-698c8ef8f5a9?source=rss-fd80535c97b9------2</link>
            <guid isPermaLink="false">https://medium.com/p/698c8ef8f5a9</guid>
            <category><![CDATA[backtracking]]></category>
            <category><![CDATA[recursion]]></category>
            <category><![CDATA[data-structures]]></category>
            <category><![CDATA[leetcode]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Aditya Gannavarapu]]></dc:creator>
            <pubDate>Sat, 04 May 2024 22:24:38 GMT</pubDate>
            <atom:updated>2024-05-04T22:24:38.122Z</atom:updated>
            <content:encoded><![CDATA[<h3>Sudoku Solver : Recursion &amp; Backtracking</h3><p>Sudoku, Is a board game originally originated from Switzerland which later gained popularity in Japan. This game involves filling a 9x9 board with numbers from 1 to 9, refraining from any repetition along the rows, columns, or 3x3 sub grids. This article deep dives into programmatically solving Sudoku using recursion and backtracking, until finding the correct one. It’s a combination of algorithmic thinking, logic and strategy,.</p><p>What will we cover in this article:</p><ul><li>Rules of Sudoku</li><li>Recursion</li><li>Backtracking</li><li>Implementation</li></ul><h3><strong>Rules</strong></h3><ol><li>Each number should appear exactly once in each 3x3 sub grid.</li><li>Each number should appear exactly once in each row, from 1 to 9.</li><li>Each number should appear exactly once in each column, from 1 to 9.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*V9zn-_IFKTKoGRFD1oE6Jw.png" /></figure><h3>Recursion</h3><ul><li>We will attempt to fill the board with numbers from 1 to 9, For each empty cell in the Sudoku board.</li><li>This approach utilizes recursion, as we recursively explore possible values( 1 to 9). for each cell.</li><li>If a value is valid and leads to a successful solution, we continue recursively passing the updated board for further exploration.</li><li>We’ve developed a <strong>helper</strong> <strong>function</strong> that will be recursively invoked.</li></ul><h3>Backtracking</h3><ul><li>If the above rules are violated at any step during the recursive process, we’ll need to backtrack that step.</li><li>This involves removing the previously assigned value and trying an alternative value or leaving the cell blank.</li><li>If the <strong>isFeasible</strong> <strong>function</strong> returns false anywhere throughout the process we backtrack.</li><li>If the false condition is never met, we finally return true.</li></ul><h3>Implementation</h3><ol><li><strong>sudokuSolver function :</strong></li></ol><ul><li>Use a function called sudokuSolver to solve the Sudoku board.</li><li>It calls recursive function called <strong>helper</strong> to solve the puzzle.</li></ul><p><strong>2. Helper Function:</strong></p><ul><li>Helper function iterates over each empty cell in the Sudoku board.</li><li>For each empty cell, it tries numbers from 1 to 9.</li><li>If a number fits(is valid as per the rules), it places the number and continues solving the board recursively.</li><li>If we cannot find a solution, we need to backtracks and try a different number.</li></ul><p><strong>3. isFeasible Function</strong></p><ul><li>This helper function which ensures validity of a number.</li><li>If a number adheres the Sudoku rules it can be placed in the given position.</li><li>If the number is not present in the same row, column, or 3x3 grid it returns true, else returns false.</li></ul><p><strong><em>How to check in 3* 3 grid???</em></strong></p><ol><li><strong>Calculating row index(a)</strong></li></ol><ul><li>3 * Math.floor(row / 3): This expression effectively divides the Sudoku board into sections of 3 rows each and selects the section containing the current row.</li><li>Math.floor(i / 3): This part determines which row within the 3-row section the loop is currently iterating over.</li><li>Adding these two values together gives the row index (a) of the top-left cell of the 3x3 grid containing the current cell (row, col).</li></ul><p>2. <strong>Calculating the Column Index (</strong><strong>b)</strong></p><ul><li>3 * Math.floor(col / 3): This expression divides the Sudoku board into sections of 3 columns each and selects the section containing the current column.</li><li>i % 3: This part determines which column within the 3-column section the loop is currently iterating over.</li><li>Adding these two values together gives the column index (b) of the top-left cell of the 3x3 grid containing the current cell (row, col).</li></ul><p><strong><em>Complete Code</em></strong></p><pre>let board = [<br>    [&quot;5&quot;,&quot;3&quot;,&quot;.&quot;,&quot;.&quot;,&quot;7&quot;,&quot;.&quot;,&quot;.&quot;,&quot;.&quot;,&quot;.&quot;],<br>    [&quot;6&quot;,&quot;.&quot;,&quot;.&quot;,&quot;1&quot;,&quot;9&quot;,&quot;5&quot;,&quot;.&quot;,&quot;.&quot;,&quot;.&quot;],<br>    [&quot;.&quot;,&quot;9&quot;,&quot;8&quot;,&quot;.&quot;,&quot;.&quot;,&quot;.&quot;,&quot;.&quot;,&quot;6&quot;,&quot;.&quot;],<br>    [&quot;8&quot;,&quot;.&quot;,&quot;.&quot;,&quot;.&quot;,&quot;6&quot;,&quot;.&quot;,&quot;.&quot;,&quot;.&quot;,&quot;3&quot;],<br>    [&quot;4&quot;,&quot;.&quot;,&quot;.&quot;,&quot;8&quot;,&quot;.&quot;,&quot;3&quot;,&quot;.&quot;,&quot;.&quot;,&quot;1&quot;],<br>    [&quot;7&quot;,&quot;.&quot;,&quot;.&quot;,&quot;.&quot;,&quot;2&quot;,&quot;.&quot;,&quot;.&quot;,&quot;.&quot;,&quot;6&quot;],<br>    [&quot;.&quot;,&quot;6&quot;,&quot;.&quot;,&quot;.&quot;,&quot;.&quot;,&quot;.&quot;,&quot;2&quot;,&quot;8&quot;,&quot;.&quot;],<br>    [&quot;.&quot;,&quot;.&quot;,&quot;.&quot;,&quot;4&quot;,&quot;1&quot;,&quot;9&quot;,&quot;.&quot;,&quot;.&quot;,&quot;5&quot;],<br>    [&quot;.&quot;,&quot;.&quot;,&quot;.&quot;,&quot;.&quot;,&quot;8&quot;,&quot;.&quot;,&quot;.&quot;,&quot;7&quot;,&quot;9&quot;]<br>];<br><br>function sudokuSolver(board){<br>    // initialize a recursive function<br>    helper(board)<br>    // return the populated board <br>    return board;<br>}<br><br>function helper(board){<br>    // since the board is 9*9<br>    // iterate over the rows<br>    for(let row=0; row&lt;9; row++){<br>        // iterate over the columns<br>        for(let col=0; col&lt;9; col++){<br>            // find an empty space<br>            if(board[row][col] === &quot;.&quot;){<br>                // check for all permuatations from 1...9<br>                for(let k = 1; k&lt;=9; k++){<br>                    // if a particular value between 1...9 looks valid<br>                    if(isFeasible(board, row, col, k)){<br>                        // place the value k(1...9)<br>                        board[row][col] = k.toString();<br>                        // recursively call the helper method to fill the next balck value<br>                        if(helper(board)){<br>                            // if the last recursion returns true return true<br>                            return true<br>                        }else{<br>                            // if any value doesn&#39;t workout BACKTRACK<br>                            // undo the value.<br>                            board[row][col] = &quot;.&quot;<br>                        }<br>                    }<br>                }<br>                // out of 1...9 if any value doesn&#39;t satisfy return a false, as an indication to backtrack.<br>                return false;<br>            }<br>        }<br>    }<br>    // each recursion on success returns true<br>    return true<br>}<br><br>function isFeasible(board, row, col, k) {<br>    for(let i = 0; i&lt;8; i++){<br>        /* check the row <br>        throughout the row the value of k shouldn&#39;t be available. */<br>        if(board[row][i] === k.toString()){<br>            // if available return false<br>            return false<br>        }<br>        /* check the column <br>        throughout the column the value of k shouldn&#39;t be available. */<br>        if(board[i][col] === k.toString()){<br>            return false<br>        }<br>        /* check the 3*3 grid <br>        throughout the 3*3 grid the value of k shouldn&#39;t be available. */<br>        let a = 3* Math.floor(row/3)+ Math.floor(i/3) <br>        let b = 3* Math.floor(col/3) + i%3<br>        if(board[a][b] === k.toString()){<br>            return false<br>        }<br>    }<br>    return true<br>}<br><br><br>console.log(sudokuSolver(board))<br></pre><pre>Output:<br>[<br> [ &#39;5&#39;, &#39;3&#39;, &#39;4&#39;, &#39;6&#39;, &#39;7&#39;, &#39;8&#39;, &#39;9&#39;, &#39;1&#39;, &#39;2&#39;],<br> [ &#39;6&#39;, &#39;7&#39;, &#39;2&#39;, &#39;1&#39;, &#39;9&#39;, &#39;5&#39;, &#39;3&#39;, &#39;4&#39;, &#39;8&#39;],<br> [ &#39;1&#39;, &#39;9&#39;, &#39;8&#39;, &#39;3&#39;, &#39;4&#39;, &#39;2&#39;, &#39;5&#39;, &#39;6&#39;, &#39;7&#39;],<br> [ &#39;8&#39;, &#39;5&#39;, &#39;9&#39;, &#39;7&#39;, &#39;6&#39;, &#39;1&#39;, &#39;4&#39;, &#39;2&#39;, &#39;3&#39;],<br> [ &#39;4&#39;, &#39;2&#39;, &#39;6&#39;, &#39;8&#39;, &#39;5&#39;, &#39;3&#39;, &#39;7&#39;, &#39;9&#39;, &#39;1&#39;],<br> [ &#39;7&#39;, &#39;1&#39;, &#39;3&#39;, &#39;9&#39;, &#39;2&#39;, &#39;4&#39;, &#39;8&#39;, &#39;5&#39;, &#39;6&#39;],<br> [ &#39;9&#39;, &#39;6&#39;, &#39;1&#39;, &#39;5&#39;, &#39;3&#39;, &#39;7&#39;, &#39;2&#39;, &#39;8&#39;, &#39;4&#39;],<br> [ &#39;2&#39;, &#39;8&#39;, &#39;7&#39;, &#39;4&#39;, &#39;1&#39;, &#39;9&#39;, &#39;6&#39;, &#39;3&#39;, &#39;5&#39;],<br> [ &#39;3&#39;, &#39;4&#39;, &#39;5&#39;, &#39;2&#39;, &#39;8&#39;, &#39;6&#39;, &#39;1&#39;, &#39;7&#39;, &#39;9&#39;]<br>]</pre><p><strong>Conclusion</strong></p><p>Core programming concepts like recursion and backtracking could easily be used while solving a complex Sudoku problem. Breaking a big problem into smaller pieces and trying solutions sets with different permutations and combinations. This not only assists in improving our cognitive thinking skills, but also mandates to analyze problems from different perspectives. Understanding recursion and backtracking through Sudoku drives creative thinking and in turn be a better problem-solver.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=698c8ef8f5a9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Custom Debouncing and throttling in Javascript.]]></title>
            <link>https://medium.com/@adityakashyap_36551/custom-debouncing-and-throttling-in-javascript-c64e3e82392d?source=rss-fd80535c97b9------2</link>
            <guid isPermaLink="false">https://medium.com/p/c64e3e82392d</guid>
            <dc:creator><![CDATA[Aditya Gannavarapu]]></dc:creator>
            <pubDate>Sat, 20 Apr 2024 06:26:43 GMT</pubDate>
            <atom:updated>2024-04-20T06:35:04.337Z</atom:updated>
            <content:encoded><![CDATA[<h3>Custom Debouncing and Throttling in Javascript.</h3><p>Debouncing and throttling are essential engineering concepts, often mistaken but crucial for different tasks. Though developers often resort to libraries like lodash, grasping their core principles is vital for efficient applications. This article aims to clarify debouncing and throttling, emphasising their importance and enabling engineers to devise custom JavaScript implementations for tailored solutions.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LC-tOP3tjr_Xxs7KYq7_oA.png" /></figure><p>What will we cover in this article:</p><ul><li>Debouncing and its use cases.</li><li>Custom JS debounce fn()</li><li>Throttling and its use cases.</li><li>Custom JS throttle fn()</li></ul><h3>Debouncing:</h3><ol><li>Debouncing delays function execution util after a period of inactivity.</li><li>It consolidate multiple rapid functions calls into a single call by cancelling all other previous calls.</li><li>Debouncing function calls, optimises browser memory usage efficiently.</li><li>This technique proves valuable for scenarios where you aim to handle frequent event triggers, ensuring that the function is invoked only after a period of inactivity.</li></ol><p><strong>Use Cases</strong>:</p><ul><li>Search Input: Debouncing limits API requests by triggering search only after user pauses typing.</li><li>Button Clicks: Debouncing ensures actions are triggered only once, even with rapid clicks.</li><li>Scrolling Events: Debouncing reduces data fetching by loading content after scroll completion.</li><li>Window Resize: Debouncing window resize delays re-rendering until resize completion.</li><li>Mouse Movement: Debouncing triggers actions like hover effects after brief mouse inactivity.</li></ul><h3>Custom debounce Implementation</h3><pre>function debouncing(cb, interval){<br>    let timeoutId;<br>    return function (){<br>        clearTimeout(timeoutId);<br>        timeoutId= setTimeout(cb, interval);<br>    }<br>};</pre><ul><li>This takes a callback and a time interval.</li><li>This returns a function adhering to the closure principals.</li><li>If any subsequent call to this function is triggered before the previous time out is executed then the previous timeout is cleared and a new timeout is being set.</li><li>If no new function trigger takes place the call in timeout in the task queue is fleshed by the event loop for execution.</li></ul><h3><strong>Throttling</strong></h3><ol><li>The purpose of debouncing is to regulate the execution of a function within a specific time interval.</li><li>It ensures that the function is triggered at a steady rate within the designated timeframe.</li><li>Throttling limits the frequency of function calls to a steady rate within a specified time interval.</li><li>Throttling function calls, optimises browser memory usage efficiently.</li><li>This technique proves valuable for scenarios where you aim to handle frequent event triggers, ensuring that the function is invoked at steady rate in a specific time interval.</li></ol><p><strong>Use cases </strong>:</p><ol><li>User Interaction: Throttling moderates user actions, like clicks or scrolls, preventing system strain and improving usability.</li><li>Scrolling: Throttling smooths scrolling, ensuring content loads steadily for seamless browsing.</li><li>Network Communication: Throttling manages API requests, preventing server strain and streamlining data transfer.</li><li>Real-time Data Handling: Throttling optimizes data processing, maintaining system stability in dynamic environments.</li><li>Event-driven Architectures: Throttling balances event flow, enhancing system performance in high-demand scenarios.</li></ol><h3><strong>Custom Implementation of Throttle function</strong></h3><pre>function throttle(cb, interval){<br>   let prevTime = 0<br>   return function(...args){<br>       let currTime = new Date();<br>       if(currTime-prevTime&gt;interval){<br>           cb.apply(this, args);<br>           prevTime = currTime<br>       }<br>   }<br>}</pre><ul><li>This takes a callback and a time interval.</li><li>This returns a function adhering to the closure principals.</li><li>The closure maintains the previous and current time check.</li><li>if the difference between the current and previous time exceeds the given interval cb is executed.</li><li>The current time becomes the previous time now.</li></ul><h3><strong>Summary</strong>:</h3><p>Yes that was all about Throttling and Debouncing.</p><p>In this article we explored two critical JavaScript event handling techniques: debouncing and throttling.</p><p><strong><em>Debouncing delays a series of calls until a pause occurs, while throttling limits the rate of a specific call within a defined interval.</em></strong> We explored practical applications and provide custom JavaScript implementations for both techniques, enabling developers to optimise event handling and enhance user experience efficiently.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c64e3e82392d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[React vs Svelte: Finding Your Perfect Fit]]></title>
            <link>https://medium.com/@adityakashyap_36551/react-vs-svelte-finding-your-perfect-fit-bebaa05f6134?source=rss-fd80535c97b9------2</link>
            <guid isPermaLink="false">https://medium.com/p/bebaa05f6134</guid>
            <category><![CDATA[react]]></category>
            <category><![CDATA[svelte]]></category>
            <category><![CDATA[frontend]]></category>
            <category><![CDATA[ui]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Aditya Gannavarapu]]></dc:creator>
            <pubDate>Thu, 08 Feb 2024 18:35:58 GMT</pubDate>
            <atom:updated>2024-02-08T18:35:58.240Z</atom:updated>
            <content:encoded><![CDATA[<p>In recent years, React has been the go-to framework in web development, but the rise of Svelte as a compelling alternative raises the question: React or Svelte? With Svelte offering benefits such as efficiency and simplicity, making the choice depends on your project’s specific requirements. Let’s dig into the strengths of each to aid your decision-making process.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/648/1*VV6mxoG92e3n3BPunNeplQ.png" /></figure><h3><strong>Topics</strong></h3><ul><li>React</li><li>Svelte</li><li>Comparative analysis</li><li>What suits me?</li></ul><h3>React</h3><ul><li>React was initially released by Facebook in May 2013.</li><li>React is js library and often requires supports from other libraries for utilities like state management, transpilation.</li><li>React offers a vast ecosystem of libraries and tools for enhanced development.</li><li>Transpilers are essential for react. Browsers usually do not understand ES6 code hence, babel transpiler convers the JSX to brower understandable JS code.</li><li>React has a JSX template which in other words in HTML inside javascript.</li><li>React works on the concept of one way data binding.</li><li>React uses the concept of Virtual DOM.</li><li>React includes virtual DOM and react runtime in the build.</li><li>The virtual DOM is compared to actual DOM and the part of DOM which needs update gets updated.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VGMWOduFMODYyQyLWgxX3A.png" /><figcaption>How react components are rendered.</figcaption></figure><h3>Svelte</h3><ul><li>Svelte is Compiler-Based, its compiler compiles the components into optimized JavaScript during build, resulting in efficient code execution.</li><li>It updates the DOM directly for fast rendering and efficient updates.</li><li>Scoped stylesheets ensure clean and maintainable CSS within components.</li><li>Svelte’s reactive system simplifies state management and enhances code readability.</li><li>Svelte’s concise syntax and minimal boilerplate make development straightforward.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*On5ZjzT-ZWlfqOi3YGc0TA.png" /><figcaption>How svelte components are rendered.</figcaption></figure><h3>Comparative Analysis</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9riMecbHZRERG06qHDvgSg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*el6ySghxsmYAOX7V7Eg2Pw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0DprnGBHkMYamwZd2LJN8g.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*l5hF1eZZQoZLEIz0SwiWiQ.png" /><figcaption>React vs Svelte</figcaption></figure><h3>How to choose one?</h3><ul><li><strong>Complexity</strong>: React is ideal for complex applications, while Svelte is better suited for simpler ones.</li><li><strong>Developer Experience</strong>: Prioritize Developer Experience; use React if your team is familiar with it, and consider Svelte for its simplicity.</li><li><strong>Performance</strong>: Svelte provides faster load times and updates, making it a strong choice for performance-driven projects.</li><li><strong>Ecosystem Support</strong>: React boasts a larger library ecosystem, whereas Svelte’s is growing steadily.</li><li><strong>Maintenance</strong>: React benefits from established support, while Svelte’s support is newer and evolving.</li><li><strong>Interoperability</strong>: React excels in interoperability, while Svelte’s lightweight design may require more customized solutions for integration.</li></ul><h3><strong>Summary</strong></h3><p>We’ve explored both React and Svelte, two frameworks for building standalone applications. We’ve discussed how to choose the best one for specific requirements. We’ve highlighted areas where Svelte excels over React and vice versa. However, ultimately, the decision comes down to factors like project complexity, familiarity with each tool, and the need for speed. Considering these factors will guide you in selecting the most suitable framework for your project.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bebaa05f6134" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Priority Queue in JavaScript: Binary Heap]]></title>
            <link>https://medium.com/@adityakashyap_36551/priority-queue-in-javascript-binary-heap-076d0d38703f?source=rss-fd80535c97b9------2</link>
            <guid isPermaLink="false">https://medium.com/p/076d0d38703f</guid>
            <category><![CDATA[dsa-courses]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[priority-queue]]></category>
            <category><![CDATA[data-structures]]></category>
            <category><![CDATA[algorithms]]></category>
            <dc:creator><![CDATA[Aditya Gannavarapu]]></dc:creator>
            <pubDate>Sat, 20 Jan 2024 18:59:08 GMT</pubDate>
            <atom:updated>2024-01-20T18:59:08.286Z</atom:updated>
            <content:encoded><![CDATA[<p>In JavaScript, there is no built-in implementation of a priority queue in the standard library. However, you can implement a priority queue using various data structures, and one common choice is to use a binary heap.</p><h3>Topics:</h3><ul><li>Binary heap in JS</li><li>Types of binary heap</li><li>Usecases for priority queuue</li><li>Implementation of priority quque using Binary heap.</li></ul><h3><strong>Binary heap</strong></h3><p>A binary heap is a type of data structure used for prioritizing elements in an array. It’s like an array where you put values based on their priority, which is determined by a constant. The higher (or lower) the priority, the closer the element is to the front of the array. It’s a way of organising values to quickly find and remove the one with the highest (or lowest) priority.</p><h3>Types</h3><ol><li><strong>Min Heap</strong>: In a min heap, the element with the smallest priority (value) is at the top of the heap (the root). This allows for efficient retrieval of the minimum element when dequeuing. The structure of the min heap ensures that the parent node has a smaller value than its children, creating a hierarchy that facilitates quick access to the minimum element.</li><li><strong>Max Heap</strong>: In a max heap, the element with the highest priority (largest value) is at the top of the heap. This arrangement allows for efficient retrieval of the maximum element when dequeuing. The structure of the max heap ensures that the parent node has a larger value than its children, creating a hierarchy that facilitates quick access to the maximum element.</li></ol><h3><strong>Use cases</strong></h3><ol><li>Dijkstra’s / Shortest Path Algorithms</li><li>Task scheduling/ prioritization.</li><li>Job Scheduling in Parallel Computing</li><li>A* search algorithm</li></ol><h3><strong>Implementation</strong></h3><ul><li><strong>Enqueue</strong>: Adding an element to the the queue.</li><li><strong>Dequeue</strong>: Removing an element from the queue.</li><li><strong>Size</strong>: Returns the number of elements in the queue.</li><li><strong>isEmpty</strong>: Returns true if the queue is empty, false otherwise.</li></ul><p><strong>Min heap Implementation:</strong></p><ul><li><strong>Enqueue</strong>: Adding an element to the the queue based on the lowest priority.</li><li><strong>Dequeue</strong>: Removing an element from the queue from the front.</li></ul><pre>class PriorityQueue{<br>    constructor(){<br>        this.values = [];<br>    }<br>    <br>    enqueue(node, priority){<br>        var flag = false;<br>        for(let i=0; i&lt;this.values.length; i++){<br>            if(this.values[i].priority&gt;priority){<br>                this.values.splice(i, 0, {node, priority})<br>                flag = true;<br>                break;<br>            }<br>        }<br>        if(!flag){<br>            this.values.push({node, priority})<br>        }<br>    }<br>    <br>    dequeue(){<br>        return this.values.shift()<br>    }<br>    <br>    size(){<br>        return this.values.length;<br>    }<br>}<br><br>var a = new PriorityQueue()<br>a.enqueue(10,1)<br>a.enqueue(1, 0)<br>a.enqueue(8,2)<br>console.log(a.dequeue())<br>console.log(a.dequeue())<br>console.log(a.dequeue())</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BRSj247ue9i8fQKJBGE3Dg.png" /><figcaption>dequeuing elements with minimum priorities</figcaption></figure><p><strong>Max heap Implementation</strong></p><ul><li><strong>Enqueue</strong>: Adding an element to the the queue based on the highest priority.</li><li><strong>Dequeue</strong>: Removing an element from the queue from the front.</li></ul><pre>class PriorityQueue{<br>    constructor(){<br>        this.values = [];<br>    }<br>    <br>    enqueue(node, priority){<br>        var flag = false;<br>        for(let i=0; i&lt;this.values.length; i++){<br>            if(this.values[i].priority&lt;priority){<br>                this.values.splice(i, 0, {node, priority})<br>                flag = true;<br>                break;<br>            }<br>        }<br>        if(!flag){<br>            this.values.push({node, priority})<br>        }<br>    }<br>    <br>    dequeue(){<br>        return this.values.shift()<br>    }<br>    <br>    size(){<br>        return this.values.length;<br>    }<br>}<br><br>var a = new PriorityQueue()<br>a.enqueue(10,1)<br>a.enqueue(1, 0)<br>a.enqueue(8,2)<br>console.log(a.dequeue())<br>console.log(a.dequeue())<br>console.log(a.dequeue())</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/980/1*vC_xLYEe5vbi7Sgr1x1Xgw.png" /><figcaption>dequeuing elements with maximum priorities</figcaption></figure><p><strong><em>Please note, this is not the actual implementation of binary heap however this would be enough to deal with pragmatic use cases on day to day basis.</em></strong></p><p><strong>Conclusion</strong></p><p>JavaScript lacks a built-in priority queue, this basic implementation is handy for tasks needing efficient prioritizations. You can adjust it to work as a min heap or max heap, depending on your needs, showcasing the adaptability of JavaScript in various programming scenarios</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=076d0d38703f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Disjoint /Union Set in JavaScript: Graph (Leetcode)]]></title>
            <link>https://medium.com/@adityakashyap_36551/disjoint-union-set-in-javascript-graph-leetcode-0425f274d222?source=rss-fd80535c97b9------2</link>
            <guid isPermaLink="false">https://medium.com/p/0425f274d222</guid>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[es6]]></category>
            <category><![CDATA[leetcode]]></category>
            <category><![CDATA[data-structure-algorithm]]></category>
            <dc:creator><![CDATA[Aditya Gannavarapu]]></dc:creator>
            <pubDate>Fri, 12 Jan 2024 17:30:47 GMT</pubDate>
            <atom:updated>2024-01-12T17:30:47.721Z</atom:updated>
            <content:encoded><![CDATA[<p>LeetCode graph problems, encountering questions involving Union Sets (also known as Disjoint Sets) is a common theme. These problems often revolve around determining connected components, counting islands, or solving scenarios like stone groupings. Despite their significance, JavaScript solutions for these problems are scarcely found on the internet. This article serves as a consolidated resource, offering comprehensive JavaScript solutions to LeetCode challenges related to Union Sets, providing clarity and guidance in one centralised location.</p><p>Topics:</p><ul><li>Problem statement</li><li>Rank</li><li>Size</li><li>Functions</li><li>Disjoint-set Data structure.</li><li>Summary</li></ul><h3><strong>Problem statement</strong></h3><ul><li>Lets say we have 4 nodes [1,2,3,4], var edges = [[1,2], [2,3], [3,4]];</li><li>These nodes are somehow connected with each other to one of the root.</li><li><strong>To rephrase, each node is somehow connected to an ultimate node which is also know as the ultimate parent.</strong></li><li>This node is also the union of this set or this disjoint set.</li><li>We can find the union either by considering the union rank or by considering the union size.</li><li>We will see how we can do that programatically in this article.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/638/1*N-Hl-AA5kW8bkgkMR2CK9g.png" /><figcaption>Graphical representation of edges [[1,2], [2,3], [3,4]]</figcaption></figure><h3><strong>Rank</strong></h3><ul><li>Rank is the approximate height of a node in a tree-based representation of a disjoint set. It is used to optimize the union operation by attaching the smaller tree to the root of the larger tree, helping to keep the overall height of the trees small and maintain efficient performance.</li><li>When we</li><li>For this case the rank will be [1,0,0,0] or [0,1,0,0].</li><li>Element 1 is the root of its own set, so its rank is 1.</li><li>Elements 2, 3, and 4 are connected to element 1, so their ranks are 0.</li><li>Every time a node is connected to other the <strong>ultimate parent of node with larger parent rank is assigned the parent of the parent of node with smaller rank.</strong></li><li>If ranks are same them increment the rank by one.</li></ul><h3>Size</h3><ul><li>Size is the summation of the number of nodes who are finally connected. Size of two nodes which are clubbed together.</li><li>Initially each node is initialised with size of 1.</li><li>Every time a node is connected to other we just summate their sizes and refer the node with larger size as the parent of the node with smaller size.</li></ul><h3>Methods:</h3><ol><li>Constructor :<br> * Parent: initialise the parent array with the index as itself.<br> * Size: initialise the size of each vertex as 1.<br> * Rank: initialise the size of each vertex as 0.</li><li>findUltimateParent: A recursive function to find the nth parent while finding the union.</li><li>unionByRank(src, des): This sets the rank of each node if the parent of src and des are not equal. Every time a node is connected to other the <strong>ultimate parent of node with larger parent rank is assigned the parent of the parent of node with smaller rank. </strong>refer<strong> </strong>unionByRank(src, des)</li><li>unionBySize(src, des): This sets the size of each node if the parent of src and des are not equal. Every time a node is connected to other the <strong>ultimate parent of node with larger parent size is assigned the parent of the parent of node with smaller size. </strong>refer<strong> </strong>unionBySize(src, des)</li></ol><h3>Disjoint set Implementation</h3><pre>class DisjointSet{<br>    constructor(n){<br>        this.parent = new Array(n).fill().map((_, i) =&gt; i);<br>        this.size = new Array(n).fill(1);<br>        this.rank = new Array(n).fill(0);<br>    }<br>    <br>    findUltimateParent(a){<br>        if(this.parent[a] === a) return a<br>        return this.parent[a] = this.findUltimateParent(this.parent[a]);<br>    }<br>    <br>    unionByRank(src, des){<br>        let srcUltimateParent = this.findUltimateParent(src);<br>        let desUltimateParent = this.findUltimateParent(des);<br>        if(srcUltimateParent === desUltimateParent) return;<br>        <br>        let srcUltimateParentRank = this.rank[srcUltimateParent];<br>        let desUltimateParentRank = this.rank[desUltimateParent];<br>        <br>        if(srcUltimateParentRank&lt;desUltimateParentRank){<br>            this.parent[srcUltimateParent] = desUltimateParent;<br>        } else if(desUltimateParentRank&lt;srcUltimateParentRank){<br>             this.parent[desUltimateParent] = srcUltimateParent;<br>        } else {<br>            this.parent[srcUltimateParent] = desUltimateParent;<br>            this.rank[desUltimateParent]++;<br>        }<br>    }<br>    <br>    unionBySize(src, des){<br>        let srcUltimateParent = this.findUltimateParent(src);<br>        let desUltimateParent = this.findUltimateParent(des);<br>        if(srcUltimateParent === desUltimateParent) return;<br>        <br>        let srcUltimateParentSize = this.size[srcUltimateParent];<br>        let desUltimateParentSize = this.size[desUltimateParent];<br>        <br>        if(srcUltimateParentSize&gt;desUltimateParentSize){<br>             this.parent[desUltimateParent] = srcUltimateParent;<br>             this.size[srcUltimateParent]+= this.size[desUltimateParent]<br>        } else {<br>             this.parent[srcUltimateParent] = desUltimateParent;<br>              this.size[desUltimateParent]+= this.size[srcUltimateParent]<br>        }<br>    }<br>    <br>    isConnected(a, b){<br>        return this.findUltimateParent(a) === this.findUltimateParent(b);<br>    }<br>}<br></pre><p>Examples:</p><p>Union By Size:</p><pre>const edges = [[0,1], [1,2], [2,3]], n = 4<br><br>function disjointSet(edges, n){<br>    let ds = new DisjointSet(n);<br>    for(let i =0; i&lt;edges.length; i++){<br>        if(!ds.isConnected(edges[i][0], edges[i][1])){<br>            //ds.unionByRank(edges[i][0], edges[i][1])<br>            ds.unionBySize(edges[i][0], edges[i][1])<br>        }<br>    }<br>    <br>   return ds.size;<br>}<br><br>console.log(disjointSet(edges, n))</pre><p>Output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XLxhT9V9oEvqUwrHyWI8bw.png" /></figure><p>Union By Rank:</p><pre>const edges = [[0,1], [1,2], [2,3]], n = 4<br><br>function disjointSet(edges, n){<br>    let ds = new DisjointSet(n);<br>    for(let i =0; i&lt;edges.length; i++){<br>        if(!ds.isConnected(edges[i][0], edges[i][1])){<br>            ds.unionByRank(edges[i][0], edges[i][1])<br>            //ds.unionBySize(edges[i][0], edges[i][1])<br>        }<br>    }<br>    <br>   return ds.rank;<br>}<br><br>console.log(disjointSet(edges, n))</pre><p>Output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/690/1*dOAP5toSmGCi78VtJT_3GQ.png" /></figure><h3>Summary</h3><p>As we explore disjoint sets, we’ve grasped essential functions like finding parents and uniting sets using techniques such as union by size and union by rank. This knowledge serves as a valuable tool, making it easier to handle graphical problems efficiently. It enhances our ability to navigate complex graphs, providing a smoother path to solving various graph-related challenges with clarity and proficiency.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0425f274d222" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Pub-Sub Pattern: Event Management in JavaScript]]></title>
            <link>https://medium.com/@adityakashyap_36551/the-pub-sub-pattern-event-management-in-javascript-17196444ca2f?source=rss-fd80535c97b9------2</link>
            <guid isPermaLink="false">https://medium.com/p/17196444ca2f</guid>
            <category><![CDATA[pub-sub-pattern]]></category>
            <category><![CDATA[frontend]]></category>
            <category><![CDATA[patterns]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Aditya Gannavarapu]]></dc:creator>
            <pubDate>Sat, 30 Sep 2023 02:17:43 GMT</pubDate>
            <atom:updated>2023-09-30T02:25:07.687Z</atom:updated>
            <content:encoded><![CDATA[<p>The Publish-Subscribe (Pub-Sub) pattern, whether you’re engaged in React, Angular, or RxJS development, is a fundamental concept that impacts our everyday work. It’s quite common for us to employ this pattern, often without deliberate awareness. Whether consciously or inadvertently, understanding Pub-Sub is valuable, as it underpins effective communication and modularity in our applications. For example, when you subscribe to a store, utilize reducers, or trigger actions in Redux, you are essentially leveraging the principles of Pub-Sub for managing state and orchestrating interactions.</p><p>In this Article we will be implementing the Pub-sub pattern using the the custom event concept of Javascript.</p><h3><strong>Topics:</strong></h3><ol><li>Custom events concepts : on, off, Emit</li><li>Subscribe</li><li>Unsubscribe</li><li>Publish</li><li>A general scenario</li></ol><h3><strong>1. Custom event concepts</strong></h3><p>In javascript we can create a custom event Emitter the custom emmiter concept has three fundamentals</p><p>a. <strong>on</strong>: on is similar to subscribe you can register an event and the callback using ON</p><p>b. <strong>off</strong>: on is similar to unsubscribe you can de-register andevent and the callback using OFF</p><p>c. <strong>emit</strong>: Emit is similar publish where each callback registered on an event is triggered with some data.</p><h3>2. <strong>Subscribe</strong></h3><p>The core fundamental of subscribe is to register a callback on an event. You can register `n` number of callbacks to one specific event. <em>Note this is not valid for DOM events (addEventListener , they work with one to one mapping that the main difference between DOM events and custom events).</em></p><p><strong>This is similar to the ON logic of custom emitter.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*voXLtDZpwLlVKePfsHaJzg.png" /><figcaption>Subscribe registers a listener to an event</figcaption></figure><h3>3. <strong>Unsubscribe:</strong></h3><p>The core fundamental of unsubscribe is to de-register a callback on an event. You can remove a callback from a specific event based on reference.</p><p>We first find the index of the target callback based on reference and eventually splice the target callback.</p><p><strong>This is similar to the OFF logic of custom emitter.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*781V9053wqVFr8oI2ntKEw.png" /><figcaption>Un-subscribe deregisters a callback from an event</figcaption></figure><h3>4. <strong>Publish</strong></h3><p>As the name implies, the core fundamental of publish is to publish/ emit the data to all the listeners of a particular event. Publish, simultaneously emits the data to all the listeners with a specified data.</p><p><strong>This is similar to the Emit logic of custom emitter.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lqQCFkjUtlaGskezwIux3A.png" /><figcaption>Emitting data to all the listeners/handlers</figcaption></figure><h3>5. <strong>Pub-Sub Implementation put together.</strong></h3><pre>class PublishSubscribe{<br>    constructor(){<br>        this.events = {}<br>    }<br>    <br>    // on logic can be leveraged to fulfill subscribe<br>    subscribe(event, handler){<br>        if(!this.events[event]){<br>            this.events[event] = []<br>        }<br>        this.events[event].push(handler)<br>    }<br>    <br>    //off logic can be leveraged to fulfill unsubscribe<br>    unsubscribe(event, handler){<br>        if(this.events[event]){<br>            const index = this.events[event].findIndex(item =&gt; item === handler)<br>            this.events[event].splice(index, 1);<br>        }<br>    }<br>    <br>    //emit logic can be leveraged to fulfill unsubscribe<br>    publish(event, data){<br>        if(this.events[event]){<br>            this.events[event].forEach(handler =&gt; handler(data));<br>        }<br>    }<br>}<br><br>const pubSubClient = new PublishSubscribe()<br><br>pubSubClient.subscribe(&#39;someEvent&#39;, data =&gt; {<br>    console.log(`I am subscriber 1 with published data ${data}`)<br>})<br><br>pubSubClient.subscribe(&#39;someEvent&#39;, data =&gt; {<br>   console.log(`I am subscriber 2 with published data ${data}`)<br>})<br>console.log(`**********After two subscriptions *************`)<br><br>pubSubClient.publish(&#39;someEvent&#39;, &quot;DATA FROM PUBLISH&quot;)<br><br>console.log(`**********Data published to both subscribers*************`)<br><br>pubSubClient.unsubscribe(&#39;someEvent&#39;, data =&gt; {<br>   console.log(`I am subscriber 2 with published data ${data}`)<br>})<br><br>// again publishing<br>console.log(`**********After unsubscribe*************`)<br>pubSubClient.publish(&#39;someEvent&#39;, &quot;DATA FROM PUBLISH&quot;)<br><br></pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MLf-YyMx7XnITLq588OTsQ.png" /><figcaption>Output based on the above code.</figcaption></figure><h3><strong>Summary</strong></h3><p>Pub-Sub is a crutial pattern to leverage the understanding of building scalable, maintainable, and responsive applications. It not only promotes clean code but also enables efficient communication between components. Thereby, making it an invaluable tool in modern web development.</p><p>Moreover, It helps developers understand the internal functioning of many libraries and frameworks, as the Pub-Sub pattern is often used as a core concept in various programming environments. This insight is invaluable for working with and customizing libraries and frameworks effectively.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=17196444ca2f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Decoding Promises: Custom Promise from the Ground Up.]]></title>
            <link>https://medium.com/@adityakashyap_36551/decoding-promises-custom-promise-class-from-the-ground-up-e1c198481f36?source=rss-fd80535c97b9------2</link>
            <guid isPermaLink="false">https://medium.com/p/e1c198481f36</guid>
            <category><![CDATA[front-end-development]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[es6]]></category>
            <category><![CDATA[promises]]></category>
            <dc:creator><![CDATA[Aditya Gannavarapu]]></dc:creator>
            <pubDate>Sat, 09 Sep 2023 03:55:21 GMT</pubDate>
            <atom:updated>2023-09-09T04:28:07.561Z</atom:updated>
            <content:encoded><![CDATA[<p>Many developers limit themselves to merely grasping the surface-level implementation of promises, but only a small number dig into the inner workings of the mechanism.In this article, we will dive deeply into the construction of promises, specifically a custom promise, to gain a comprehensive understanding of their inner workings.</p><p>I would highly recommend to first understand the syntax and working of actual promise before diving deep into this article.</p><p><strong><em>Please note : This implementation is just a representation of actual promise but may miss some crucial aspects like promise.all(), promise.allSettled(), promise.race(), static resolve reject methods and finally.</em></strong></p><p>We are restricting our scopes to the below:</p><ul><li>Promise constructor</li><li>State of a Promise</li><li>Resolve/ Reject</li><li>Then</li><li>ExecuteHandlers</li><li>Catch</li></ul><h3><strong>1. States of a promise</strong></h3><ul><li>Promise can be either PENDING, RESOLVED or REJECTED.</li><li><em>PENDING</em>: when the promise has not been resolved.</li><li><em>RESOLVED</em>: when the promise has a successful resolution.</li><li><em>REJECTED</em>: when the promise is discarded.</li><li>We will maintain the states object as a constant.</li><li>If Promise is not yet resolved its STATE.PENDING</li><li>Else a promise will be STATE.RESOLVED if successful or STATE.REJECTED.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nKqGNQPrFOXXiKtubvNJ-w.png" /><figcaption>State a Promise respects.</figcaption></figure><h3><strong>2. Promise constructor</strong></h3><p>Within a promise constructor we will define four things:<br> 1. State Initialization: Initialising the state to pending as a promise is neither resolved nor rejected.<br> 2. Initialise the value of. Promise to null, this would be set once a promise is resolved or rejected<br> 3. Have appropriate handlers which would be executed in the near future asynchronously.<br>4. Trigger the callback executor function so that a promise is initialized and respective states are either resolved or rejected.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_3SOFF_i-AbyNSntYAe7ig.png" /><figcaption>Constructor definition of a promise.</figcaption></figure><h3><strong>3. Resolve/Reject:</strong></h3><ul><li>Whenever we trigger a promise its value will be either resolved or rejected.</li><li>Rejected and resolved promise states have already ended their lifecycle hence resolve rejected is not called.</li><li>Promise will only be resolved if it is unresolved (i.e pending state.) and the promise is a success.</li><li>When a promise is resolved the state is updated to resolved.</li><li>The values is set to the value passed a param to the resolved function.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dksxxGzQh7yKTmIFKJidqg.png" /><figcaption>Resolve is triggered when a promise is resolved</figcaption></figure><ul><li>Whenever we trigger a promise its value will be either resolved or rejected.</li><li>Promise will only be rejected if it is unresolved (i.e pending state) and the promise is a failed.</li><li>Rejected and resolved promise states have already ended their lifecycle hence resolve rejected is not called.</li><li>When a promise is rejected the state is updated to rejected.</li><li>The values is set to the value passed a param to the resolved function/ or catch function.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VSe2Xe9ZXftxZtWKoE433Q.png" /><figcaption>Reject is triggered when a promise is rejected</figcaption></figure><h3><strong>3. Then</strong></h3><ul><li>Then is a function which continues the promise execution and eventually leads to ultimate resolution or rejection.</li><li>Then should be chain-able as promise can in-turn return another promise.</li><li>Thus, then should always return a new promise Instance.</li><li>Then takes two params, one is the successCall back other being the failure callback .</li><li>Whenever then is triggered a new promise is triggered and handers are fed with an object which takes the resolve /reject of the new promise object and also pass success and failure callbacks.</li><li>After passing the values to handlers the handlers are initialied (executor function)with in the constructor of the new Promise.</li><li><strong>The key point to understand here is that the </strong><strong>onSuccess handler captures the value in its closure when it is created, not when it&#39;s executed.</strong></li><li><strong>Therefore, even though the handler is part of the new promise’s context, it still has access to the value from the previous promise.</strong></li><li>So, the value of the previous promise is preserved in the closure of the onSuccess handler, allowing you to access it even when creating new promises.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-rtZjgQye0pZKK6DCD9CmQ.png" /><figcaption>Then always returns a promise as then should be chainable</figcaption></figure><h3>4.<strong> Executehandler helper:</strong></h3><ul><li>Execute handlers has two flows, one when the state is resolved and the other being the rejected flow.</li><li>Both the flows, pretty much follow the same signature the only difference being on resolve we trigger the onSuccess if provided.</li><li>Whereas, on rejected we trigger the onFail callback if provided.</li><li>In order, to mimic asynchrony we use setTimeout , even a 0 timelapse would work as we just want to out this function in the macrotask queue(event loop)<em> I would soon publish an article on Eventloops, Micro and macro task queues.</em></li><li>Execute handler basically checks the below usecases:</li></ul><ol><li>if onSuccess/ onFail provided it executed them with the value of current promise.</li><li>if onSuccess/ onFail is not provided then simply resolve reject the new promise created in then with the current Value.</li><li>if onSuccess/ onFail returns a new Promise. execute that promise then and there itself and pass the resolved/ rejected value of this promise to the intermediate promise created as a part of then. this maintains the chaining.</li><li>On any exception directly trigger the reject function of the intermediate promise create via then.</li></ol><p><strong><em>For detailed comments refer the code at the bottom of the article.</em></strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_iFrYzZG0Ejy1gX7O9O4IQ.png" /><figcaption>Resolved State of then</figcaption></figure><p><strong><em>For detailed comments refer the code at the bottom of the article.</em></strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ftg7eXy5UFUtQJPRrvw0ng.png" /><figcaption>Rejected State of then</figcaption></figure><h3><strong>Catch:</strong></h3><ol><li>In a promise chain, when an error occurs in any of the preceding then methods (e.g., an exception is thrown), the normal flow of the chain is disrupted.</li><li>The promise chain jumps to the nearest catch block down the chain, skipping any remaining then blocks.</li><li>The code within the catch block is executed, and it receives the error as an argument, allowing you to handle or log the error as needed.</li><li>After the catch block is executed, the promise chain continues with its normal flow, which means you can still attach more then or catch blocks after the catch block to handle subsequent promises.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*brMF2DkNPk2ZTR4HjpkmOg.png" /></figure><p><strong><em>Putting it all together:</em></strong></p><pre><br>const state = {<br>    PENDING: &#39;pending&#39;, <br>    RESOLVED:&#39;resolved&#39;,<br>    REJECTED: &#39;rejected&#39;<br>}<br><br>class CustomPromise {<br>    constructor(executor){<br>        // executor is the callback which is initialized when a promise is created.<br>        this.value = null;<br>        this.handlers = [];<br>        this.state = state.PENDING;<br>        <br>        try{<br>            // execute the executor with resolve and rejects as params.<br>            executor(this.resolve.bind(this), this.reject.bind(this))<br>        }catch(e){<br>            this.reject(e)<br>        }<br>    }<br>    <br>    resolve(value){<br>        // only resolve when unresolved<br>        if(this.state ===state.PENDING){<br>            this.state = state.RESOLVED;<br>        //update value to the resolved value<br>            this.value = value;<br>            this.handlers.forEach(item =&gt; item.onSuccess(this.value))<br>        }<br>    }<br>    <br>    reject(value){<br>        // only reject when unresolved<br>        if(this.state=== state.PENDING){<br>            this.state = state.REJECTED;<br>            // update value to the rejected value<br>            this.value = value;<br>            this.handlers.forEach(item =&gt; item.onFail(this.value))<br>        }<br>    }<br>    <br>    executeHandlers(handleObj){<br> //handle the resolved flow<br>        if(this.state === state.RESOLVED){<br>           var cb = handleObj.onSuccess<br>           // to mock asynchrony<br>           setTimeout(() =&gt; {<br>               try{<br>                  // check if success callback present<br>                   if(typeof cb === &quot;function&quot;){<br>                  // if yes then execute the cb with the existing promise resolved value<br>                    var res = cb(this.value)<br>                  // if the result is inturn returns a promise<br>                    if(res instanceof CustomPromise){<br>                  // resolve the promise and set the value to returning promise.<br>                        res.then(resVal =&gt; handleObj.res(resVal), resVal =&gt; handleObj.rej(resVal))<br>                    } else {<br>                        setTimeout(() =&gt; {<br>                    // if res is not a promise directly resolve it withe the promise create from the previous then<br>                            handleObj.res(res)<br>                        }, 0)<br>                    }<br>               }else {<br>// if success callback not present simply resolve the promise with the result of callback<br>                   handleObj.res(this.value)<br>               }<br>               }catch(e){<br>// on any exception trigger the reject handler.<br>                  handleObj.rej(e) <br>               }<br>           })<br>//handle the rejected flow below<br>        } else if(this.state === state.REJECTED){<br>            // to mock asynchrony<br>            var cb = handleObj.onFail;<br>            setTimeout(() =&gt; {<br>                try{<br>                  // check if failure callback present<br>                    if(typeof cb === &quot;function&quot;){<br>// if yes then execute the cb with the existing promise resolved value<br>                        const res = cb(this.value)<br>// if the result is inturn returns a promise<br>                        if(res instanceof CustomPromise){<br>                            res.then(resVal =&gt; handleObj.res(resVal), resVal =&gt; handleObj.rej(resval))<br>                        } else {<br>                            setTimeout(() =&gt; {<br>// if res is not a promise directly reject it withe the promise create from the previous then<br>                                 handleObj.rej(res)<br>                        }, 0)<br>                        }<br>                    } else{<br>// if failure callback not present simply resolve the promise with the result of callback<br>                        handleObj.rej(this.value)<br>                    }<br>                } catch(e){<br>// on any exception trigger the reject handler.<br>                   handleObj.rej(e)   <br>                }<br>            })<br>        }<br>    }<br>    <br>    then(onSuccess, onFail){<br>// everytime a then is triggerred return a new promise<br>        return new CustomPromise((res, rej) =&gt; {<br>// as a part of constructor function push handlers with new resolve , reject and prev onSuccess. onFail<br>            this.handlers.push({<br>                res,<br>                rej,<br>                onSuccess,<br>                onFail<br>            })<br>//execute the handlers to kickstart<br>            this.executeHandlers(this.handlers[this.handlers.length-1])<br>        })<br>    }<br>    <br>    catch(onFail) {<br>// onany failure / exception gracefully handle the scenarios<br>        return this.then(null, onFail);<br>    }<br>}<br><br>let a = new CustomPromise((res, rej) =&gt; {<br>    <br>    res(5)<br>})<br><br>a.then((val) =&gt; {<br>    //createdNew promise with old new resolve reject and new onSuccess onFail function<br>    console.log(val)<br>    return new CustomPromise((res, rej) =&gt; {<br>        res(10)<br>    })<br>}).then(val =&gt; {<br>    console.log(val)<br>})<br><br></pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MyPXfT2X9KAndBiK6yEQgw.png" /><figcaption>output for above code.</figcaption></figure><ul><li>In the above example we are resolving a promise with value 5 as a part of its constructor where resolve is triggered.</li><li>Resolve sets the value as 5 and state as resolved.</li><li>On the first <strong>then</strong> we return a new Custom promise</li><li>However, while creating this new custom promise the internal constructor functional is executed and excute the executeHandler function.</li><li>Since in this case we are returning another custom promise.</li><li>hence it falls in the scenario of callback returning a custom promise hence we will execute the custom promise with resolved value as 10).</li><li>While execution of this new Custom promise we set the value to 10.</li><li>On next then trigger we just trigger the new promise’s then with the previous promise value.</li><li>Thats how we settle all values.</li></ul><h3><strong>Conclusion</strong></h3><p>I know this wasn’t an easy task . However, Promises are must to understand the asynchrony and this small project will certainly help us grow as developers.</p><p>By examining these fundamental aspects of promises, readers gain valuable insights into how promises work internally. It’s important to note that while this custom promise implementation provides a simplified view of promises, real-world promises offer additional features like Promise.all(), Promise.race(), and static methods such as Promise.resolve() and Promise.reject(). Nonetheless, understanding the core concepts presented here forms a solid foundation for comprehending the inner workings of promises in JavaScript.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e1c198481f36" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>