{
    "version": "https://jsonfeed.org/version/1",
    "title": "João Melo",
    "home_page_url": "https://jopcmelo.dev",
    "feed_url": "https://jopcmelo.dev/rss/feed.json",
    "description": "A software engineer, and open-source contributor.",
    "icon": "https://jopcmelo.dev/favicon.ico",
    "author": {
        "name": "João Melo"
    },
    "items": [
        {
            "id": "https://jopcmelo.dev/articles/dijkstras-algorithms",
            "content_html": "<p>Have you ever wondered when navigating Google Maps how it comes up with the quickest route to your destination? The answer to your curiosity lies in the magnificent world of weighted graphs and Dijkstra&#x27;s algorithm.</p>\n<p>Let&#x27;s explore this further. Imagine you&#x27;re traveling on different roads of unequal lengths and different speed limits, thus affecting the time spent on each route. In graph theory, this scenario could symbolize a weighted graph where each edge (or path) carries its weight (the time spent on each road). Therefore, finding the quickest route essentially means figuring out the shortest path in this weighted graph, and here is where Dijkstra&#x27;s algorithm comes to play. This article will walk you through a deep understanding of weighted graphs and the backbone of quickest route algorithms, Dijkstra&#x27;s algorithm.</p>\n<h2>A Closer Look at Dijkstra&#x27;s Algorithm</h2>\n<p>Let&#x27;s explore the following weighted graph.</p>\n<img alt=\"Weighted graph representation\" fetchpriority=\"high\" width=\"490\" height=\"139\" decoding=\"async\" data-nimg=\"1\" style=\"color:transparent\" src=\"/_next/static/media/weighted-graph.54f87fa9.svg\"/>\n<p>This graph shows two possible routes from the Origin to Destiny. The numbers represent the time it takes to move from one point to another. If you recall from our discussion on <a href=\"https://www.jopcmelo.dev/articles/introduction-to-graphs\">breadth-first search</a>, it would suggest the shortest route as <code>Origin -&gt; A -&gt; Destiny</code>. While this path has fewer segments, the quickest option would be through Dijkstra&#x27;s Algorithm, taking the path <code>Origin -&gt; B -&gt; A -&gt; Destiny</code>, taking a total of 6 minutes.</p>\n<img alt=\"Weighted graph representation\" fetchpriority=\"high\" width=\"490\" height=\"139\" decoding=\"async\" data-nimg=\"1\" style=\"color:transparent\" src=\"/_next/static/media/weighted-graph-solution.3019bf22.svg\"/>\n<p>Now that we know the result, let&#x27;s break it down into four simple steps:</p>\n<ol>\n<li>You identify the cheapest node. This refers to the node reachable in the least amount of time.</li>\n<li>Update the costs of its neighboring nodes.</li>\n<li>Repeat the process for every node in the graph.</li>\n<li>Calculate the final path.</li>\n</ol>\n<h3>Step 1: Finding the Cheapest Node</h3>\n<table><thead><tr><th>Vertex</th><th>Time</th></tr></thead><tbody><tr><td>A</td><td>6</td></tr><tr><td>B</td><td>2</td></tr><tr><td>Destiny</td><td>Infinity</td></tr></tbody></table>\n<p>You&#x27;re at the Origin contemplating your next stop: Node A takes 6 minutes, while Node B takes 2 minutes. The time required to get to the Destiny is still unknown, hence we consider it infinite for now. Therefore, Node B becomes our cheapest node.</p>\n<h3>Step 2: Updating the Costs of the Neighbors</h3>\n<table><thead><tr><th>Vertex</th><th>Time</th></tr></thead><tbody><tr><td>A</td><td><del>6</del> 5</td></tr><tr><td>B</td><td>2</td></tr><tr><td>Destiny</td><td>7</td></tr></tbody></table>\n<p>From Node B, you realize you could reach Node A in 5 minutes (2 to get to B then 3 to A) which is a minute less than going directly. Subsequently, you update the time for Node A. Similarly, you understand that reaching the Destiny would take 7 minutes (2 to B then 5 to Destiny).</p>\n<h3>Step 3 and 4: Repeat and Compute the Final Path</h3>\n<p>The process is then repeated for Node A and the final path calculated. The quickest route ends up being <code>Origin -&gt; B -&gt; A -&gt; Destiny</code>, taking a total of 6 minutes.</p>\n<table><thead><tr><th>Vertex</th><th>Time</th></tr></thead><tbody><tr><td>A</td><td>5</td></tr><tr><td>B</td><td>2</td></tr><tr><td>Destiny</td><td><del>7</del> 6</td></tr></tbody></table>\n<h2>Digging into the Algorithm</h2>\n<p>In Dijkstra&#x27;s Algorithm, each edge possesses an associated number known as the weight and the graph becomes known as a &quot;weighted graph.&quot; Whereas previously in our <a href=\"https://www.jopcmelo.dev/articles/introduction-to-graphs\">breadth-first search</a>, the &quot;shortest path&quot; referred to the minimum number of segments, in Dijkstra&#x27;s interpretation, it implies the path with the least cumulative weight.</p>\n<p>One caveat in Dijkstra&#x27;s algorithm is its inefficiency in dealing with cycles. A cycle occurs when you can start at one vertex and traverse through the graph to return to the same vertex. Take a look at the following example:</p>\n<img alt=\"Weighted graph representation\" loading=\"lazy\" width=\"365\" height=\"148\" decoding=\"async\" data-nimg=\"1\" style=\"color:transparent\" src=\"/_next/static/media/weighted-graph-cycles.f0da8edd.svg\"/>\n<p>Here, even though the quickest path is <code>Origin -&gt; A -&gt; B -&gt; Destiny</code> taking 3 minutes, Dijkstra&#x27;s algorithm may keep circling between A and B.</p>\n<h2>Handling Negative Weights</h2>\n<p>Dijkstra&#x27;s algorithm fails to handle negative weights. In cases where there are negative weights, like this:</p>\n<img alt=\"Weighted graph representation\" loading=\"lazy\" width=\"489\" height=\"114\" decoding=\"async\" data-nimg=\"1\" style=\"color:transparent\" src=\"/_next/static/media/weighted-graph-negative.ea08babd.svg\"/>\n<p>The quickest path would be <code>Origin -&gt; A -&gt; B -&gt; Destiny</code>, taking 33 minutes. Using Dijkstra&#x27;s algorithm, we would unusedly arrive at longer routes. Instead, for such cases, we use the Bellman-Ford algorithm, a more suitable algorithm for graphs involving negative weights. While Bellman-Ford isn&#x27;t in the scope of this article, we&#x27;ll surely approach it in possible future articles.</p>\n<h2>Implementing Dijkstra&#x27;s Algorithm</h2>\n<p>Let&#x27;s dive into creating Dijkstra&#x27;s algorithm for our initial graph using JavaScript. Before implementing, you&#x27;ll need three <a href=\"https://www.jopcmelo.dev/articles/hash-tables\">hash tables</a>.</p>\n<p>The first table will store the graph, the second table will store the costs, and the third table will store the parents. The cost and parents tables will be updated as the algorithm proceeds. Below you&#x27;ll find a sample implementation of Dijkstra&#x27;s algorithm.</p>\n<p>First, let&#x27;s implement the graph.</p>\n<pre class=\"language-javascript\"><code class=\"language-javascript\"><span class=\"token keyword\">const</span> graph <span class=\"token operator\">=</span> <span class=\"token punctuation\">{</span><span class=\"token punctuation\">}</span>\ngraph<span class=\"token punctuation\">[</span><span class=\"token string\">&#x27;origin&#x27;</span><span class=\"token punctuation\">]</span> <span class=\"token operator\">=</span> <span class=\"token punctuation\">{</span><span class=\"token punctuation\">}</span>\ngraph<span class=\"token punctuation\">[</span><span class=\"token string\">&#x27;origin&#x27;</span><span class=\"token punctuation\">]</span><span class=\"token punctuation\">[</span><span class=\"token string\">&#x27;a&#x27;</span><span class=\"token punctuation\">]</span> <span class=\"token operator\">=</span> <span class=\"token number\">6</span>\ngraph<span class=\"token punctuation\">[</span><span class=\"token string\">&#x27;origin&#x27;</span><span class=\"token punctuation\">]</span><span class=\"token punctuation\">[</span><span class=\"token string\">&#x27;b&#x27;</span><span class=\"token punctuation\">]</span> <span class=\"token operator\">=</span> <span class=\"token number\">2</span>\ngraph<span class=\"token punctuation\">[</span><span class=\"token string\">&#x27;a&#x27;</span><span class=\"token punctuation\">]</span> <span class=\"token operator\">=</span> <span class=\"token punctuation\">{</span><span class=\"token punctuation\">}</span>\ngraph<span class=\"token punctuation\">[</span><span class=\"token string\">&#x27;a&#x27;</span><span class=\"token punctuation\">]</span><span class=\"token punctuation\">[</span><span class=\"token string\">&#x27;destiny&#x27;</span><span class=\"token punctuation\">]</span> <span class=\"token operator\">=</span> <span class=\"token number\">1</span>\ngraph<span class=\"token punctuation\">[</span><span class=\"token string\">&#x27;b&#x27;</span><span class=\"token punctuation\">]</span> <span class=\"token operator\">=</span> <span class=\"token punctuation\">{</span><span class=\"token punctuation\">}</span>\ngraph<span class=\"token punctuation\">[</span><span class=\"token string\">&#x27;b&#x27;</span><span class=\"token punctuation\">]</span><span class=\"token punctuation\">[</span><span class=\"token string\">&#x27;a&#x27;</span><span class=\"token punctuation\">]</span> <span class=\"token operator\">=</span> <span class=\"token number\">3</span>\ngraph<span class=\"token punctuation\">[</span><span class=\"token string\">&#x27;b&#x27;</span><span class=\"token punctuation\">]</span><span class=\"token punctuation\">[</span><span class=\"token string\">&#x27;destiny&#x27;</span><span class=\"token punctuation\">]</span> <span class=\"token operator\">=</span> <span class=\"token number\">5</span>\ngraph<span class=\"token punctuation\">[</span><span class=\"token string\">&#x27;destiny&#x27;</span><span class=\"token punctuation\">]</span> <span class=\"token operator\">=</span> <span class=\"token punctuation\">{</span><span class=\"token punctuation\">}</span> <span class=\"token comment\">// The destination node has no neighbors</span>\n</code></pre>\n<p>In order to get all the neighbors of a node, you can use the <code>Object.keys()</code> method.</p>\n<div class=\"flex flex-col gap-4\"><div class=\"rounded-3xl border border-zinc-200/10 bg-[#0E0E10] shadow-inner transition-all duration-500 ease-in-out\"><div class=\"z-10 h-full w-full rounded-3xl bg-[#0E0E10] px-4 transition-all duration-500 ease-in-out\"><button class=\"inline-flex items-center justify-center whitespace-nowrap text-sm font-medium ring-offset-background transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50 h-10 px-4 py-2 relative -top-6 right-2 float-right rounded-2xl text-white bg-teal-600 hover:bg-teal-500\"><svg xmlns=\"http://www.w3.org/2000/svg\" width=\"24\" height=\"24\" viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"currentColor\" stroke-width=\"2\" stroke-linecap=\"round\" stroke-linejoin=\"round\" class=\"lucide lucide-rocket w-4 h-4 mr-3\"><path d=\"M4.5 16.5c-1.5 1.26-2 5-2 5s3.74-.5 5-2c.71-.84.7-2.13-.09-2.91a2.18 2.18 0 0 0-2.91-.09z\"></path><path d=\"m12 15-3-3a22 22 0 0 1 2-3.95A12.88 12.88 0 0 1 22 2c0 2.72-.78 7.5-6 11a22.35 22.35 0 0 1-4 2z\"></path><path d=\"M9 12H4s.55-3.03 2-4c1.62-1.08 5 0 5 0\"></path><path d=\"M12 15v5s3.03-.55 4-2c1.08-1.62 0-5 0-5\"></path></svg>Run code</button></div></div></div>\n<p>Now, you need a hash table to store the weights.</p>\n<pre class=\"language-javascript\"><code class=\"language-javascript\"><span class=\"token keyword\">const</span> weights <span class=\"token operator\">=</span> <span class=\"token punctuation\">{</span><span class=\"token punctuation\">}</span>\nweights<span class=\"token punctuation\">[</span><span class=\"token string\">&#x27;a&#x27;</span><span class=\"token punctuation\">]</span> <span class=\"token operator\">=</span> <span class=\"token number\">6</span>\nweights<span class=\"token punctuation\">[</span><span class=\"token string\">&#x27;b&#x27;</span><span class=\"token punctuation\">]</span> <span class=\"token operator\">=</span> <span class=\"token number\">2</span>\nweights<span class=\"token punctuation\">[</span><span class=\"token string\">&#x27;destiny&#x27;</span><span class=\"token punctuation\">]</span> <span class=\"token operator\">=</span> <span class=\"token number\">Infinity</span> <span class=\"token comment\">// The time to reach the destination is unknown for now</span>\n</code></pre>\n<p>And the last, but not least, you need a hash table to store the parents.</p>\n<pre class=\"language-javascript\"><code class=\"language-javascript\"><span class=\"token keyword\">const</span> parents <span class=\"token operator\">=</span> <span class=\"token punctuation\">{</span><span class=\"token punctuation\">}</span>\nparents<span class=\"token punctuation\">[</span><span class=\"token string\">&#x27;a&#x27;</span><span class=\"token punctuation\">]</span> <span class=\"token operator\">=</span> <span class=\"token string\">&#x27;origin&#x27;</span>\nparents<span class=\"token punctuation\">[</span><span class=\"token string\">&#x27;b&#x27;</span><span class=\"token punctuation\">]</span> <span class=\"token operator\">=</span> <span class=\"token string\">&#x27;origin&#x27;</span>\nparents<span class=\"token punctuation\">[</span><span class=\"token string\">&#x27;destiny&#x27;</span><span class=\"token punctuation\">]</span> <span class=\"token operator\">=</span> <span class=\"token keyword null nil\">null</span> <span class=\"token comment\">// The destination has no parent yet</span>\n</code></pre>\n<p>Finally, you need a way to keep track of all the processed vertices, as they don&#x27;t need to be processed more than once.</p>\n<pre class=\"language-javascript\"><code class=\"language-javascript\"><span class=\"token keyword\">const</span> processed <span class=\"token operator\">=</span> <span class=\"token keyword\">new</span> <span class=\"token class-name\">Map</span><span class=\"token punctuation\">(</span><span class=\"token punctuation\">)</span>\n</code></pre>\n<p>Now, with all the necessary data structures in place, you can implement the algorithm.</p>\n<div class=\"flex flex-col gap-4\"><div class=\"rounded-3xl border border-zinc-200/10 bg-[#0E0E10] shadow-inner transition-all duration-500 ease-in-out\"><div class=\"z-10 h-full w-full rounded-3xl bg-[#0E0E10] px-4 transition-all duration-500 ease-in-out\"><button class=\"inline-flex items-center justify-center whitespace-nowrap text-sm font-medium ring-offset-background transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50 h-10 px-4 py-2 relative -top-6 right-2 float-right rounded-2xl text-white bg-teal-600 hover:bg-teal-500\"><svg xmlns=\"http://www.w3.org/2000/svg\" width=\"24\" height=\"24\" viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"currentColor\" stroke-width=\"2\" stroke-linecap=\"round\" stroke-linejoin=\"round\" class=\"lucide lucide-rocket w-4 h-4 mr-3\"><path d=\"M4.5 16.5c-1.5 1.26-2 5-2 5s3.74-.5 5-2c.71-.84.7-2.13-.09-2.91a2.18 2.18 0 0 0-2.91-.09z\"></path><path d=\"m12 15-3-3a22 22 0 0 1 2-3.95A12.88 12.88 0 0 1 22 2c0 2.72-.78 7.5-6 11a22.35 22.35 0 0 1-4 2z\"></path><path d=\"M9 12H4s.55-3.03 2-4c1.62-1.08 5 0 5 0\"></path><path d=\"M12 15v5s3.03-.55 4-2c1.08-1.62 0-5 0-5\"></path></svg>Run code</button></div></div></div>\n<h2>Conclusion</h2>\n<p>Diagramming the quickest route on Google Maps no longer feels like a giant enigma. In summary, Dijkstra&#x27;s algorithm aids in navigating a weighted graph efficiently by finding the path with the least total weight. Remember, weighted graphs are your friend when you&#x27;re trying to find the shortest route in terms of weight or cost, not necessarily the number of segments!</p>\n<p>Have any more doubts about Dijkstra&#x27;s Algorithm, weighted graphs, or any other algorithm? Feel free to reach out. You can also subscribe to my newsletter for updates about my latest articles and guides. Happy coding!</p>",
            "url": "https://jopcmelo.dev/articles/dijkstras-algorithms",
            "title": "Understanding Weighted Graphs: Dijkstra's Algorithm Revealed",
            "summary": "In this guide for developers, we delve into an understanding of weighted graphs and Dijkstra's Algorithm, a popular method for finding the shortest paths in such structures. Master your graph-based problems with this in-depth walkthrough.",
            "date_modified": "2024-05-05T00:00:00.000Z",
            "author": {
                "name": "João Melo"
            }
        },
        {
            "id": "https://jopcmelo.dev/articles/introduction-to-graphs",
            "content_html": "<p>In the world of software engineering, finding the most efficient path between two points is a common challenge, one that can take many forms. Whether it&#x27;s an AI algorithm strategizing the fewest moves to victory in a game of checkers, a spell-checker computing the minimum number of edits to convert a misspelled word into a correct one, or locating the nearest in-network doctor, the underlying issue is the same. This is where the concept of the shortest path, or the <em>minimum path problem</em>, comes into play.</p>\n<p>Let&#x27;s bring this into a real-world example. Imagine you&#x27;re in San Francisco, looking to travel from Twin Peaks to the Golden Gate Bridge. You plan to take the bus, aiming to minimize the number of transfers. What algorithm could you use to find the route with the fewest steps?</p>\n<img alt=\"Bus Line Example as a Graph\" fetchpriority=\"high\" width=\"1095\" height=\"600\" decoding=\"async\" data-nimg=\"1\" style=\"color:transparent\" srcSet=\"/_next/image?url=%2F_next%2Fstatic%2Fmedia%2Fbus-example.2bc42c19.png&amp;w=1200&amp;q=75 1x, /_next/image?url=%2F_next%2Fstatic%2Fmedia%2Fbus-example.2bc42c19.png&amp;w=3840&amp;q=75 2x\" src=\"/_next/image?url=%2F_next%2Fstatic%2Fmedia%2Fbus-example.2bc42c19.png&amp;w=3840&amp;q=75\"/>\n<p>You&#x27;d start by considering whether it&#x27;s possible to reach your destination in one step. Here are all the locations you can get to in a single step:</p>\n<img alt=\"Single step result\" fetchpriority=\"high\" width=\"1095\" height=\"600\" decoding=\"async\" data-nimg=\"1\" style=\"color:transparent\" srcSet=\"/_next/image?url=%2F_next%2Fstatic%2Fmedia%2Fone-step-only.f5ec3eb6.png&amp;w=1200&amp;q=75 1x, /_next/image?url=%2F_next%2Fstatic%2Fmedia%2Fone-step-only.f5ec3eb6.png&amp;w=3840&amp;q=75 2x\" src=\"/_next/image?url=%2F_next%2Fstatic%2Fmedia%2Fone-step-only.f5ec3eb6.png&amp;w=3840&amp;q=75\"/>\n<p>The bridge isn&#x27;t reachable in one step, so what about two steps?</p>\n<img alt=\"Two steps result\" loading=\"lazy\" width=\"1095\" height=\"600\" decoding=\"async\" data-nimg=\"1\" style=\"color:transparent\" srcSet=\"/_next/image?url=%2F_next%2Fstatic%2Fmedia%2Ftwo-steps-only.ece9590f.png&amp;w=1200&amp;q=75 1x, /_next/image?url=%2F_next%2Fstatic%2Fmedia%2Ftwo-steps-only.ece9590f.png&amp;w=3840&amp;q=75 2x\" src=\"/_next/image?url=%2F_next%2Fstatic%2Fmedia%2Ftwo-steps-only.ece9590f.png&amp;w=3840&amp;q=75\"/>\n<p>Once again, the bridge eludes us. But what happens at three steps?</p>\n<img alt=\"Three steps result\" loading=\"lazy\" width=\"1095\" height=\"600\" decoding=\"async\" data-nimg=\"1\" style=\"color:transparent\" srcSet=\"/_next/image?url=%2F_next%2Fstatic%2Fmedia%2Fthree-steps-only.a6ad0b42.png&amp;w=1200&amp;q=75 1x, /_next/image?url=%2F_next%2Fstatic%2Fmedia%2Fthree-steps-only.a6ad0b42.png&amp;w=3840&amp;q=75 2x\" src=\"/_next/image?url=%2F_next%2Fstatic%2Fmedia%2Fthree-steps-only.a6ad0b42.png&amp;w=3840&amp;q=75\"/>\n<p>Aha! Now the bridge is highlighted in red, indicating that it&#x27;s possible to reach in three steps.</p>\n<img alt=\"Right path highlight\" loading=\"lazy\" width=\"1095\" height=\"600\" decoding=\"async\" data-nimg=\"1\" style=\"color:transparent\" srcSet=\"/_next/image?url=%2F_next%2Fstatic%2Fmedia%2Fright-path.9da52882.png&amp;w=1200&amp;q=75 1x, /_next/image?url=%2F_next%2Fstatic%2Fmedia%2Fright-path.9da52882.png&amp;w=3840&amp;q=75 2x\" src=\"/_next/image?url=%2F_next%2Fstatic%2Fmedia%2Fright-path.9da52882.png&amp;w=3840&amp;q=75\"/>\n<p>There may be other routes to the bridge, but they&#x27;re longer. The algorithm has determined that the shortest path to the bridge requires three steps. This type of problem is solved by an algorithm called Breadth-First Search (BFS), which systematically explores the graph to find the shortest path between two points.</p>\n<p>To understand how to go from Twin Peaks to the Golden Gate Bridge using BFS, we need to:</p>\n<ol>\n<li>Model the problem using graphs.</li>\n<li>Solve the problem using Breadth-First Search.</li>\n</ol>\n<p>Let&#x27;s delve into what graphs are and how BFS can help us find the shortest path.</p>\n<h2>What is a Graph?</h2>\n<p>A graph is a set of connections. It&#x27;s a powerful model used to represent and solve problems involving networks of points, which in graph terminology are called nodes or vertices, connected by lines known as edges.</p>\n<p>For example, consider a scenario where you and your friends are playing poker, and you want to keep track of who owes money to whom. You might say, &quot;João owes money to Juan&quot;.</p>\n<img alt=\"A relationship representation between João and Juan in a graph\" loading=\"lazy\" width=\"432\" height=\"204\" decoding=\"async\" data-nimg=\"1\" style=\"color:transparent\" srcSet=\"/_next/image?url=%2F_next%2Fstatic%2Fmedia%2Fjoao-juan.7bcf1fd9.png&amp;w=640&amp;q=75 1x, /_next/image?url=%2F_next%2Fstatic%2Fmedia%2Fjoao-juan.7bcf1fd9.png&amp;w=1080&amp;q=75 2x\" src=\"/_next/image?url=%2F_next%2Fstatic%2Fmedia%2Fjoao-juan.7bcf1fd9.png&amp;w=1080&amp;q=75\"/>\n<p>A graph consists of vertices (like João and Juan) and edges (the relationship that represents who owes money to whom).</p>\n<img alt=\"Vertex and edges\" loading=\"lazy\" width=\"432\" height=\"204\" decoding=\"async\" data-nimg=\"1\" style=\"color:transparent\" srcSet=\"/_next/image?url=%2F_next%2Fstatic%2Fmedia%2Fvertex-edges.e9134344.png&amp;w=640&amp;q=75 1x, /_next/image?url=%2F_next%2Fstatic%2Fmedia%2Fvertex-edges.e9134344.png&amp;w=1080&amp;q=75 2x\" src=\"/_next/image?url=%2F_next%2Fstatic%2Fmedia%2Fvertex-edges.e9134344.png&amp;w=1080&amp;q=75\"/>\n<p>That&#x27;s essentially it—a graph is simply a collection of vertices connected by edges. A vertex can be directly connected to many other vertices, which are referred to as its neighbors. Graphs provide a way to model how different events, people, or points are interconnected.</p>\n<p>With this understanding of graphs, we can now explore how to navigate these connections to find the shortest paths using Breadth-First Search.</p>\n<h2>Breadth-First Search (BFS)</h2>\n<p>In a previous article, we discussed <a href=\"https://www.jopcmelo.dev/articles/binary-search\">binary search</a>, an efficient algorithm for finding an item in a sorted array. Breadth-First Search (BFS) is another kind of algorithm entirely, one that leverages graphs to answer questions such as:</p>\n<ol>\n<li>Is there a path from vertex A to vertex B?</li>\n<li>What is the shortest path from vertex A to vertex B?</li>\n</ol>\n<p>BFS operates on the principle of exploring the closest, or neighboring, vertices first before moving on to more distant ones. This approach ensures that if a path exists, it will be found as efficiently as possible. Let&#x27;s understand BFS with an example involving a practical scenario.</p>\n<p>Imagine you own a mango farm and are looking for a mango seller who can market your harvest. You might start by asking, &quot;Do I know any mango sellers on Facebook?&quot; This search process is quite straightforward. First, make a list of friends to search through.</p>\n<pre><code>1. Juan\n2. Diogo\n3. Erick\n4. ...\n</code></pre>\n<p>For each friend, you check if they sell mangas:</p>\n<ol>\n<li>Does Juan sell mangas? If yes, great! If not, next.</li>\n<li>Does Diogo sell mangas? If yes, great! If not, next.</li>\n<li>Does Erick sell mangas? If yes, great! If not, next.</li>\n<li>...</li>\n</ol>\n<p>Suppose none of your immediate friends are mango sellers. You would then need to look at your friends&#x27; friends.</p>\n<img alt=\"Mangoes sellers graph\" loading=\"lazy\" width=\"1031\" height=\"683\" decoding=\"async\" data-nimg=\"1\" style=\"color:transparent\" srcSet=\"/_next/image?url=%2F_next%2Fstatic%2Fmedia%2Fmangoes-sellers.0fbce412.png&amp;w=1080&amp;q=75 1x, /_next/image?url=%2F_next%2Fstatic%2Fmedia%2Fmangoes-sellers.0fbce412.png&amp;w=3840&amp;q=75 2x\" src=\"/_next/image?url=%2F_next%2Fstatic%2Fmedia%2Fmangoes-sellers.0fbce412.png&amp;w=3840&amp;q=75\"/>\n<p>As you search each person on your list, if they aren&#x27;t mango sellers, you add all their friends to your search list. This way, you&#x27;re not only searching among your friends but also among their friends, and so on. This creates a search pattern that expands outwards, ensuring that you cover your entire network until you find a mango seller. This is Breadth-First Search at work.</p>\n<h2>Finding the Shortest Path</h2>\n<p>We&#x27;ve seen how to determine if a path exists between two vertices using BFS. Now, let&#x27;s figure out how to find the shortest path between them. Can you find the closest mango seller? For instance, your direct friends are first-degree connections, while friends of friends are second-degree connections. Naturally, you&#x27;d prefer a first-degree connection over a second-degree one and so on.</p>\n<p>It&#x27;s vital not to search through second-degree connections until you&#x27;re sure there are no first-degree connections who are mango sellers. The way BFS works, it spreads out from the starting point, ensuring that you check all first-degree connections before moving on to second-degree ones. By following the order of the list—first-degree, then second-degree connections, and so on—you&#x27;re guaranteed to find the closest mango seller. BFS doesn&#x27;t just find any path; it finds the shortest path. This is only effective if you maintain the order in which connections are added to the list, adhering to their degree of separation.</p>\n<p>In the subsequent section, we&#x27;ll discuss the role of queues in BFS and how they help maintain the order necessary to ensure the shortest path is found.</p>\n<h2>Queues</h2>\n<p>When dealing with the mechanics of the Breadth-First Search algorithm, the data structure that comes into play is the queue. A queue operates much like the queues we&#x27;re familiar with in everyday life—think of a line of people waiting to buy tickets at a movie theater.</p>\n<p>In computer science, a queue is a collection where elements are added to the back and removed from the front, adhering to a First-In-First-Out (FIFO) policy. Imagine a lineup of people: the first person to join the line is the first person to be served and leave the line.</p>\n<p>The operations that can be performed on a queue are &#x27;enqueue&#x27;, which adds an element to the end of the queue, and &#x27;dequeue&#x27;, which removes an element from the front. If you enqueue two items, the first item will be dequeued before the second—just as in a real-world queue.</p>\n<pre><code>enqueue(item1) -&gt; item1 is now at the back of the queue\nenqueue(item2) -&gt; item2 is placed behind item1\ndequeue() -&gt; item1 is removed from the front of the queue\n</code></pre>\n<p>This behavior is pivotal for the BFS algorithm as it ensures that vertices are explored in the order they were discovered. As you come across new vertices during your search, you enqueue them. When it&#x27;s time to explore a vertex, you dequeue, ensuring you&#x27;re always checking the oldest unexplored vertex first, which maintains the breadth-first nature of the search.</p>\n<p>Contrast this with a stack, a Last-In-First-Out (LIFO) structure where the last element added is the first to be removed, which is used in another type of graph traversal called Depth-First Search. The choice between using a queue or a stack is what distinguishes BFS from DFS, with each serving different types of problems and goals in graph exploration.</p>\n<p>In summary, queues in BFS allow the algorithm to keep track of which vertices to explore next and ensure that the search is conducted level by level, starting from the source vertex and moving outward, thereby guaranteeing the shortest path is found in an unweighted graph.</p>\n<h2>Implementing a Graph</h2>\n<p>In the realm of programming, the first step towards solving graph-related problems is to implement a graph in code. A graph comprises nodes, also known as vertices, which are interconnected through edges.</p>\n<p>To represent a relationship like &quot;you → Bob&quot;, a helpful data structure is a <a href=\"https://www.jopcmelo.dev/articles/hash-tables\">hash table</a>.</p>\n<p>Here&#x27;s a simple representation of a graph in JavaScript:</p>\n<pre class=\"language-javascript\"><code class=\"language-javascript\"><span class=\"token keyword\">const</span> graph <span class=\"token operator\">=</span> <span class=\"token punctuation\">{</span><span class=\"token punctuation\">}</span>\ngraph<span class=\"token punctuation\">[</span><span class=\"token string\">&#x27;you&#x27;</span><span class=\"token punctuation\">]</span> <span class=\"token operator\">=</span> <span class=\"token punctuation\">[</span><span class=\"token string\">&#x27;alice&#x27;</span><span class=\"token punctuation\">,</span> <span class=\"token string\">&#x27;bob&#x27;</span><span class=\"token punctuation\">,</span> <span class=\"token string\">&#x27;claire&#x27;</span><span class=\"token punctuation\">]</span>\n</code></pre>\n<p>In this graph, &quot;you&quot; is mapped to an array that contains all your neighbors. But what if we want to extend this graph to include more nodes and connections?</p>\n<pre class=\"language-javascript\"><code class=\"language-javascript\"><span class=\"token keyword\">const</span> graph <span class=\"token operator\">=</span> <span class=\"token punctuation\">{</span><span class=\"token punctuation\">}</span>\ngraph<span class=\"token punctuation\">[</span><span class=\"token string\">&#x27;you&#x27;</span><span class=\"token punctuation\">]</span> <span class=\"token operator\">=</span> <span class=\"token punctuation\">[</span><span class=\"token string\">&#x27;alice&#x27;</span><span class=\"token punctuation\">,</span> <span class=\"token string\">&#x27;bob&#x27;</span><span class=\"token punctuation\">,</span> <span class=\"token string\">&#x27;claire&#x27;</span><span class=\"token punctuation\">]</span>\ngraph<span class=\"token punctuation\">[</span><span class=\"token string\">&#x27;bob&#x27;</span><span class=\"token punctuation\">]</span> <span class=\"token operator\">=</span> <span class=\"token punctuation\">[</span><span class=\"token string\">&#x27;anuj&#x27;</span><span class=\"token punctuation\">,</span> <span class=\"token string\">&#x27;peggy&#x27;</span><span class=\"token punctuation\">]</span>\ngraph<span class=\"token punctuation\">[</span><span class=\"token string\">&#x27;alice&#x27;</span><span class=\"token punctuation\">]</span> <span class=\"token operator\">=</span> <span class=\"token punctuation\">[</span><span class=\"token string\">&#x27;peggy&#x27;</span><span class=\"token punctuation\">]</span>\ngraph<span class=\"token punctuation\">[</span><span class=\"token string\">&#x27;claire&#x27;</span><span class=\"token punctuation\">]</span> <span class=\"token operator\">=</span> <span class=\"token punctuation\">[</span><span class=\"token string\">&#x27;thom&#x27;</span><span class=\"token punctuation\">,</span> <span class=\"token string\">&#x27;jonny&#x27;</span><span class=\"token punctuation\">]</span>\ngraph<span class=\"token punctuation\">[</span><span class=\"token string\">&#x27;anuj&#x27;</span><span class=\"token punctuation\">]</span> <span class=\"token operator\">=</span> <span class=\"token punctuation\">[</span><span class=\"token punctuation\">]</span>\ngraph<span class=\"token punctuation\">[</span><span class=\"token string\">&#x27;peggy&#x27;</span><span class=\"token punctuation\">]</span> <span class=\"token operator\">=</span> <span class=\"token punctuation\">[</span><span class=\"token punctuation\">]</span>\ngraph<span class=\"token punctuation\">[</span><span class=\"token string\">&#x27;thom&#x27;</span><span class=\"token punctuation\">]</span> <span class=\"token operator\">=</span> <span class=\"token punctuation\">[</span><span class=\"token punctuation\">]</span>\ngraph<span class=\"token punctuation\">[</span><span class=\"token string\">&#x27;jonny&#x27;</span><span class=\"token punctuation\">]</span> <span class=\"token operator\">=</span> <span class=\"token punctuation\">[</span><span class=\"token punctuation\">]</span>\n</code></pre>\n<p>In this expanded graph, Anuj, Peggy, Thom, and Jonny don&#x27;t have any neighbors. They have edges pointing towards them, but no edges from them to others. This type of graph is called a <em>directed graph (or digraph)</em>, where the relationship holds true in only one direction.</p>\n<h2>Implementing the Algorithm</h2>\n<p>For a practical application of the Breadth-First Search algorithm, we&#x27;ll find a mango seller within our network. Here&#x27;s how we can achieve that:</p>\n<ol>\n<li>Create a queue containing all the people to be checked.</li>\n<li>Dequeue a person from the queue.</li>\n<li>Check if this person is a mango seller.</li>\n<li>If yes, you&#x27;ve found the mango seller.</li>\n<li>If not, add all their neighbors to the queue.</li>\n<li>Repeat steps 2-5.</li>\n<li>If the queue is empty, there are no mango sellers in your network.</li>\n</ol>\n<p>Here&#x27;s a JavaScript implementation of the above steps:</p>\n\n<h2>Time Complexity</h2>\n<p>The execution time of Breadth-First Search algorithm mainly involves checking every edge, implying a runtime of at least <code>O(E)</code>, where <code>E</code> is the number of edges. In addition, a queue of people is maintained to be checked, with each insertion operation consuming constant time, <code>O(1)</code>, leading to an overall time complexity of <code>O(V)</code> for all people, where <code>V</code> is the number of vertices.</p>\n<p>Therefore, the total execution time is <code>O(V + E)</code>, where <code>V</code> is the number of vertices (or nodes/people), and <code>E</code> is the number of edges (or connections). This efficient time complexity makes Breadth-First Search a useful choice for finding the shortest path in unweighted graphs.</p>\n<h2>Conclusion</h2>\n<p>Implementing and understanding graphs are key aspects of being a proficient software engineer. They are not only fundamental data structures, but their wide range of applications from social networks to geographical maps highlight their importance. The Breadth-First Search (BFS) that we covered in this article offers an efficient way to traverse or search a graph, commonly used for finding the shortest path in unweighted graphs. Remember its time complexity is <code>O(V+E)</code>, making it efficient for large scale applications.</p>\n<p>Though we used JavaScript in this example, knowledge of how to implement a graph and BFS algorithm transcends specific programming languages and is applicable across the board.</p>\n<p>Keep honing your algorithms and data structures skills, as they significantly enhance your problem-solving capabilities as a software engineer.</p>\n<p>For more articles on latest technologies and guides on mastering foundational concepts, subscribe to the newsletter below.</p>\n<p>Keep coding, and see you on the next one!\nimport  from &quot;react&quot;</p>",
            "url": "https://jopcmelo.dev/articles/introduction-to-graphs",
            "title": "Graphs Unveiled: Exploring Shortest Paths with Breadth-First Search",
            "summary": "Delve into the implementation of graphs, understand the Breadth-First Search (BFS) algorithm, its application and time complexity. A handy guide for software engineers.",
            "date_modified": "2024-02-25T00:00:00.000Z",
            "author": {
                "name": "João Melo"
            }
        },
        {
            "id": "https://jopcmelo.dev/articles/hash-tables",
            "content_html": "<p>Let&#x27;s take a journey into the world of a librarian. A reader wishes to read a particular book, say &quot;War and Peace&quot;. You, as the librarian, scour your list of available books to find its reference number.</p>\n<p>If the list isn&#x27;t alphabetically sorted, you could spend precious time going through every entry in an attempt to locate &quot;War and Peace&quot;. This method closely resembles a linear search, an algorithm whose performance stands at <code>O(n)</code>.</p>\n<p>You may consider keeping the list alphabetically organized and then using a <a href=\"https://www.jopcmelo.dev/articles/binary-search\">binary search</a> to find the book. This drill could cut the searching time to <code>O(log n)</code>, a significant improvement over the previous method.</p>\n<p>However, making a reader wait even for these few moments is hardly an ideal scenario. What if we could instantly recall the reference number of any book on demand? Such a system with <code>O(1)</code> runtime would significantly enhance the user experience while reducing the waiting time to virtually zero.</p>\n<p>To replicate this level of efficiency in our software projects, we turn to a powerful data structure - Hash Tables. This tool joins the line-up of <a href=\"https://www.jopcmelo.dev/articles/arrays-and-linked-lists\">array and linked list data structures</a>, providing a powerful tool to fast-track data retrieval within your applications.</p>\n<h2>The Mechanism of Hash Functions: Fueling Hash Tables</h2>\n<p>Hash Functions allow us to build this highly efficient system. They are unique functions that take a sequence of bytes (like a string), and return a number; in essence, they map strings to numbers. Yet, for hash functions to work effectively in a Hash Table, they must follow certain crucial rules:</p>\n<ol>\n<li><strong>Consistency</strong>: If you input the string &quot;War and Peace&quot; and it returns the number 4578, it must return the same output each time you input &quot;War and Peace&quot;. If it doesn&#x27;t, our Hash Table would become dysfunctional.</li>\n<li><strong>Unique Mappings</strong>: The function should map different words to different numbers. It&#x27;s not much use if the function returns the same number for different strings. Ideally, every unique string would map to a unique number.</li>\n<li><strong>Array-Friendliness</strong>: A Hash Function should know the size of your array, thus always ensuring it gives back valid indices.</li>\n</ol>\n<p>The operation of a hash function becomes clear when visualized in steps:</p>\n<ol>\n<li>We start with an empty array.</li>\n<li>We insert the word &quot;War and Peace&quot;.</li>\n<li>The hash function gives back the number 4578.</li>\n<li>We put the reference number of &quot;War and Peace&quot; at index 4578 in our array.</li>\n<li>Now, if we ask, &quot;What is the reference number for &#x27;War and Peace&#x27;?&quot;, the hash function will immediately return 4578.</li>\n<li>We proceed directly to array index 4578 to retrieve the book&#x27;s reference number in no time.</li>\n</ol>\n<p>Combine a hash function&#x27;s unique mapping with an array, and voila! You have a powerful new data structure in your hands: a Hash Table. Hash Tables, hence, owe their efficiency to the intricate workings of hash functions.</p>\n<h2>The Power of Hash Tables: Smart Data Storage</h2>\n<p>Hash Tables emerge as the first data structure that introduces a dose of logic in learning, marking a departure from the direct mapping to memory that we see in <a href=\"https://www.jopcmelo.dev/articles/arrays-and-linked-lists\">arrays and linked lists</a>. Hash Tables are indeed smarter and more efficient.</p>\n<p>How is that? They ingeniously leverage a hash function to decide precisely where to store elements. As a result, Hash Tables are among the most useful, albeit complex, data structures that you will learn.</p>\n<p>These clever constructs are often known as hash maps, maps, dictionaries, and dispersion tables, hinting at their extensive utilization. One of the key advantages of Hash Tables is their high speed and efficiency, which comes in handy in many applications.</p>\n<p>Importantly, you&#x27;ll seldom need to implement a Hash Table from scratch. Almost every programming language will have one pre-built for you. Here&#x27;s what a Hash Table looks like in JavaScript:</p>\n<pre class=\"language-javascript\"><code class=\"language-javascript\"><span class=\"token keyword\">const</span> hash <span class=\"token operator\">=</span> <span class=\"token punctuation\">{</span><span class=\"token punctuation\">}</span>\nhash<span class=\"token punctuation\">[</span><span class=\"token string\">&#x27;War and Peace&#x27;</span><span class=\"token punctuation\">]</span> <span class=\"token operator\">=</span> <span class=\"token number\">4578</span>\nhash<span class=\"token punctuation\">[</span><span class=\"token string\">&#x27;1984&#x27;</span><span class=\"token punctuation\">]</span> <span class=\"token operator\">=</span> <span class=\"token number\">1532</span>\n<span class=\"token console class-name\">console</span><span class=\"token punctuation\">.</span><span class=\"token method function property-access\">log</span><span class=\"token punctuation\">(</span>hash<span class=\"token punctuation\">[</span><span class=\"token string\">&#x27;War and Peace&#x27;</span><span class=\"token punctuation\">]</span><span class=\"token punctuation\">)</span> <span class=\"token comment\">// 4578</span>\n</code></pre>\n<p>Observe how each hash table contains a key (book title in this case) and a corresponding value (reference number). It&#x27;s their unique amalgamation within a Hash Table that paves the way for their on-demand and instant retrieval.</p>\n<h2>Real-world Applications of Hash Tables</h2>\n<p>Hash Tables are versatile and can be applied in various scenarios due to their effective data retrieval capabilities. Let&#x27;s delve into some practical applications.</p>\n<h3>Hash Tables for Lookup</h3>\n<p>Consider your school with various classrooms, each assigned a unique code. Suppose you want to create a system to map classroom codes to the teachers assigned to them. This system should:</p>\n<ol>\n<li>Add a teacher&#x27;s name and a classroom code</li>\n<li>Find the classroom code using a teacher&#x27;s name</li>\n</ol>\n<p>This scenario is the perfect use case for Hash Tables, which are ideal when mapping from one item to another or performing a lookup. Let&#x27;s use a Hash Table for this:</p>\n<pre class=\"language-javascript\"><code class=\"language-javascript\"><span class=\"token keyword\">const</span> classroomMap <span class=\"token operator\">=</span> <span class=\"token punctuation\">{</span><span class=\"token punctuation\">}</span>\n\n<span class=\"token comment\">// Add a teacher&#x27;s name and a classroom code</span>\nclassroomMap<span class=\"token punctuation\">[</span><span class=\"token string\">&#x27;Donald E. Knuth&#x27;</span><span class=\"token punctuation\">]</span> <span class=\"token operator\">=</span> <span class=\"token string\">&#x27;Room A123&#x27;</span>\nclassroomMap<span class=\"token punctuation\">[</span><span class=\"token string\">&#x27;Alan Kay&#x27;</span><span class=\"token punctuation\">]</span> <span class=\"token operator\">=</span> <span class=\"token string\">&#x27;Room B456&#x27;</span>\n\n<span class=\"token comment\">// Find the classroom code</span>\n<span class=\"token console class-name\">console</span><span class=\"token punctuation\">.</span><span class=\"token method function property-access\">log</span><span class=\"token punctuation\">(</span>classroomMap<span class=\"token punctuation\">[</span><span class=\"token string\">&#x27;Donald E. Knuth&#x27;</span><span class=\"token punctuation\">]</span><span class=\"token punctuation\">)</span> <span class=\"token comment\">// Room A123</span>\n</code></pre>\n<h3>Avoiding Duplicate Entries</h3>\n<p>Imagine you&#x27;re managing entries for an event where each guest may only enter once. How do you check if a guest has already entered? You could maintain a list of guests that have already entered and check their full name against it. But this method gets cumbersome when dealing with large crowds and extensive lists.</p>\n<p>Instead, we could utilize a Hash Table!</p>\n<pre class=\"language-javascript\"><code class=\"language-javascript\"><span class=\"token keyword\">const</span> enteredGuests <span class=\"token operator\">=</span> <span class=\"token punctuation\">{</span><span class=\"token punctuation\">}</span>\n\n<span class=\"token comment\">// Check if guest already entered</span>\n<span class=\"token keyword control-flow\">if</span> <span class=\"token punctuation\">(</span>enteredGuests<span class=\"token punctuation\">[</span><span class=\"token string\">&#x27;Erick Wendel&#x27;</span><span class=\"token punctuation\">]</span><span class=\"token punctuation\">)</span> <span class=\"token punctuation\">{</span>\n  <span class=\"token console class-name\">console</span><span class=\"token punctuation\">.</span><span class=\"token method function property-access\">log</span><span class=\"token punctuation\">(</span><span class=\"token string\">&#x27;Already entered!&#x27;</span><span class=\"token punctuation\">)</span>\n<span class=\"token punctuation\">}</span> <span class=\"token keyword control-flow\">else</span> <span class=\"token punctuation\">{</span>\n  enteredGuests<span class=\"token punctuation\">[</span><span class=\"token string\">&#x27;Erick Wendel&#x27;</span><span class=\"token punctuation\">]</span> <span class=\"token operator\">=</span> <span class=\"token boolean\">true</span>\n  <span class=\"token console class-name\">console</span><span class=\"token punctuation\">.</span><span class=\"token method function property-access\">log</span><span class=\"token punctuation\">(</span><span class=\"token string\">&#x27;Welcome!&#x27;</span><span class=\"token punctuation\">)</span>\n<span class=\"token punctuation\">}</span>\n</code></pre>\n<p>With this Hash Table, we can instantly check if a guest has already entered, saving precious time and computing resources.</p>\n<h3>Hash Tables as a Cache</h3>\n<p>Web developers often endorse caching as a best practice. When you visit websites like Amazon.com, the server may take a few seconds to gather all the featured deals and top-selling products. These few seconds can seem like an eternity to users who might perceive Amazon to be sluggish.</p>\n<p>Caching plays a crucial role here, acting like a memory bank that recalls data instead of recalculating it every time. When you revisit Amazon, the server checks if the home page is stored in its cache (which we can represent with a Hash Table). If it finds a cached version, it quickly serves out the webpage.</p>\n<p>This caching technique has two primary benefits:</p>\n<ol>\n<li>The webpage loads much faster, just like you could quickly answer the rainbow colors question after memorizing them.</li>\n<li>Amazon&#x27;s servers work less since they need not recreate the homepage every time a user visits.</li>\n</ol>\n<p>Here&#x27;s a simplified pseudo-code representation of such caching:</p>\n<pre class=\"language-javascript\"><code class=\"language-javascript\"><span class=\"token keyword\">let</span> cache <span class=\"token operator\">=</span> <span class=\"token punctuation\">{</span><span class=\"token punctuation\">}</span>\n\n<span class=\"token keyword\">async</span> <span class=\"token keyword\">function</span> <span class=\"token function\">getCachedPage</span><span class=\"token punctuation\">(</span><span class=\"token parameter\">url</span><span class=\"token punctuation\">)</span> <span class=\"token punctuation\">{</span>\n  <span class=\"token keyword control-flow\">if</span> <span class=\"token punctuation\">(</span>cache<span class=\"token punctuation\">[</span>url<span class=\"token punctuation\">]</span><span class=\"token punctuation\">)</span> <span class=\"token punctuation\">{</span>\n    <span class=\"token keyword control-flow\">return</span> cache<span class=\"token punctuation\">[</span>url<span class=\"token punctuation\">]</span>\n  <span class=\"token punctuation\">}</span> <span class=\"token keyword control-flow\">else</span> <span class=\"token punctuation\">{</span>\n    <span class=\"token keyword\">const</span> page <span class=\"token operator\">=</span> <span class=\"token keyword control-flow\">await</span> <span class=\"token function\">fetchFromServer</span><span class=\"token punctuation\">(</span>url<span class=\"token punctuation\">)</span>\n    cache<span class=\"token punctuation\">[</span>url<span class=\"token punctuation\">]</span> <span class=\"token operator\">=</span> page\n    <span class=\"token keyword control-flow\">return</span> page\n  <span class=\"token punctuation\">}</span>\n<span class=\"token punctuation\">}</span>\n</code></pre>\n<h2>Hash Collisions and Their Resolution</h2>\n<p>Hash collisions are a common challenge that programmers face when working with hash tables. So, what exactly is a hash collision, and how do we deal with it?</p>\n<p>Collisions happen when two keys map to the same slot in a hash table. Although hash functions aim to provide a unique mapping, achieving a perfect hash function, which guarantees that each key will map to a different slot, isn&#x27;t always feasible.</p>\n<p>Let us consider a scenario where we keep track of the population of American cities. Suppose we have an array with 50 slots, each corresponding to a U.S. state, and the hash function assigns each city to an array slot based on which state the city belongs to. All&#x27;s well initially. The population of Augusta (Maine) is stored in the first slot, and Annapolis (Maryland) goes into the second. But things get problematic when we try adding Auburn (Alabama). Our hash function maps it to the first slot, which is already holding Augusta&#x27;s data. Hence, a collision has occurred.</p>\n<p>This collision is problematic, as if we store Auburn&#x27;s population in this slot, it will overwrite Augusta&#x27;s population. So, when we want to retrieve Augusta&#x27;s population, the hash table will incorrectly give us Auburn&#x27;s population.</p>\n<p>One way to handle collisions is by using a <a href=\"https://www.jopcmelo.dev/articles/arrays-and-linked-lists\">linked list</a>. Whenever multiple keys map to the same slot, you simply start a linked list at that slot.</p>\n<p>This solution works fine if your linked list is relatively small. However, imagine having a linked list with thousands of city data entries. Searching through it would be considerably slow.</p>\n<p>From this, we learn two important lessons:</p>\n<ol>\n<li>The hash function is crucial as it needs to map keys as evenly as possible across all slots. In an ideal scenario, your hash function should distribute key-value pairs uniformly across the hash table.</li>\n<li>If your linked lists become too long due to collisions, they can drastically slow down the performance of your hash table. However, this can be mitigated by a good hash function which minimizes collisions.</li>\n</ol>\n<p>In short, preventing collisions is all about designing a robust hash function that mitigates the risk of collisions and ensures uniform key distribution.</p>\n<h2>Understanding Hash Table Performance</h2>\n<p>Among the various data structures available, hash tables are acclaimed for their excellent performance. To understand why, let&#x27;s delve into how their efficiency is quantified and how to ensure optimal performance.</p>\n<p>In terms of time efficiency, hash tables are exceptional. In the average case, all operations – search, insert, and delete – are executed in <code>O(1)</code> time. This is referred to as <em>constant time</em>. Constant time doesn&#x27;t mean the operation is instant, but rather that the time required remains the same regardless of the hash table&#x27;s size.</p>\n<p>However, the worst-case scenario tells a different story. If things go south, the time efficiency becomes <code>O(n)</code>, i.e., <a href=\"https://www.jopcmelo.dev/articles/big-o-notation\">linear time</a>, for all operations. This is much slower and usually due to collisions.</p>\n<p>Let&#x27;s look at a comparative analysis of hash tables, arrays, and linked lists:</p>\n<table><thead><tr><th></th><th>Hash tables (Average case)</th><th>Hash tables (Worst case)</th><th>Arrays</th><th>Linked lists</th></tr></thead><tbody><tr><td>Search</td><td><code>O(1)</code></td><td><code>O(n)</code></td><td><code>O(1)</code></td><td><code>O(n)</code></td></tr><tr><td>Insert</td><td><code>O(1)</code></td><td><code>O(n)</code></td><td><code>O(n)</code></td><td><code>O(1)</code></td></tr><tr><td>Delete</td><td><code>O(1)</code></td><td><code>O(n)</code></td><td><code>O(n)</code></td><td><code>O(1)</code></td></tr></tbody></table>\n<p>In the average case, hash tables excel by rivaling arrays in search time and linked lists in insert/delete times - it’s the best of both worlds. But the worst-case scenario reveals a direr performance. Therefore, it&#x27;s crucial to avoid worst-case scenarios by preventing collisions. How? Through a low load factor and a good hash function.</p>\n<h3>Load Factor</h3>\n<p>The <em>load factor</em> of a hash table indicates how filled the hash table is. It’s calculated as the number of items in the hash table divided by the total number of slots. For example, a load factor of 0.5 means that half of the hash table&#x27;s slots are filled, while a load factor of &gt;1 indicates overfilling.</p>\n<p>Managing the load factor is vital to the performance of the hash table. As the load factor rises, the likelihood of collisions increases, slowing down the hash table’s performance. <strong>A widely accepted threshold is to resize the hash table when the load factor exceeds 0.7.</strong></p>\n<h3>Resizing</h3>\n<p><em>Resizing</em> is the process of increasing the hash table&#x27;s capacity when its load factor breaches an upper limit. Essentially, you&#x27;re making more room for new entries and reducing the collision probability.</p>\n<p>To resize, start by doubling the existing array size. Then, you&#x27;ll have to rehash all the items using the hash function and insert them into this newly expanded hash table. With this increased capacity, the load factor drops, thereby decreasing chances for collisions and improving the performance of your hash table.</p>\n<h2>Conclusion</h2>\n<p>Understanding hash tables, collisions, and maintaining high performance are essential for every software engineer handling large datasets. Hash tables emerge as one of the most efficient data structures due to their constant time complexity across search, insert, and delete operations. However, their effectiveness significantly depends on minimizing collisions and appropriately maintaining the hash tables&#x27; load factor.</p>\n<p>Quality hash functions contribute to evenly distributing data across the table and reducing collisions, but they aren&#x27;t always sufficient. Once we encounter more collisions, and our load factor exceeds certain thresholds (0.7 is commonly used), it&#x27;s essential to resize our tables, creating a larger space for data and thereby reducing the probability of future collisions.</p>\n<p>While hash tables can&#x27;t always guarantee constant time complexity, with a carefully constructed hash function and an attentive eye on load factors, you can ensure you’re close to meeting that benchmark.</p>\n<p>In essence, hash tables are highly desirable for their speedy operation times, which are achievable under ideal conditions. Yet, understanding the potential for hash tables to operate at linear time efficiency is equally important. Hence, monitoring and optimizing the load factor are crucial practices in working with hash tables.</p>\n<p>If you enjoyed this deep-dive into hash tables and want to keep the ball rolling on your data structure journey, don&#x27;t forget to subscribe to my newsletter.</p>",
            "url": "https://jopcmelo.dev/articles/hash-tables",
            "title": "Mastering Hash Tables: From Understanding to Optimization",
            "summary": "A comprehensive look at hash tables and practical tips to optimize their utilization. Dive into hash functions, load factors, and trade-offs to learn how to get the best of hash tables.",
            "date_modified": "2023-11-28T00:00:00.000Z",
            "author": {
                "name": "João Melo"
            }
        },
        {
            "id": "https://jopcmelo.dev/articles/quicksort",
            "content_html": "<p>Quicksort, a renowned sorting algorithm boasting its high speed compared to <a href=\"https://www.jopcmelo.dev/articles/selection-sort\">selection sort</a>, frequently wins the hearts of programmers around the world. This article aims to illuminate its methodology and nuances using straightforward examples that delve into the handling of arrays with various lengths.</p>\n<h2>Gaining Familiarity: Simple Arrays</h2>\n<p>Straightforward as it may seem, a methodical understanding of quicksort begins with the most rudimentary array - an empty array or an array with a single element. In sorting such an array—voila—it&#x27;s already sorted! Thus, these cases form our base case.</p>\n<p>Moving on, let&#x27;s consider an array with two elements. The algorithm&#x27;s job is to ensure that the first element is smaller than the second. Otherwise, it flips them.</p>\n<h2>Applying Divide and Conquer Strategy</h2>\n<p>Things get trickier once we escalate to a three-element array. It&#x27;s important to remember that quicksort is a faithful practitioner of the <a href=\"https://www.jopcmelo.dev/articles/divide-and-conquer\"><em>Divide and Conquer</em> strategy</a>.</p>\n<p>The aim is to decompose the array until we reach our base case. Consequently, in quicksort, we assign an <em>anchor</em> role to one element of the array, called the <em>pivot</em>. For simplicity, initially, we elect the first item of the array as our pivot.</p>\n<p>This leads us to perform <em>partitioning</em>, where we identify elements smaller than the pivot and those greater. Post-partitioning, you&#x27;ll have:</p>\n<ul>\n<li>A subarray with elements inferior to the pivot</li>\n<li>The pivot</li>\n<li>A subarray with elements superior to the pivot</li>\n</ul>\n<p><strong>Do note that both these subarrays are partitioned but not sorted</strong>. How do we sort them then? Bob&#x27;s your uncle here, as our base case has already paved the way. Apply quicksort recursively to both subarrays and combine the results.</p>\n<h2>Tackling Larger Arrays</h2>\n<p>Once you&#x27;ve mastered sorting a three-element array, you can tackle an array with more elements using the same approach. Let&#x27;s consider a four-element array where we choose the largest number as the pivot. Consequently, one of the partitions will contain the remaining three elements, which we already know how to handle!</p>\n<p>Once you grasp this pattern, sorting larger arrays becomes a breeze. For an illustrative JavaScript implementation of Quicksort, visit our <a href=\"https://github.com/joaopcm/algorithms/blob/main/quicksort/index.js\">GitHub repository</a> or see the code snippet below.</p>\n<pre class=\"language-javascript\"><code class=\"language-javascript\"><span class=\"token keyword\">function</span> <span class=\"token function\">quicksort</span><span class=\"token punctuation\">(</span><span class=\"token parameter\">array</span><span class=\"token punctuation\">)</span> <span class=\"token punctuation\">{</span>\n  <span class=\"token keyword control-flow\">if</span> <span class=\"token punctuation\">(</span>array<span class=\"token punctuation\">.</span><span class=\"token property-access\">length</span> <span class=\"token operator\">&lt;</span> <span class=\"token number\">2</span><span class=\"token punctuation\">)</span> <span class=\"token punctuation\">{</span>\n    <span class=\"token keyword control-flow\">return</span> array\n  <span class=\"token punctuation\">}</span>\n\n  <span class=\"token keyword\">const</span> pivotIndex <span class=\"token operator\">=</span> <span class=\"token known-class-name class-name\">Math</span><span class=\"token punctuation\">.</span><span class=\"token method function property-access\">floor</span><span class=\"token punctuation\">(</span><span class=\"token known-class-name class-name\">Math</span><span class=\"token punctuation\">.</span><span class=\"token method function property-access\">random</span><span class=\"token punctuation\">(</span><span class=\"token punctuation\">)</span> <span class=\"token operator\">*</span> array<span class=\"token punctuation\">.</span><span class=\"token property-access\">length</span><span class=\"token punctuation\">)</span>\n  <span class=\"token keyword\">const</span> pivot <span class=\"token operator\">=</span> array<span class=\"token punctuation\">[</span>pivotIndex<span class=\"token punctuation\">]</span>\n  array<span class=\"token punctuation\">.</span><span class=\"token method function property-access\">splice</span><span class=\"token punctuation\">(</span>pivotIndex<span class=\"token punctuation\">,</span> <span class=\"token number\">1</span><span class=\"token punctuation\">)</span>\n\n  <span class=\"token keyword\">const</span> lower <span class=\"token operator\">=</span> array<span class=\"token punctuation\">.</span><span class=\"token method function property-access\">filter</span><span class=\"token punctuation\">(</span><span class=\"token punctuation\">(</span><span class=\"token parameter\">el</span><span class=\"token punctuation\">)</span> <span class=\"token arrow operator\">=&gt;</span> el <span class=\"token operator\">&lt;=</span> pivot<span class=\"token punctuation\">)</span>\n  <span class=\"token keyword\">const</span> higher <span class=\"token operator\">=</span> array<span class=\"token punctuation\">.</span><span class=\"token method function property-access\">filter</span><span class=\"token punctuation\">(</span><span class=\"token punctuation\">(</span><span class=\"token parameter\">el</span><span class=\"token punctuation\">)</span> <span class=\"token arrow operator\">=&gt;</span> el <span class=\"token operator\">&gt;</span> pivot<span class=\"token punctuation\">)</span>\n\n  <span class=\"token keyword control-flow\">return</span> <span class=\"token function\">quicksort</span><span class=\"token punctuation\">(</span>lower<span class=\"token punctuation\">)</span><span class=\"token punctuation\">.</span><span class=\"token method function property-access\">concat</span><span class=\"token punctuation\">(</span><span class=\"token punctuation\">[</span>pivot<span class=\"token punctuation\">]</span><span class=\"token punctuation\">,</span> <span class=\"token function\">quicksort</span><span class=\"token punctuation\">(</span>higher<span class=\"token punctuation\">)</span><span class=\"token punctuation\">)</span>\n<span class=\"token punctuation\">}</span>\n\n<span class=\"token console class-name\">console</span><span class=\"token punctuation\">.</span><span class=\"token method function property-access\">log</span><span class=\"token punctuation\">(</span><span class=\"token function\">quicksort</span><span class=\"token punctuation\">(</span><span class=\"token punctuation\">[</span><span class=\"token number\">10</span><span class=\"token punctuation\">,</span> <span class=\"token number\">5</span><span class=\"token punctuation\">,</span> <span class=\"token number\">2</span><span class=\"token punctuation\">,</span> <span class=\"token number\">3</span><span class=\"token punctuation\">]</span><span class=\"token punctuation\">)</span><span class=\"token punctuation\">)</span> <span class=\"token comment\">// [2, 3, 5, 10]</span>\n</code></pre>\n<h2>Importance of Pivot Choice</h2>\n<p>Selecting the pivot in Quicksort is not a trivial task. In fact, the pivot choice significantly influences the efficiency of the entire sorting process.</p>\n<p>To understand this, imagine a scenario where you always pick the first element as the pivot. Now consider what happens when quicksort is applied to an already sorted array. Interestingly, Quicksort does not have a mechanism to check if an array is pre-sorted, which means it proceeds to attempt sorting it anyway.</p>\n<p>The issue here is that the sorting process does not yield two balanced partitions due to the specific pivot choice (the first element). In other words, you are not truly dividing your problem into smaller, equal parts. What you get instead is an entirely empty subarray and another that has to absorb all the elements. This imbalance subsequently leads to excessive recursion, flooding the call stack, which induces performance inefficiencies.</p>\n<p>On the contrary, opting to choose the middle element as the pivot proffers more balanced partitions. The idea here is to distribute the sorting load more equally between two smaller subarrays. This approach effectively splits the problem into two approximately equal parts, minimizing the need for excessive recursive executions. Evidently, each separate sorting task is easier and quicker to handle, thereby contributing to a more efficient Quicksort process overall.</p>\n<p>In other words, a simple choice in pivot selection can drastically alter how the stack call is utilized, thereby potentially augmenting or hindering the efficiency of the sorting. Therefore, choosing a random element from the array as the pivot whenever Quicksort is used emerges as an efficient strategy to enhance the overall performance and limit the recursions.</p>\n<h2>Conclusion</h2>\n<p>Mastering quicksort requires understanding its base cases, implementation of the <em>Divide and Conquer</em> strategy, and the pivotal role of the pivot. Just like a well-sorted array, understanding these building blocks will empower you to sort any array, no matter its size.</p>\n<p>And remember, choice matters—especially when choosing the pivot!</p>\n<p>Did this article help you better understand quicksort? The journey doesn&#x27;t end here. Subscribe to my newsletter below and master more concepts!</p>",
            "url": "https://jopcmelo.dev/articles/quicksort",
            "title": "Mastering Quicksort: A comprehensive Guide for Developers",
            "summary": "Unravel the workings of the Quicksort algorithm, right from its application on simple arrays to handling larger ones. Discover how the 'Divide and Conquer' strategy plays out in Quicksort, and learn the underestimated significance of pivot choice in boosting efficiency.",
            "date_modified": "2023-11-26T00:00:00.000Z",
            "author": {
                "name": "João Melo"
            }
        },
        {
            "id": "https://jopcmelo.dev/articles/divide-and-conquer",
            "content_html": "<p>Have you ever faced a daunting task, like a jigsaw puzzle, and wondered where to start? Most of us would instinctively begin by sorting the pieces into small manageable groups, maybe by color or edge type. This illustrates a common problem-solving strategy, breaking a problem down into smaller parts to make it more manageable. In computer science, we use the same principle with a strategy known as &quot;Divide and Conquer&quot;. In this article, we dive into the fundamentals of &quot;Divide and Conquer&quot; and show how it can be applied with recursive algorithms, using real-world examples.</p>\n<img alt=\"Jigsaw Puzzle\" fetchpriority=\"high\" width=\"1024\" height=\"1024\" decoding=\"async\" data-nimg=\"1\" style=\"color:transparent\" srcSet=\"/_next/image?url=%2F_next%2Fstatic%2Fmedia%2Fjigsaw-puzzle.1bb23e68.png&amp;w=1080&amp;q=75 1x, /_next/image?url=%2F_next%2Fstatic%2Fmedia%2Fjigsaw-puzzle.1bb23e68.png&amp;w=2048&amp;q=75 2x\" src=\"/_next/image?url=%2F_next%2Fstatic%2Fmedia%2Fjigsaw-puzzle.1bb23e68.png&amp;w=2048&amp;q=75\"/>\n<h2>Unraveling Complexities with Divide and Conquer</h2>\n<p>&quot;Divide and Conquer&quot; is a popular problem-solving strategy in the field of computer science. It involves breaking down a complex problem into smaller subproblems. These subproblems are easier to solve, and their solutions can then be combined to address the original issue. Essentially, you&#x27;re turning a big, complex problem into a series of more manageable tasks.</p>\n<p>The key steps of the divide and conquer technique are:</p>\n<ol>\n<li><strong>Identify the base case</strong>: This is the simplest possible instance of the problem.</li>\n<li><strong>Divide or shrink your problem</strong>: With each iteration, you break down your problem until it matches the identified base case.</li>\n</ol>\n<p>This technique forms the cornerstone of recursive algorithms, an important computer science concept I discussed in a <a href=\"https://www.jopcmelo.dev/articles/recursion\">previous article</a>. Let&#x27;s start applying these principles to our first problem.</p>\n<h2>Real-world Example: Dividing a Farm into Equal Squares</h2>\n<p>To bring this concept to life, let&#x27;s consider a farmer who wishes to divide a plot of land, measuring 1680m by 640m, into equal square portions. The challenge here is to determine the maximum size of these square parcels.</p>\n<p>Following the Divide and Conquer approach, our first step is to identify the base case. For this scenario, a simple base case would be if one of the sides were a multiple of the other. For instance, if we had a 50m by 25m plot, we could easily divide it into two squares each measuring 25m by 25m.</p>\n<img alt=\"Farm plot\" loading=\"lazy\" width=\"1792\" height=\"1024\" decoding=\"async\" data-nimg=\"1\" style=\"color:transparent\" srcSet=\"/_next/image?url=%2F_next%2Fstatic%2Fmedia%2Ffarm.27f73162.png&amp;w=1920&amp;q=75 1x, /_next/image?url=%2F_next%2Fstatic%2Fmedia%2Ffarm.27f73162.png&amp;w=3840&amp;q=75 2x\" src=\"/_next/image?url=%2F_next%2Fstatic%2Fmedia%2Ffarm.27f73162.png&amp;w=3840&amp;q=75\"/>\n<p>Now on to the next step: dividing the original problem until we encounter our base case. This is the point where Divide and Conquer really shines. Starting with the vast land area, we first identify the largest square that fits: in this case, a 640m x 640m square. We fit as many of these squares as possible into our area of land and then look at what&#x27;s left over.</p>\n<p>Following this process, we find that two 640m x 640m squares can fit within our plot, leaving behind a 400m x 640m area. From this point, we now need to divide this residual area in the same approach as before, shrinking our problem at every turn. The largest square that could fit in this remaining area is 400m x 400m which leaves a 240m x 400m area undivided.</p>\n<p>Continuing this strategy, we fit in another square, this time 240m x 240m, leaving a 160m x 240m area. We then add a 160m square and are left with an area of 160m x 80m. At this point, we have reached our base case, as 160 is a multiple of 80. Dividing this last segment into squares leaves no segments unused. Therefore, for the original farmland, the largest square unit we can use to divide it into equal squares is 80m x 80m.</p>\n<h2>Putting it into Code: Summing Elements in an Array</h2>\n<p>This technique also has many practical applications in programming tasks. For instance, if you want to sum all the numbers in an array, you could easily execute this with a for loop:</p>\n<pre class=\"language-js\"><code class=\"language-js\"><span class=\"token keyword\">function</span> <span class=\"token function\">sum</span><span class=\"token punctuation\">(</span><span class=\"token parameter\">arr</span><span class=\"token punctuation\">)</span> <span class=\"token punctuation\">{</span>\n  <span class=\"token keyword\">let</span> total <span class=\"token operator\">=</span> <span class=\"token number\">0</span>\n  <span class=\"token keyword control-flow\">for</span> <span class=\"token punctuation\">(</span><span class=\"token keyword\">let</span> i <span class=\"token operator\">=</span> <span class=\"token number\">0</span><span class=\"token punctuation\">;</span> i <span class=\"token operator\">&lt;</span> arr<span class=\"token punctuation\">.</span><span class=\"token property-access\">length</span><span class=\"token punctuation\">;</span> i<span class=\"token operator\">++</span><span class=\"token punctuation\">)</span> <span class=\"token punctuation\">{</span>\n    total <span class=\"token operator\">+=</span> arr<span class=\"token punctuation\">[</span>i<span class=\"token punctuation\">]</span>\n  <span class=\"token punctuation\">}</span>\n  <span class=\"token keyword control-flow\">return</span> total\n<span class=\"token punctuation\">}</span>\n</code></pre>\n<p>However, this problem could also be solved recursively, using the Divide and Conquer technique. By defining our base case as an array with length 0 (or 1), we continuously reduce the size of the array with each recursive call until we reach the base case:</p>\n<pre class=\"language-js\"><code class=\"language-js\"><span class=\"token keyword\">function</span> <span class=\"token function\">sum</span><span class=\"token punctuation\">(</span><span class=\"token parameter\">arr</span><span class=\"token punctuation\">)</span> <span class=\"token punctuation\">{</span>\n  <span class=\"token keyword control-flow\">if</span> <span class=\"token punctuation\">(</span>arr<span class=\"token punctuation\">.</span><span class=\"token property-access\">length</span> <span class=\"token operator\">===</span> <span class=\"token number\">0</span><span class=\"token punctuation\">)</span> <span class=\"token punctuation\">{</span>\n    <span class=\"token comment\">// returns the base case</span>\n    <span class=\"token keyword control-flow\">return</span> <span class=\"token number\">0</span>\n  <span class=\"token punctuation\">}</span>\n  <span class=\"token keyword control-flow\">return</span> arr<span class=\"token punctuation\">[</span><span class=\"token number\">0</span><span class=\"token punctuation\">]</span> <span class=\"token operator\">+</span> <span class=\"token function\">sum</span><span class=\"token punctuation\">(</span>arr<span class=\"token punctuation\">.</span><span class=\"token method function property-access\">slice</span><span class=\"token punctuation\">(</span><span class=\"token number\">1</span><span class=\"token punctuation\">)</span><span class=\"token punctuation\">)</span> <span class=\"token comment\">// returns the sum of the first element and the sum of the rest of the array</span>\n<span class=\"token punctuation\">}</span>\n</code></pre>\n<p>Notice how the function reduces the problem size, brings it closer to the base case with each recursive call, and finally halts when it hits the base case. That is Divide and Conquer in action!</p>\n<h2>Further Practice: Dive Deeper with More Exercises</h2>\n<p>Further practice with the Divide and Conquer technique helps cement your understanding of recursive functions. Try your hand at the following exercises.</p>\n<h3>Recursive function to count the number of items in a list</h3>\n<pre class=\"language-js\"><code class=\"language-js\"><span class=\"token keyword\">function</span> <span class=\"token function\">count</span><span class=\"token punctuation\">(</span><span class=\"token parameter\">arr</span><span class=\"token punctuation\">)</span> <span class=\"token punctuation\">{</span>\n  <span class=\"token keyword control-flow\">if</span> <span class=\"token punctuation\">(</span>arr<span class=\"token punctuation\">.</span><span class=\"token property-access\">length</span> <span class=\"token operator\">===</span> <span class=\"token number\">0</span><span class=\"token punctuation\">)</span> <span class=\"token punctuation\">{</span>\n    <span class=\"token comment\">// returns the base case</span>\n    <span class=\"token keyword control-flow\">return</span> <span class=\"token number\">0</span>\n  <span class=\"token punctuation\">}</span>\n  <span class=\"token keyword control-flow\">return</span> <span class=\"token number\">1</span> <span class=\"token operator\">+</span> <span class=\"token function\">count</span><span class=\"token punctuation\">(</span>arr<span class=\"token punctuation\">.</span><span class=\"token method function property-access\">slice</span><span class=\"token punctuation\">(</span><span class=\"token number\">1</span><span class=\"token punctuation\">)</span><span class=\"token punctuation\">)</span> <span class=\"token comment\">// returns 1 plus the count of the rest of the array</span>\n<span class=\"token punctuation\">}</span>\n</code></pre>\n<h3>Recursive function to find the highest value in a list</h3>\n<pre class=\"language-js\"><code class=\"language-js\"><span class=\"token keyword\">function</span> <span class=\"token function\">max</span><span class=\"token punctuation\">(</span><span class=\"token parameter\">arr</span><span class=\"token punctuation\">)</span> <span class=\"token punctuation\">{</span>\n  <span class=\"token keyword control-flow\">if</span> <span class=\"token punctuation\">(</span>arr<span class=\"token punctuation\">.</span><span class=\"token property-access\">length</span> <span class=\"token operator\">===</span> <span class=\"token number\">1</span><span class=\"token punctuation\">)</span> <span class=\"token punctuation\">{</span>\n    <span class=\"token comment\">// returns the base case</span>\n    <span class=\"token keyword control-flow\">return</span> arr<span class=\"token punctuation\">[</span><span class=\"token number\">0</span><span class=\"token punctuation\">]</span>\n  <span class=\"token punctuation\">}</span>\n  <span class=\"token keyword control-flow\">return</span> <span class=\"token known-class-name class-name\">Math</span><span class=\"token punctuation\">.</span><span class=\"token method function property-access\">max</span><span class=\"token punctuation\">(</span>arr<span class=\"token punctuation\">[</span><span class=\"token number\">0</span><span class=\"token punctuation\">]</span><span class=\"token punctuation\">,</span> <span class=\"token function\">max</span><span class=\"token punctuation\">(</span>arr<span class=\"token punctuation\">.</span><span class=\"token method function property-access\">slice</span><span class=\"token punctuation\">(</span><span class=\"token number\">1</span><span class=\"token punctuation\">)</span><span class=\"token punctuation\">)</span><span class=\"token punctuation\">)</span> <span class=\"token comment\">// returns the highest value between the first element and the highest value of the rest of the array</span>\n<span class=\"token punctuation\">}</span>\n</code></pre>\n<h2>Wrapping Up: Achieving Mastery in Divide and Conquer Strategy</h2>\n<p>In summary, the Divide and Conquer strategy allows us to tackle complex problems by breaking them down into more manageable subproblems. This technique then employs recursion to systematically solve these problems. Whether you&#x27;re simplifying a land division problem or programming an array summing algorithm, this strategy greatly facilitates organized problem-solving.</p>\n<p>Most importantly, this technique forms the foundation of various efficient sorting algorithms such as Quick Sort and Merge Sort, demonstrating its versatility and its critical role in computer science. Now that you&#x27;ve learned the fundamentals of &quot;Divide and Conquer&quot; techniques and their implementation in recursive algorithms, take some time to practice and solidify your understanding.</p>\n<p>As with any skill, mastering these techniques comes with consistent practice. To guide your practice similar problems, I&#x27;ve included the code from this article and additional related examples in an open-source GitHub repository. Feel free to explore it at <a href=\"https://github.com/joaopcm/algorithms/tree/main/divide-and-conquer\">this link</a>.</p>\n<p><em>If you enjoyed this article and want even more great content like this, subscribe to my newsletter. Feel free to explore previous articles on recursion, selection sort, and other insightful subjects. Thanks for reading!</em></p>",
            "url": "https://jopcmelo.dev/articles/divide-and-conquer",
            "title": "Deconstructing Problems with \"Divide and Conquer\" Technique",
            "summary": "Unlock the power of \"Divide and Conquer\" strategy in problem-solving. Learn how to solve complex problems with simplicity using recursive algorithms. Master this fundamental tool of computer science, and apply it in real-world examples from farmland division to summing elements in an array.",
            "date_modified": "2023-11-10T00:00:00.000Z",
            "author": {
                "name": "João Melo"
            }
        },
        {
            "id": "https://jopcmelo.dev/articles/recursion",
            "content_html": "<p>Think about a Russian doll. You open the first doll to find a smaller doll inside, then another one in that, and this continues until you can&#x27;t find any more dolls. This real-world scenario exhibits recursion, where a big problem (finding the smallest doll) can be solved by dividing it into smaller, simpler problems of the same type.</p>\n<p>Recursion is pervasive in computer programming, enabling developers to tackle complex chaos with simple elegance. However, to some, it can appear daunting, or even unnecessary – when can&#x27;t I just use a loop? I aim to dispel this unease by lending you my understanding of recursion, built especially for software engineering, with all of its beauty, drawbacks and common applications.</p>\n<img alt=\"A Russian doll\" fetchpriority=\"high\" width=\"1024\" height=\"1024\" decoding=\"async\" data-nimg=\"1\" style=\"color:transparent\" srcSet=\"/_next/image?url=%2F_next%2Fstatic%2Fmedia%2Frussian-doll.6b72e123.png&amp;w=1080&amp;q=75 1x, /_next/image?url=%2F_next%2Fstatic%2Fmedia%2Frussian-doll.6b72e123.png&amp;w=2048&amp;q=75 2x\" src=\"/_next/image?url=%2F_next%2Fstatic%2Fmedia%2Frussian-doll.6b72e123.png&amp;w=2048&amp;q=75\"/>\n<h2>Spotting Recursion in everyday Scenarios</h2>\n<p>The suitcase conundrum: imagine you&#x27;re rummaging through your basement and stumble upon a mysterious, locked suitcase. You suspect the key is hiding in one of many boxes lying around, but these boxes can further contain smaller boxes. A recursive solution to finding the key looks like this:</p>\n<ol>\n<li>Examine box contents.</li>\n<li>If another box lurks inside, go to step 1.</li>\n<li>If you find the key, celebrate!</li>\n</ol>\n<p>On the other hand, you could set up a loop that throws all boxes on a pile, reviewing each until the key is found. While these strategies hit the same outcome, recursion undoubtedly adds an intuitive clarity to the answer&#x27;s pathway.</p>\n<p>Interestingly, this elegance does not translate into performance benefits. Sometimes, loops even have the upper hand when considering system resources.</p>\n<h2>Recursion Anatomy: Base Case and Recursive Case</h2>\n<p>A recursive function needs to know when to stop calling itself, ensuring we&#x27;re safe from a dreaded infinite loop. Therefore, every recursive function has two essential parts:</p>\n<ol>\n<li><strong>Base case</strong>: It defines the condition which stops the function from calling itself, thus avoiding an infinite loop.</li>\n<li><strong>Recursive case</strong>: It specifies the condition under which the function calls itself, hence the recursion.</li>\n</ol>\n<h2>Call Stack Unwrapped</h2>\n<p>The &#x27;stack&#x27; concept is integral to understanding recursion - and can be easily imagined by considering a pile of sticky notes. Each note could represent a task for, let&#x27;s say, an upcoming BBQ party. You add tasks on top of the stack (<code>push</code>), and you deal with them from the top too, reading and removing as you go (<code>pop</code>) – that&#x27;s a &#x27;Stack&#x27;.</p>\n<p>However, recursion deals with a specific version - &#x27;Call Stack&#x27;. Every time a function is activated, a new frame is pushed onto the Call Stack. This Stack keeps track of the function to return to post the current function&#x27;s completion. The concept extends to recursive functions, with every recursive call adding a new frame. The base case comes to rescue when all function calls have completed executing, popping frames off the Call Stack until it&#x27;s empty.</p>\n<p>Let&#x27;s dissect this on a classic example: factorial function.</p>\n<pre class=\"language-js\"><code class=\"language-js\"><span class=\"token keyword\">function</span> <span class=\"token function\">factorial</span><span class=\"token punctuation\">(</span><span class=\"token parameter\">x</span><span class=\"token punctuation\">)</span> <span class=\"token punctuation\">{</span>\n  <span class=\"token keyword control-flow\">if</span> <span class=\"token punctuation\">(</span>x <span class=\"token operator\">===</span> <span class=\"token number\">1</span><span class=\"token punctuation\">)</span> <span class=\"token keyword control-flow\">return</span> <span class=\"token number\">1</span>\n\n  <span class=\"token keyword control-flow\">return</span> x <span class=\"token operator\">*</span> <span class=\"token function\">factorial</span><span class=\"token punctuation\">(</span>x <span class=\"token operator\">-</span> <span class=\"token number\">1</span><span class=\"token punctuation\">)</span>\n<span class=\"token punctuation\">}</span>\n</code></pre>\n<p>The <code>factorial</code> function calls itself to find the product of a number and the factorial of the one before it. When <code>x</code> equals <code>1</code>, it stops the recursive calls, popping the frames and returning the computed value.</p>\n<p>While the Call Stack aids recursion, overusing it might lead to memory issues. If you&#x27;re saving numerous calls in memory (you&#x27;ve a very long stack), you could either rewrite your function to use loops instead of recursion or use tail recursion - a complex concept beyond the scope of this post, with limited support across programming languages.</p>\n<h2>More Meat on Recursion: Real-World Code Examples</h2>\n<h3>Diving into Directories</h3>\n<p>A practical example of recursion is counting the total number of files in a directory and its sub-directories.</p>\n<pre class=\"language-js\"><code class=\"language-js\"><span class=\"token keyword\">function</span> <span class=\"token function\">countFiles</span><span class=\"token punctuation\">(</span><span class=\"token parameter\">directory</span><span class=\"token punctuation\">)</span> <span class=\"token punctuation\">{</span>\n  <span class=\"token keyword\">let</span> count <span class=\"token operator\">=</span> directory<span class=\"token punctuation\">.</span><span class=\"token property-access\">files</span><span class=\"token punctuation\">.</span><span class=\"token property-access\">length</span>\n\n  <span class=\"token keyword control-flow\">for</span> <span class=\"token punctuation\">(</span><span class=\"token keyword\">const</span> subDirectory <span class=\"token keyword\">of</span> directory<span class=\"token punctuation\">.</span><span class=\"token property-access\">subDirectories</span><span class=\"token punctuation\">)</span> <span class=\"token punctuation\">{</span>\n    count <span class=\"token operator\">+=</span> <span class=\"token function\">countFiles</span><span class=\"token punctuation\">(</span>subDirectory<span class=\"token punctuation\">)</span>\n  <span class=\"token punctuation\">}</span>\n\n  <span class=\"token keyword control-flow\">return</span> count\n<span class=\"token punctuation\">}</span>\n</code></pre>\n<h3>Adventuring in Array Summation</h3>\n<p>Arriving at simpler problems, consider summing an array of numbers through recursion.</p>\n<pre class=\"language-js\"><code class=\"language-js\"><span class=\"token keyword\">function</span> <span class=\"token function\">sum</span><span class=\"token punctuation\">(</span><span class=\"token parameter\">array</span><span class=\"token punctuation\">)</span> <span class=\"token punctuation\">{</span>\n  <span class=\"token keyword control-flow\">if</span> <span class=\"token punctuation\">(</span>array<span class=\"token punctuation\">.</span><span class=\"token property-access\">length</span> <span class=\"token operator\">===</span> <span class=\"token number\">0</span><span class=\"token punctuation\">)</span> <span class=\"token keyword control-flow\">return</span> <span class=\"token number\">0</span>\n\n  <span class=\"token keyword control-flow\">return</span> array<span class=\"token punctuation\">[</span><span class=\"token number\">0</span><span class=\"token punctuation\">]</span> <span class=\"token operator\">+</span> <span class=\"token function\">sum</span><span class=\"token punctuation\">(</span>array<span class=\"token punctuation\">.</span><span class=\"token method function property-access\">slice</span><span class=\"token punctuation\">(</span><span class=\"token number\">1</span><span class=\"token punctuation\">)</span><span class=\"token punctuation\">)</span>\n<span class=\"token punctuation\">}</span>\n</code></pre>\n<h2>The Famed Fibonacci Sequence</h2>\n<p>Computing the Fibonacci series is a classic recursion job - each number equals the sum of the two preceding ones.</p>\n<pre class=\"language-js\"><code class=\"language-js\"><span class=\"token keyword\">function</span> <span class=\"token function\">fibonacci</span><span class=\"token punctuation\">(</span><span class=\"token parameter\">n</span><span class=\"token punctuation\">)</span> <span class=\"token punctuation\">{</span>\n  <span class=\"token keyword control-flow\">if</span> <span class=\"token punctuation\">(</span>n <span class=\"token operator\">&lt;=</span> <span class=\"token number\">2</span><span class=\"token punctuation\">)</span> <span class=\"token keyword control-flow\">return</span> <span class=\"token number\">1</span>\n\n  <span class=\"token keyword control-flow\">return</span> <span class=\"token function\">fibonacci</span><span class=\"token punctuation\">(</span>n <span class=\"token operator\">-</span> <span class=\"token number\">1</span><span class=\"token punctuation\">)</span> <span class=\"token operator\">+</span> <span class=\"token function\">fibonacci</span><span class=\"token punctuation\">(</span>n <span class=\"token operator\">-</span> <span class=\"token number\">2</span><span class=\"token punctuation\">)</span>\n<span class=\"token punctuation\">}</span>\n\n<span class=\"token console class-name\">console</span><span class=\"token punctuation\">.</span><span class=\"token method function property-access\">log</span><span class=\"token punctuation\">(</span><span class=\"token function\">fibonacci</span><span class=\"token punctuation\">(</span><span class=\"token number\">7</span><span class=\"token punctuation\">)</span><span class=\"token punctuation\">)</span> <span class=\"token comment\">// Output: 13</span>\n</code></pre>\n<h2>Wrapping Up</h2>\n<p>So we&#x27;ve deciphered recursion. Gaining comfort with recursion can take a little time. Breaking up complex problems into smaller, similar problems - over and over again until a solution surfaces should become more natural with practice. It&#x27;s a powerful tool that can effectively clear a lot of conceptual clutter, lend elegance to your solution and breed efficient code when used appropriately. So gear up for some recursive coding!</p>",
            "url": "https://jopcmelo.dev/articles/recursion",
            "title": "Recursion Revealed: An Intuitive Guide for Software Engineers",
            "summary": "Delve into the depths of recursion, an elegant and mighty concept in coding. With an array of real-life examples and code snippets, we'll unravel the 'mystery' of recursion, proving that it's not as daunting as it seems! Step in and immerse yourself into the world where problems solve themselves.",
            "date_modified": "2023-11-06T00:00:00.000Z",
            "author": {
                "name": "João Melo"
            }
        },
        {
            "id": "https://jopcmelo.dev/articles/selection-sort",
            "content_html": "<p>So you&#x27;ve dipped your toes with arrays and linked lists (<a href=\"https://www.jopcmelo.dev/articles/arrays-and-linked-lists\">here&#x27;s a link to the tutorial for a quick refresher</a>), and you&#x27;ve understood the Big O Notation (<a href=\"https://www.jopcmelo.dev/articles/big-o-notation\">check out the article if you haven&#x27;t yet</a>). It&#x27;s time to unpack the mechanics of the Selection Sort algorithm.</p>\n<img alt=\"Selection Sort algorithm in action\" fetchpriority=\"high\" width=\"1024\" height=\"1024\" decoding=\"async\" data-nimg=\"1\" style=\"color:transparent\" srcSet=\"/_next/image?url=%2F_next%2Fstatic%2Fmedia%2Fselection-sort.8110097d.png&amp;w=1080&amp;q=75 1x, /_next/image?url=%2F_next%2Fstatic%2Fmedia%2Fselection-sort.8110097d.png&amp;w=2048&amp;q=75 2x\" src=\"/_next/image?url=%2F_next%2Fstatic%2Fmedia%2Fselection-sort.8110097d.png&amp;w=2048&amp;q=75\"/>\n<p>Let&#x27;s imagine you have a list of artists based on their play-count on your computer:</p>\n<table><thead><tr><th>Artist</th><th>Plays count</th></tr></thead><tbody><tr><td>Van Halen</td><td>132</td></tr><tr><td>The Rolling Stones</td><td>353</td></tr><tr><td>Metallica</td><td>220</td></tr><tr><td>Nirvana</td><td>185</td></tr><tr><td>Aerosmith</td><td>157</td></tr><tr><td>Led Zeppelin</td><td>238</td></tr><tr><td>Red Hot Chili Peppers</td><td>201</td></tr></tbody></table>\n<p>You&#x27;d like to sort this list from high to low play-count to categorize your favorite artists. One way to do it would be to pull the most played artist from your list and add it to a new one, then repeat this process until everybody&#x27;s accounted for:</p>\n<table><thead><tr><th>Artist</th><th>Plays count</th></tr></thead><tbody><tr><td>The Rolling Stones</td><td>353</td></tr><tr><td>Led Zeppelin</td><td>238</td></tr><tr><td>Metallica</td><td>220</td></tr><tr><td>Red Hot Chili Peppers</td><td>201</td></tr><tr><td>Nirvana</td><td>185</td></tr><tr><td>Aerosmith</td><td>157</td></tr><tr><td>Van Halen</td><td>132</td></tr></tbody></table>\n<h2>Evaluating the Algorithm</h2>\n<p>To find the artist with the most plays, we check each item in the list, a process with run-time <code>O(n)</code>. To find the second most popular artist, you&#x27;ll again need to check the list item by item, again <code>O(n)</code>. As you see, when you want to find the next most popular artist, you run the same code <code>n</code> times. This makes the running time <code>O(n²)</code>.</p>\n<h2>What About Fewer Elements Each Time?</h2>\n<p>You&#x27;d be right to observe that as you proceed, the number of elements to examine shrinks, eventually leaving only a single element. So why the <code>O(n²)</code> complexity? The answer lies in the specifics of Big O Notation.</p>\n<p>You first check <code>n</code> elements, then <code>n - 1</code>, <code>n - 2</code>, and so forth, which averages out to checking <code>1/2 * n</code> elements. The running time becomes <code>O(n * 1/2 * n)</code>. However, in Big O Notation, we disregard constants like <code>1/2</code>, leaving us with <code>O(n * n)</code> or <code>O(n²)</code>.</p>\n<h2>Implementing the Algorithm</h2>\n<p>Although a good algorithm, the Selection Sort isn&#x27;t particularly fast. The <a href=\"https://jopcmelo.dev/articles/quicksort\">Quicksort</a>, for example, is faster with a complexity of <code>O(n log n)</code>— a topic for another post.</p>\n<p>Here&#x27;s a code snippet of how you&#x27;d sort an array of numbers using the selection sort algorithm in JavaScript:</p>\n<pre class=\"language-js\"><code class=\"language-js\"><span class=\"token keyword\">function</span> <span class=\"token function\">searchForSmallest</span><span class=\"token punctuation\">(</span><span class=\"token parameter\">arr</span><span class=\"token punctuation\">)</span> <span class=\"token punctuation\">{</span>\n  <span class=\"token keyword\">let</span> smallest <span class=\"token operator\">=</span> arr<span class=\"token punctuation\">[</span><span class=\"token number\">0</span><span class=\"token punctuation\">]</span>\n  <span class=\"token keyword\">let</span> smallestIndex <span class=\"token operator\">=</span> <span class=\"token number\">0</span>\n\n  <span class=\"token keyword control-flow\">for</span> <span class=\"token punctuation\">(</span><span class=\"token keyword\">let</span> i <span class=\"token operator\">=</span> <span class=\"token number\">0</span><span class=\"token punctuation\">;</span> i <span class=\"token operator\">&lt;</span> arr<span class=\"token punctuation\">.</span><span class=\"token property-access\">length</span><span class=\"token punctuation\">;</span> i<span class=\"token operator\">++</span><span class=\"token punctuation\">)</span> <span class=\"token punctuation\">{</span>\n    <span class=\"token keyword control-flow\">if</span> <span class=\"token punctuation\">(</span>arr<span class=\"token punctuation\">[</span>i<span class=\"token punctuation\">]</span> <span class=\"token operator\">&lt;</span> smallest<span class=\"token punctuation\">)</span> <span class=\"token punctuation\">{</span>\n      smallest <span class=\"token operator\">=</span> arr<span class=\"token punctuation\">[</span>i<span class=\"token punctuation\">]</span>\n      smallestIndex <span class=\"token operator\">=</span> i\n    <span class=\"token punctuation\">}</span>\n  <span class=\"token punctuation\">}</span>\n\n  <span class=\"token keyword control-flow\">return</span> smallestIndex\n<span class=\"token punctuation\">}</span>\n\n<span class=\"token keyword\">function</span> <span class=\"token function\">selectionSort</span><span class=\"token punctuation\">(</span><span class=\"token parameter\">arr</span><span class=\"token punctuation\">)</span> <span class=\"token punctuation\">{</span>\n  <span class=\"token keyword\">const</span> newArr <span class=\"token operator\">=</span> <span class=\"token punctuation\">[</span><span class=\"token punctuation\">]</span>\n\n  <span class=\"token keyword control-flow\">while</span> <span class=\"token punctuation\">(</span>arr<span class=\"token punctuation\">.</span><span class=\"token property-access\">length</span><span class=\"token punctuation\">)</span> <span class=\"token punctuation\">{</span>\n    <span class=\"token keyword\">const</span> smallestIndex <span class=\"token operator\">=</span> <span class=\"token function\">searchForSmallest</span><span class=\"token punctuation\">(</span>arr<span class=\"token punctuation\">)</span>\n    newArr<span class=\"token punctuation\">.</span><span class=\"token method function property-access\">push</span><span class=\"token punctuation\">(</span>arr<span class=\"token punctuation\">.</span><span class=\"token method function property-access\">splice</span><span class=\"token punctuation\">(</span>smallestIndex<span class=\"token punctuation\">,</span> <span class=\"token number\">1</span><span class=\"token punctuation\">)</span><span class=\"token punctuation\">[</span><span class=\"token number\">0</span><span class=\"token punctuation\">]</span><span class=\"token punctuation\">)</span>\n  <span class=\"token punctuation\">}</span>\n\n  <span class=\"token keyword control-flow\">return</span> newArr\n<span class=\"token punctuation\">}</span>\n\n<span class=\"token console class-name\">console</span><span class=\"token punctuation\">.</span><span class=\"token method function property-access\">log</span><span class=\"token punctuation\">(</span><span class=\"token function\">selectionSort</span><span class=\"token punctuation\">(</span><span class=\"token punctuation\">[</span><span class=\"token number\">5</span><span class=\"token punctuation\">,</span> <span class=\"token number\">3</span><span class=\"token punctuation\">,</span> <span class=\"token number\">6</span><span class=\"token punctuation\">,</span> <span class=\"token number\">2</span><span class=\"token punctuation\">,</span> <span class=\"token number\">10</span><span class=\"token punctuation\">]</span><span class=\"token punctuation\">)</span><span class=\"token punctuation\">)</span> <span class=\"token comment\">// [2, 3, 5, 6, 10]</span>\n</code></pre>\n<p>You can find this script in my GitHub algorithms repository <a href=\"https://github.com/joaopcm/algorithms/blob/main/selection-sort/index.js\">here</a>. A more visual and interactive dig into the algorithm is available in <a href=\"https://app.getnodepad.com/653e87dc49fad0c6f2cecd01\">this Nodepad note</a> I&#x27;ve prepared for you.</p>\n<h2>Conclusion</h2>\n<p>And there you have it, folks! The selection sort algorithm might not be the fastest, but it&#x27;s straightforward and a great starting point for understanding the mechanics of sorting algorithms. It thrives in simplicity, and its concept can be translated easily into real-world tasks.</p>\n<p>Remember, in programming (and in life), understanding the basics is key to tackling even the most complex problems. As you&#x27;ve ventured into Selection Sort, remember that this foundation will carry you forward in your journey towards comprehending more efficient algorithms.</p>\n<p>Keep your eyes on our future discussions about sorting algorithms like <a href=\"https://jopcmelo.dev/articles/quicksort\">Quicksort</a>, and let&#x27;s continue expanding our arsenal together!</p>\n<p>Don&#x27;t hesitate to revisit this piece anytime you need to refresh your Selection Sort knowledge. As always, happy coding!</p>",
            "url": "https://jopcmelo.dev/articles/selection-sort",
            "title": "Demystifying Sorting Algorithms: A Deep Dive into Selection Sort",
            "summary": "Break into the world of algorithms with an in-depth look at Selection Sort! With practical examples and easy-to-follow JavaScript code, this comprehensive guide will turn you into a sorting master. No fluff, just wisdom!",
            "date_modified": "2023-10-29T00:00:00.000Z",
            "author": {
                "name": "João Melo"
            }
        },
        {
            "id": "https://jopcmelo.dev/articles/arrays-and-linked-lists",
            "content_html": "<p>In the programming universe, two core data structures will frequently cross your path: arrays and linked lists. They have distinct characteristics, benefits, and cases where one might outshine the other. We&#x27;ve previously explored arrays when we delved into binary search. If you need a refresh, don&#x27;t hesitate to revisit our <a href=\"https://www.jopcmelo.dev/articles/binary-search\">binary search article</a>.</p>\n<p>Before we dive into arrays and linked lists, make sure you&#x27;re comfortable with Big O notation--it will greatly simplify the performance analysis in this tutorial. You can brush up on it <a href=\"https://www.jopcmelo.dev/articles/big-o-notation\">here</a>.</p>\n<h2>The Gym Locker Analogy: Computer Memory Explained</h2>\n<p>Think of computer memory as an expanse of gym lockers, each with its unique address. Want to store something? You get a locker. Need to store more? You&#x27;ll need more lockers.</p>\n<p>Similarly, when you save an item in computer memory, the computer assigns it an address. For multiple items, you&#x27;ll utilize arrays or linked lists.</p>\n<img alt=\"Explaining computer memory\" fetchpriority=\"high\" width=\"1024\" height=\"1024\" decoding=\"async\" data-nimg=\"1\" style=\"color:transparent\" srcSet=\"/_next/image?url=%2F_next%2Fstatic%2Fmedia%2Funderstanding-computer-memory.97f4c3dc.png&amp;w=1080&amp;q=75 1x, /_next/image?url=%2F_next%2Fstatic%2Fmedia%2Funderstanding-computer-memory.97f4c3dc.png&amp;w=2048&amp;q=75 2x\" src=\"/_next/image?url=%2F_next%2Fstatic%2Fmedia%2Funderstanding-computer-memory.97f4c3dc.png&amp;w=2048&amp;q=75\"/>\n<h2>Arrays vs. Linked Lists: Where to Store Your Groceries?</h2>\n<p>To illustrate, let’s suppose you&#x27;re building a grocery shopping app. Storing items requires either an array or a linked list. The former stores items side by side in memory.</p>\n<p>However, arrays can pose challenges. Suppose you need to add another item, but the next memory slot is occupied. You&#x27;ll need to find a larger memory region, move all items, and add the new one. Quite the hassle, right?</p>\n<p>A possible solution is to reserve more space than required, offering room for additions. But that approach wastes memory space if unused, and if the space fills up, you&#x27;re back at square one.</p>\n<h2>Linked Lists: The Treasure Hunt of Data Structures</h2>\n<p>Linked Lists offer a different approach. They allow your items to be located anywhere in memory, with each item pointing to the next one. Similar to a digital treasure hunt, you hop from one address to the next. This means you can add items anywhere in memory without relocating existing ones.</p>\n<img alt=\"Understanding linked lists\" loading=\"lazy\" width=\"1024\" height=\"1024\" decoding=\"async\" data-nimg=\"1\" style=\"color:transparent\" srcSet=\"/_next/image?url=%2F_next%2Fstatic%2Fmedia%2Flinked-lists.1dcaa07f.png&amp;w=1080&amp;q=75 1x, /_next/image?url=%2F_next%2Fstatic%2Fmedia%2Flinked-lists.1dcaa07f.png&amp;w=2048&amp;q=75 2x\" src=\"/_next/image?url=%2F_next%2Fstatic%2Fmedia%2Flinked-lists.1dcaa07f.png&amp;w=2048&amp;q=75\"/>\n<h2>Pitfall of Linked Lists and the Edge of Arrays</h2>\n<p>You know how &quot;top 10&quot; websites have a sneaky tactic for getting more views? Instead of displaying the full list on a single page, they place one item per page and make you click &quot;next&quot; to view the subsequent item. It&#x27;s annoying, but it earns them more from ad revenue.</p>\n<p>It would be considerably more user-friendly if the entire list were on one page, and you could click on each item&#x27;s name for more details.</p>\n<p>Linked lists have a similar pitfall. Suppose you want to read the last item of a linked list. You can&#x27;t do that directly as you don&#x27;t know its address. Instead, you have to go to item #1 to fetch the address for item #2, then move to item #2 to get the address for item #3, and so on until you reach the last item.</p>\n<p>Linked lists work perfectly fine if you want to read all items, one by one. However, if you want to jump from one item to another, linked lists score low on convenience.</p>\n<p>Arrays, on the other hand, operate differently. If you want to read the last item of an array, you can directly go to the address of the last item. No need to read all the items preceding it.</p>\n<p>In an array, elements are assigned an index. This indexing begins at 0, not 1. Take this array, for instance, the number 20 is at index 1.</p>\n<pre><code>[10, 20, 30, 40]\n</code></pre>\n<p>The number 10 is at index 0. This might confuse people initially, but that&#x27;s how it works.</p>\n<p>The position within an array is referred to as the index. The index of the number 20 is 1. The index of the number 10 is 0. The index of the number 40 is 3.</p>\n<p>Here&#x27;s how arrays and linked lists compare for common operations:</p>\n<table><thead><tr><th></th><th>Arrays</th><th>Linked Lists</th></tr></thead><tbody><tr><td>Reading</td><td><code>O(1)</code></td><td><code>O(n)</code></td></tr><tr><td>Insertion</td><td><code>O(n)</code></td><td><code>O(1)</code></td></tr></tbody></table>\n<h2>Inserting an Item in the Middle of the List</h2>\n<p>Imagine you want your grocery list to be alphabetically ordered. That means now, you&#x27;ll want to add items in the middle of the list - simply appending the item at the end of the list might violate the alphabetical order.</p>\n<p>What&#x27;s the better choice for inserting elements in the middle of a list: arrays or linked lists? Using linked lists, you just need to adjust what address the preceding item points to.</p>\n<p>For arrays, however, you must shift all the items below the insertion address. If there isn&#x27;t enough room, you&#x27;ll have to request more space and move every item over there.</p>\n<p>In essence, linked lists have the upper hand when it comes down to inserting items in the middle of the list.</p>\n<img alt=\"Grocery list\" loading=\"lazy\" width=\"1024\" height=\"1024\" decoding=\"async\" data-nimg=\"1\" style=\"color:transparent\" srcSet=\"/_next/image?url=%2F_next%2Fstatic%2Fmedia%2Fgrocery-list.5ef9bfbb.png&amp;w=1080&amp;q=75 1x, /_next/image?url=%2F_next%2Fstatic%2Fmedia%2Fgrocery-list.5ef9bfbb.png&amp;w=2048&amp;q=75 2x\" src=\"/_next/image?url=%2F_next%2Fstatic%2Fmedia%2Fgrocery-list.5ef9bfbb.png&amp;w=2048&amp;q=75\"/>\n<h2>Deletions</h2>\n<p>What if you want to delete an item? Once again, linked lists make this easier as you just need to adjust what address the preceding item points to.</p>\n<p>With arrays, everything needs to be shifted when an element gets eliminated. Unlike insertions, deleting elements will always be successful. Insertion may fail when there isn&#x27;t enough memory space.</p>\n<p>Here are the runtimes for the most common operations for arrays and linked lists:</p>\n<table><thead><tr><th></th><th>Arrays</th><th>Linked Lists</th></tr></thead><tbody><tr><td>Reading</td><td><code>O(1)</code></td><td><code>O(n)</code></td></tr><tr><td>Insertion</td><td><code>O(n)</code></td><td><code>O(1)</code></td></tr><tr><td>Deletion</td><td><code>O(n)</code></td><td><code>O(1)</code></td></tr></tbody></table>\n<h2>In Conclusion: Arrays vs Linked Lists?</h2>\n<p>Which one is more frequently used - arrays or linked lists? Clearly, it hinges on the scenario they&#x27;re used in. However, arrays are more commonplace since they allow random access. There are two types of access: <i>sequential</i> and <i>random</i>.</p>\n<p><i>Sequential</i> access means reading elements one by one, starting with the first.\nLinked lists can only manage sequential access. If you want to read the tenth element\nof a linked list, you first need to read the preceding nine elements to get the tenth\nelement&#x27;s address.</p>\n<p><i>Random</i> access, on the other hand, lets you jump straight to the tenth element.</p>\n<p><i>Random</i> access is much needed in many cases, leading to wider usage of arrays.\nArrays and linked lists are employed to build other data structures, such as queues,\nstacks, trees, and graphs.</p>",
            "url": "https://jopcmelo.dev/articles/arrays-and-linked-lists",
            "title": "Arrays vs Linked Lists: An In-depth Comparison and Understanding",
            "summary": "Dive into this comprehensive guide discussing arrays and linked lists: two basic data structure types. Explore their distinction in detail, performance analysis using Big O Notation, and how to leverage their strengths based on your specific application needs.",
            "date_modified": "2023-10-27T00:00:00.000Z",
            "author": {
                "name": "João Melo"
            }
        },
        {
            "id": "https://jopcmelo.dev/articles/big-o-notation",
            "content_html": "<h2>The Basics of Algorithmic Time Complexity</h2>\n<p>When writing or utilizing algorithms in real-life applications, we need to understand their performance characteristics - how fast or slow they can be. This is especially relevant when algorithms become part of specialized and critical systems like the code that determines the landing spot of a SpaceX rocket preparing to land on Mars.</p>\n<p>Think about a developer named Fred who is in charge of that code. He has to choose between two different algorithms - a <a href=\"https://www.jopcmelo.dev/articles/binary-search\">simple search or binary search</a>.</p>\n<p>Both algorithms serve the same purpose, but they grow at different rates. Binary search is faster, a desirable attribute given that Fred has merely 10 seconds to calculate the landing spot. On the other hand, implementing simple search is much easier, representing a lower risk of bugs - rather crucial because nobody wants a bug when landing a spaceship!</p>\n<img alt=\"Big O Notation\" fetchpriority=\"high\" width=\"1024\" height=\"1024\" decoding=\"async\" data-nimg=\"1\" style=\"color:transparent\" srcSet=\"/_next/image?url=%2F_next%2Fstatic%2Fmedia%2Fbig-o-notation.8e4cd26d.png&amp;w=1080&amp;q=75 1x, /_next/image?url=%2F_next%2Fstatic%2Fmedia%2Fbig-o-notation.8e4cd26d.png&amp;w=2048&amp;q=75 2x\" src=\"/_next/image?url=%2F_next%2Fstatic%2Fmedia%2Fbig-o-notation.8e4cd26d.png&amp;w=2048&amp;q=75\"/>\n<h2>The Importance of Time Complexity</h2>\n<p>To make a wise decision, Fred decides to measure both algorithms against a list of 100 elements. He assumes that each element that he searches in the list will take 1ms.</p>\n<p>The simple search algorithm will need 100ms (because it takes <code>O(n)</code> time, where <code>n</code> is the number of elements), while the binary search algorithm will only need 7ms (given its <code>O(log n)</code> time complexity). But what happens if the size of the list increases significantly? To put it into perspective, if the list had around 1 billion elements, the binary search would take ~30ms, while a simple search would take around 11 (yes, eleven) days.</p>\n<p>This hypothetical scenario showcases how the execution time of different algorithms can multiply at varying rates, demonstrating the importance of time complexity analysis. It&#x27;s not about only the time an algorithm takes, but how it scales with input size. And that&#x27;s where Big O Notation comes into play.</p>\n<table><thead><tr><th># of elements</th><th>Simple Search</th><th>Binary Search</th></tr></thead><tbody><tr><td>100</td><td>100ms</td><td>7ms</td></tr><tr><td>10,000</td><td>10 seconds</td><td>14ms</td></tr><tr><td>1,000,000,000</td><td>11 days</td><td>32ms</td></tr></tbody></table>\n<h2>Unpacking Big O Notation</h2>\n<p>Big O Notation is a mathematical notation that represents the upper bound - the worst-case scenario - in terms of time complexity for an algorithm. To take a few examples:</p>\n<ul>\n<li>Binary search has a time complexity of <code>O(log n)</code>, also known as <i>Logarithmic Time</i>.</li>\n<li>Simple search scales linearly, with a time complexity of <code>O(n)</code>, also known as <i>Linear Time</i>.</li>\n<li><a href=\"https://jopcmelo.dev/articles/quicksort\">Quicksort</a>, a fast sorting algorithm, has a time complexity of <code>O(n * log n)</code>.</li>\n<li><a href=\"https://www.jopcmelo.dev/articles/selection-sort\">Selection sort</a>, a slower sorting algorithm, scales as <code>O(n²)</code>, referred to as <i>Quadratic Time</i>.</li>\n<li>A notoriously slow algorithm is the solution to the Traveling Salesman Problem, which has a time complexity of <code>O(n!)</code>, or <i>Factorial Time</i>.</li>\n</ul>\n<p>Let&#x27;s dive deeper into the Traveling Salesman Problem, as it&#x27;s a famous example of an algorithm with frighteningly high time complexity.</p>\n<h2>An Overview of the Traveling Salesman Problem</h2>\n<p>The Traveling Salesman Problem is a combinational optimization problem. It concerns a salesman who needs to travel to multiple cities, visit each one just once, and return to the original point. The aim is to find the shortest possible route.</p>\n<img alt=\"Traveling Salesman problem\" loading=\"lazy\" width=\"1024\" height=\"1024\" decoding=\"async\" data-nimg=\"1\" style=\"color:transparent\" srcSet=\"/_next/image?url=%2F_next%2Fstatic%2Fmedia%2Ftraveling-salesman-problem.7d0d5d13.png&amp;w=1080&amp;q=75 1x, /_next/image?url=%2F_next%2Fstatic%2Fmedia%2Ftraveling-salesman-problem.7d0d5d13.png&amp;w=2048&amp;q=75 2x\" src=\"/_next/image?url=%2F_next%2Fstatic%2Fmedia%2Ftraveling-salesman-problem.7d0d5d13.png&amp;w=2048&amp;q=75\"/>\n<p>Here you can see how the growth of this algorithm scales factorially with the number of cities:</p>\n<table><thead><tr><th>Cities</th><th>Operations</th></tr></thead><tbody><tr><td>6</td><td>720</td></tr><tr><td>7</td><td>5,040</td></tr><tr><td>8</td><td>40,320</td></tr><tr><td>...</td><td>...</td></tr><tr><td>15</td><td>1,307,674,368,000</td></tr><tr><td>...</td><td>...</td></tr><tr><td>30</td><td>265,252,859,812,191,058,636,308,480,000,000</td></tr></tbody></table>\n<p>In summary, for <code>n</code> items, it takes <code>n!</code> (factorial of <code>n</code>) operations to reach a result. So, that&#x27;s <code>O(n!)</code> time complexity or <i>factorial time</i>.</p>\n<p>Time complexity analysis and Big O Notation are crucial for designing efficient algorithms and systems. Whether writing a function to sort a small list or coding rocket landing software, understanding how your program&#x27;s running time scales with the size of the input might make the difference between code that runs in milliseconds and code that runs for days.</p>\n<h2>Understanding Space Complexity</h2>\n<p>Space complexity is a term used in the study of algorithms to describe the amount of memory (space) an algorithm requires to execute. Understanding space complexity is as important as knowing time complexity, as it helps you consider the efficiency of your algorithm from a different angle.</p>\n<p>Often, a trade-off exists between time and space complexity. Sometimes, by using more space (i.e., storing pre-computed values), you can decrease the time complexity of your algorithm (i.e., by reusing these stored values instead of re-calculating them). This is commonly referred to as a space-time tradeoff.</p>\n<p>Let&#x27;s break this down through an example related to social networks. Suppose you construct an algorithm to find whether two users are friends.</p>\n<p>One approach would be to run through all connections of user A, and for each connection, check if it’s user B (simple linear search). This approach involves low space complexity (you&#x27;re not storing much extra data), but the time complexity is O(n), where n is the number of friends of user A.</p>\n<p>Another approach would be to utilize a data structure known as a hash set for storing all friends of user A. So, when you need to check if user B is a friend of A, you can look it up in the set directly. This way, the time complexity improves to O(1), but you&#x27;ve increased the space complexity because you store extra data in the hash set.</p>\n<h2>Big O Notation in Real-World Applications</h2>\n<p>In the real world, understanding Big O notation has a massive influence on how solutions are developed for large-scale systems. Here are a few examples:</p>\n<h3>Search Engines</h3>\n<p>In search engines like Google, data structures known as inverted indices are used to store and search for information. These indices use a sorted list of keywords, each associated with a list of documents (webpages) containing the keyword. Searching for web pages related to a keyword thus becomes a matter of searching for the keyword in the index – a task well-suited for binary search, which has a performance of O(log n). This is critical when dealing with the enormous number of keywords and web pages indexed by a search engine.</p>\n<h3>Streaming Services</h3>\n<p>Big O Notation plays a significant role in how services like Netflix make recommendations. They use algorithms that must be able to quickly analyze large amounts of data (i.e., previously watched movies, viewer ratings, and preferences) and make recommendations, requiring algorithms that scale well with an increase in data size. A poorly designed algorithm (with, say, quadratic time complexity) could lead to slow recommendations, negatively impacting user experience.</p>\n<h3>Database Query Optimization</h3>\n<p>Databases use various algorithms and data structures to store and retrieve data efficiently, and Big O notation describes the performance of these operations. For instance, efficient databases make use of B-Trees for indexing data due to its logarithmic time complexity which ensures that operations like insertion, deletion and search can be performed rapidly even on large datasets.</p>\n<h2>Last Word on Big O Notation</h2>\n<p>Understanding Big O notation ranks among the key steps in becoming a competent developer. Whether you&#x27;re writing simple code to sort a list, or working on complex, large-scale applications dealing with billions of data points, an awareness of time and space complexity helps you choose the right algorithms, data structures, and design decisions.</p>\n<p>Big O Notation provides a lens through which you can see potential bottlenecks in your programs and empower yourself to write code that runs efficiently, irrespective of your application&#x27;s scale. It helps you comprehend the trade-offs between time and space and optimize according to the specific needs of your project.</p>\n<p>In real-world applications ranging from search engines to streaming services and database design, we see the power of a grasp on Big O Notation: faster, more efficient systems that can handle increasing loads of data.</p>\n<p>Happy coding, and remember - the quest for efficiency is a developer&#x27;s journey with no end, just like the unending learning and growth we get to experience in this fascinating field.</p>\n<p>Until next time, keep exploring, keep coding, and most importantly, keep optimizing!</p>",
            "url": "https://jopcmelo.dev/articles/big-o-notation",
            "title": "Grasping Big O Notation: Your Algorithm's Speedometer",
            "summary": "Big O Notation is a special form of notation that helps us understand the performance characteristics of an algorithm - how fast the algorithm grows in terms of time complexity.",
            "date_modified": "2023-10-23T00:00:00.000Z",
            "author": {
                "name": "João Melo"
            }
        },
        {
            "id": "https://jopcmelo.dev/articles/binary-search",
            "content_html": "<h2>What is Binary Search?</h2>\n<p>Imagine you&#x27;re rummaging through a phonebook, looking for a name that begins with &quot;L&quot;. Most likely, you wouldn&#x27;t start from the first page and flip through each one until you reach &quot;L&quot;, right? A more plausible approach would be to open the phonebook around the middle and move to the left or right depending on where &quot;L&quot; lies.</p>\n<p>Similarly, when searching for a word that starts with &quot;P&quot; in a dictionary, you&#x27;d probably start from the middle and navigate left or right, depending on the first letter of the word you&#x27;re seeking.</p>\n<p>Welcome to the world of binary search.</p>\n<img alt=\"Binary Search algorithm representation\" fetchpriority=\"high\" width=\"1792\" height=\"1024\" decoding=\"async\" data-nimg=\"1\" style=\"color:transparent\" srcSet=\"/_next/image?url=%2F_next%2Fstatic%2Fmedia%2Fbinary-search-algorithm.1a798340.png&amp;w=1920&amp;q=75 1x, /_next/image?url=%2F_next%2Fstatic%2Fmedia%2Fbinary-search-algorithm.1a798340.png&amp;w=3840&amp;q=75 2x\" src=\"/_next/image?url=%2F_next%2Fstatic%2Fmedia%2Fbinary-search-algorithm.1a798340.png&amp;w=3840&amp;q=75\"/>\n<h2>Understanding Binary Search</h2>\n<p>At the core, binary search is an algorithm designed to sniff out an element&#x27;s location from a sorted list of elements. If the target element exists, the algorithm returns its location; if it doesn&#x27;t, it returns <code>None</code> (or <code>-1</code> in some programming languages).</p>\n<p>For instance, consider you&#x27;re seeking a number between 1 and 100. To guess, you must take the fewest possible attempts. Throughout the process, I&#x27;ll let you know if your guess is too high, too low, or right on the money.</p>\n<p>A straightforward approach (known as <strong>linear search</strong>) would be to take a shot in the dark, starting from 1, then 2, then 3, so on and so forth. If my number happens to be 99, you&#x27;d need 99 attempts to guess correctly. Would you consider that efficient? Probably not.</p>\n<p>However, if you kick off by guessing 50 (<strong>the middlemost value</strong>), I&#x27;d nudge you in the right direction – up or down. If my number is higher than 50, you can write off all numbers between 1 and 50 and look only between 51 and 100. And if it&#x27;s lower, you ditch numbers between 51 and 100, focusing only on 1 to 49. By continually halving possibilities, you home in on my number using the binary search algorithm.</p>\n<p>Here&#x27;s a glimpse of how many numbers binary search eliminates in each round: 50 -&gt; 25 -&gt; 13 -&gt; 7 -&gt; 4 -&gt; 2 -&gt; 1. In just 7 steps, you&#x27;d hit the jackpot.</p>\n<p>Now, apply this logic to a dictionary with 480,000 words. Binary search lets you find a word in, at most, 19 steps!</p>\n<p>Broadly speaking, a binary search needs <strong>log₂ n</strong> steps to return the correct value, whereas linear search requires <code>n</code> steps, where <code>n</code> corresponds to the list&#x27;s length.</p>\n<p>In case you feel a slight frown due to the term &#x27;logarithms&#x27;, here&#x27;s a refresher with an emphasis on how to compute exponentials. The expression <strong>log₁₀ 100</strong> asks: &quot;how many instances of 10 can we multiply to reach 100?&quot;. The answer is 2 because <code>10 * 10 = 100</code>. Therefore, log₁₀ 100 equals 2.</p>\n<p>Note, however, that binary search works only if your list is sorted. What would ensue if the dictionary were not arranged in alphabetical order?</p>\n<h2>Execution Time</h2>\n<p>Let&#x27;s go back to the linear search or a simple search where you check numbers sequentially. If you have a list of 100 numbers, worst-case scenario, you&#x27;d need 100 tries. For a list with 4 billion numbers, you&#x27;d need 4 billion attempts. <strong>The maximum tries are equivalent to the list&#x27;s length, known as linear time</strong>.</p>\n<p>Binary search differs. If your list has 100 items, you&#x27;d need at most 7 tries. If it contains 4 billion items, you need, at max, 32 tries. It&#x27;s a potent algorithm, isn&#x27;t it?</p>\n<h2>Implementation</h2>\n<p>Ready to see binary search in action? Here is a JavaScript implementation example to get you started:</p>\n<pre class=\"language-js\"><code class=\"language-js\"><span class=\"token keyword\">function</span> <span class=\"token function\">binarySearch</span><span class=\"token punctuation\">(</span><span class=\"token parameter\">nums<span class=\"token punctuation\">,</span> item</span><span class=\"token punctuation\">)</span> <span class=\"token punctuation\">{</span>\n  <span class=\"token keyword\">let</span> left <span class=\"token operator\">=</span> <span class=\"token number\">0</span>\n  <span class=\"token keyword\">let</span> right <span class=\"token operator\">=</span> nums<span class=\"token punctuation\">.</span><span class=\"token property-access\">length</span> <span class=\"token operator\">-</span> <span class=\"token number\">1</span>\n\n  <span class=\"token keyword control-flow\">do</span> <span class=\"token punctuation\">{</span>\n    <span class=\"token keyword\">let</span> mid <span class=\"token operator\">=</span> <span class=\"token known-class-name class-name\">Math</span><span class=\"token punctuation\">.</span><span class=\"token method function property-access\">floor</span><span class=\"token punctuation\">(</span><span class=\"token punctuation\">(</span>left <span class=\"token operator\">+</span> right<span class=\"token punctuation\">)</span> <span class=\"token operator\">/</span> <span class=\"token number\">2</span><span class=\"token punctuation\">)</span>\n    <span class=\"token keyword\">let</span> guess <span class=\"token operator\">=</span> nums<span class=\"token punctuation\">[</span>mid<span class=\"token punctuation\">]</span>\n\n    <span class=\"token keyword control-flow\">if</span> <span class=\"token punctuation\">(</span>guess <span class=\"token operator\">===</span> item<span class=\"token punctuation\">)</span> <span class=\"token punctuation\">{</span>\n      <span class=\"token keyword control-flow\">return</span> mid\n    <span class=\"token punctuation\">}</span>\n\n    <span class=\"token keyword control-flow\">if</span> <span class=\"token punctuation\">(</span>guess <span class=\"token operator\">&gt;</span> item<span class=\"token punctuation\">)</span> <span class=\"token punctuation\">{</span>\n      <span class=\"token comment\">// too high</span>\n      right <span class=\"token operator\">=</span> mid <span class=\"token operator\">-</span> <span class=\"token number\">1</span>\n    <span class=\"token punctuation\">}</span> <span class=\"token keyword control-flow\">else</span> <span class=\"token punctuation\">{</span>\n      <span class=\"token comment\">// too low</span>\n      left <span class=\"token operator\">=</span> mid <span class=\"token operator\">+</span> <span class=\"token number\">1</span>\n    <span class=\"token punctuation\">}</span>\n  <span class=\"token punctuation\">}</span> <span class=\"token keyword control-flow\">while</span> <span class=\"token punctuation\">(</span>left <span class=\"token operator\">&lt;=</span> right<span class=\"token punctuation\">)</span>\n\n  <span class=\"token keyword control-flow\">return</span> <span class=\"token operator\">-</span><span class=\"token number\">1</span>\n<span class=\"token punctuation\">}</span>\n\n<span class=\"token keyword\">const</span> result <span class=\"token operator\">=</span> <span class=\"token function\">binarySearch</span><span class=\"token punctuation\">(</span><span class=\"token punctuation\">[</span><span class=\"token number\">1</span><span class=\"token punctuation\">,</span> <span class=\"token number\">2</span><span class=\"token punctuation\">,</span> <span class=\"token number\">3</span><span class=\"token punctuation\">,</span> <span class=\"token number\">4</span><span class=\"token punctuation\">,</span> <span class=\"token number\">5</span><span class=\"token punctuation\">]</span><span class=\"token punctuation\">,</span> <span class=\"token number\">4</span><span class=\"token punctuation\">)</span> <span class=\"token comment\">// 3</span>\n<span class=\"token console class-name\">console</span><span class=\"token punctuation\">.</span><span class=\"token method function property-access\">log</span><span class=\"token punctuation\">(</span><span class=\"token punctuation\">{</span> result <span class=\"token punctuation\">}</span><span class=\"token punctuation\">)</span>\n</code></pre>\n<p>By running this code, you&#x27;ll see that it successfully locates the number &quot;4&quot; at the third index in the array. That&#x27;s the magic of binary search in action! Keep in mind, this is a simple JavaScript implementation. Depending on the layout or type of your data, you may need to adjust it to suit your scenario best.</p>\n<p>In conclusion, binary search is an efficient algorithm that can save a lot of time and computing power when locating items in large, sorted datasets. It truly underscores the benefits of understanding your data and structuring it logically to optimize search operations. Happy coding, and may binary search be with you in your algorithmic journeys!</p>",
            "url": "https://jopcmelo.dev/articles/binary-search",
            "title": "Demystifying Binary Search: An Algorithm for Quick Discovery",
            "summary": "Explore the fascinating world of Binary Search. This piece digs deep into the inner workings of this efficient algorithm, illustrating its effectiveness against a straightforward linear search. With examples and a useful JavaScript implementation, the article simplifies Binary Search, making it accessible for all developers. Ideal read for those eager to optimize their search operations in large, sorted datasets.",
            "date_modified": "2023-10-20T00:00:00.000Z",
            "author": {
                "name": "João Melo"
            }
        },
        {
            "id": "https://jopcmelo.dev/articles/ai-chat-with-langchain-pinecone-memory",
            "content_html": "<p>In recent times, the evolution of AI has been permeating various sectors of businesses and the day-to-day lives of individuals. The applicability of artificial intelligence can be immensely useful in many aspects of programming, such as generating reports, deriving insights, automating processes, processing data, and most notably, in creating chatbots trained with specific data to behave in unique ways and provide contextually relevant responses.</p>\n<p>With this development, new terminology has become popular for those working with AI, including <strong>embeddings</strong>, <strong>vectors</strong>, <strong>contexts</strong>, <strong>LangChain</strong>, and more. In this article, we&#x27;ll discuss how to create a chatbot using LangChain, Pinecone, and Upstash, with Next.js. The goal is to have an AI system ready to answer any question about an external context, store the history of message exchanges between the user and AI in a database, and use an intelligent search system to find the most appropriate response.</p>\n<p>In this article, we&#x27;ll build our chatbot using Next.js, utilizing LangChain to manage conversation chains, Pinecone to handle a vector database for executing semantic similarity searches, and Upstash to store the history of message exchanges between the user and the AI.</p>\n<h2>Before we start</h2>\n<p>As we&#x27;re about to create a project that leverages a vector database for embeddings and injects context into the AI to enable it to answer questions, it&#x27;s important that you have an account with Pinecone.</p>\n<p>You&#x27;ll need to follow the steps laid out by Pinecone to create and populate a vector index, as we&#x27;ll be consuming it in this project. For this, you can follow the steps outlined in the <a href=\"https://docs.pinecone.io/docs/quickstart\">Quickstart</a>.</p>\n<p>In a real-world application, you&#x27;ll need to devise a strategy for performing upsert operations on the vectors in your Pinecone index in accordance with your application&#x27;s context. In this article, however, we&#x27;ll focus more on how to consume the vector index for performing semantic similarity searches and passing context to the AI.</p>\n<h2>Creating a Next.js project</h2>\n<p>To kick things off, let&#x27;s create a Next.js project using the <code>npx create-next-app</code> command. We&#x27;ll name our project <code>demo-ai-chat</code>:</p>\n<pre class=\"language-bash\"><code class=\"language-bash\">npx create-next-app@latest\n</code></pre>\n<img alt=\"Creating a Next.js project\" loading=\"lazy\" width=\"722\" height=\"220\" decoding=\"async\" data-nimg=\"1\" style=\"color:transparent\" srcSet=\"/_next/image?url=%2F_next%2Fstatic%2Fmedia%2Fnextjs-setup.892138c0.png&amp;w=750&amp;q=75 1x, /_next/image?url=%2F_next%2Fstatic%2Fmedia%2Fnextjs-setup.892138c0.png&amp;w=1920&amp;q=75 2x\" src=\"/_next/image?url=%2F_next%2Fstatic%2Fmedia%2Fnextjs-setup.892138c0.png&amp;w=1920&amp;q=75\"/>\n<h2>Installing the dependencies</h2>\n<p>Now, let&#x27;s install the dependencies that we&#x27;ll be using in this project. We&#x27;ll install the following:</p>\n<ul>\n<li><code>langchain</code>: a library for managing conversation chains</li>\n<li><code>@pinecone-database/pinecone</code>: a library for dealing with a vector database and executing semantic similarity searches</li>\n<li><code>@upstash/redis</code>: a library for managing the Redis database</li>\n<li><code>ai</code>: an interoperable, streaming-enabled, edge-ready software development kit for AI apps built with React and Svelte by Vercel</li>\n</ul>\n<pre class=\"language-bash\"><code class=\"language-bash\"><span class=\"token function\">pnpm</span> <span class=\"token function\">install</span> langchain @pinecone-database/pinecone @upstash/redis ai\n</code></pre>\n<h2>Defining a simple interface for the chat</h2>\n<p>To start, let&#x27;s define a simple interface for the chat using the helper functions from the <code>ai</code> library provided by Vercel. Let&#x27;s modify the <code>app/page.tsx</code> file with the following content:</p>\n<pre class=\"language-tsx\"><code class=\"language-tsx\"><span class=\"token string\">&#x27;use client&#x27;</span>\n\n<span class=\"token keyword module\">import</span> <span class=\"token imports\"><span class=\"token punctuation\">{</span> useChat <span class=\"token punctuation\">}</span></span> <span class=\"token keyword module\">from</span> <span class=\"token string\">&#x27;ai/react&#x27;</span>\n\n<span class=\"token keyword module\">export</span> <span class=\"token keyword module\">default</span> <span class=\"token keyword\">function</span> <span class=\"token function\"><span class=\"token maybe-class-name\">Chat</span></span><span class=\"token punctuation\">(</span><span class=\"token punctuation\">)</span> <span class=\"token punctuation\">{</span>\n  <span class=\"token keyword\">const</span> <span class=\"token punctuation\">{</span> messages<span class=\"token punctuation\">,</span> input<span class=\"token punctuation\">,</span> handleInputChange<span class=\"token punctuation\">,</span> handleSubmit <span class=\"token punctuation\">}</span> <span class=\"token operator\">=</span> <span class=\"token function\">useChat</span><span class=\"token punctuation\">(</span><span class=\"token punctuation\">)</span>\n\n  <span class=\"token keyword control-flow\">return</span> <span class=\"token punctuation\">(</span>\n    <span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;</span>div</span> <span class=\"token attr-name\">className</span><span class=\"token attr-value\"><span class=\"token punctuation attr-equals\">=</span><span class=\"token punctuation\">&quot;</span>stretch mx-auto flex w-full max-w-md flex-col py-24<span class=\"token punctuation\">&quot;</span></span><span class=\"token punctuation\">&gt;</span></span><span class=\"token plain-text\">\n      </span><span class=\"token punctuation\">{</span>messages<span class=\"token punctuation\">.</span><span class=\"token property-access\">length</span> <span class=\"token operator\">&gt;</span> <span class=\"token number\">0</span>\n        <span class=\"token operator\">?</span> messages<span class=\"token punctuation\">.</span><span class=\"token method function property-access\">map</span><span class=\"token punctuation\">(</span><span class=\"token punctuation\">(</span>m<span class=\"token punctuation\">)</span> <span class=\"token arrow operator\">=&gt;</span> <span class=\"token punctuation\">(</span>\n            <span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;</span>div</span> <span class=\"token attr-name\">key</span><span class=\"token script language-javascript\"><span class=\"token script-punctuation punctuation\">=</span><span class=\"token punctuation\">{</span>m<span class=\"token punctuation\">.</span><span class=\"token property-access\">id</span><span class=\"token punctuation\">}</span></span> <span class=\"token attr-name\">className</span><span class=\"token attr-value\"><span class=\"token punctuation attr-equals\">=</span><span class=\"token punctuation\">&quot;</span>whitespace-pre-wrap<span class=\"token punctuation\">&quot;</span></span><span class=\"token punctuation\">&gt;</span></span><span class=\"token plain-text\">\n              </span><span class=\"token punctuation\">{</span>m<span class=\"token punctuation\">.</span><span class=\"token property-access\">role</span> <span class=\"token operator\">===</span> <span class=\"token string\">&#x27;user&#x27;</span> <span class=\"token operator\">?</span> <span class=\"token string\">&#x27;User: &#x27;</span> <span class=\"token operator\">:</span> <span class=\"token string\">&#x27;AI: &#x27;</span><span class=\"token punctuation\">}</span><span class=\"token plain-text\">\n              </span><span class=\"token punctuation\">{</span>m<span class=\"token punctuation\">.</span><span class=\"token property-access\">content</span><span class=\"token punctuation\">}</span><span class=\"token plain-text\">\n            </span><span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;/</span>div</span><span class=\"token punctuation\">&gt;</span></span>\n          <span class=\"token punctuation\">)</span><span class=\"token punctuation\">)</span>\n        <span class=\"token operator\">:</span> <span class=\"token keyword null nil\">null</span><span class=\"token punctuation\">}</span><span class=\"token plain-text\">\n\n      </span><span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;</span>form</span> <span class=\"token attr-name\">onSubmit</span><span class=\"token script language-javascript\"><span class=\"token script-punctuation punctuation\">=</span><span class=\"token punctuation\">{</span>handleSubmit<span class=\"token punctuation\">}</span></span><span class=\"token punctuation\">&gt;</span></span><span class=\"token plain-text\">\n        </span><span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;</span>input</span>\n          <span class=\"token attr-name\">className</span><span class=\"token attr-value\"><span class=\"token punctuation attr-equals\">=</span><span class=\"token punctuation\">&quot;</span>fixed bottom-0 mb-8 w-full max-w-md rounded border border-gray-300 p-2 shadow-xl<span class=\"token punctuation\">&quot;</span></span>\n          <span class=\"token attr-name\">value</span><span class=\"token script language-javascript\"><span class=\"token script-punctuation punctuation\">=</span><span class=\"token punctuation\">{</span>input<span class=\"token punctuation\">}</span></span>\n          <span class=\"token attr-name\">placeholder</span><span class=\"token attr-value\"><span class=\"token punctuation attr-equals\">=</span><span class=\"token punctuation\">&quot;</span>Say something...<span class=\"token punctuation\">&quot;</span></span>\n          <span class=\"token attr-name\">onChange</span><span class=\"token script language-javascript\"><span class=\"token script-punctuation punctuation\">=</span><span class=\"token punctuation\">{</span>handleInputChange<span class=\"token punctuation\">}</span></span>\n        <span class=\"token punctuation\">/&gt;</span></span><span class=\"token plain-text\">\n      </span><span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;/</span>form</span><span class=\"token punctuation\">&gt;</span></span><span class=\"token plain-text\">\n    </span><span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;/</span>div</span><span class=\"token punctuation\">&gt;</span></span>\n  <span class=\"token punctuation\">)</span>\n<span class=\"token punctuation\">}</span>\n</code></pre>\n<h2>Creating the API to interact with AI</h2>\n<h3>First, let&#x27;s create a function to instantiate our Pinecone database</h3>\n<p>To start, let&#x27;s create a function to instantiate our Pinecone database. For this, let&#x27;s create a file named <code>lib/pinecone.ts</code> with the following content:</p>\n<pre class=\"language-ts\"><code class=\"language-ts\"><span class=\"token keyword module\">import</span> <span class=\"token imports\"><span class=\"token punctuation\">{</span> <span class=\"token maybe-class-name\">PineconeClient</span> <span class=\"token punctuation\">}</span></span> <span class=\"token keyword module\">from</span> <span class=\"token string\">&#x27;@pinecone-database/pinecone&#x27;</span>\n\n<span class=\"token keyword module\">export</span> <span class=\"token keyword\">const</span> pinecone <span class=\"token operator\">=</span> <span class=\"token keyword\">new</span> <span class=\"token class-name\"><span class=\"token maybe-class-name\">PineconeClient</span></span><span class=\"token punctuation\">(</span><span class=\"token punctuation\">)</span>\n\n<span class=\"token keyword module\">export</span> <span class=\"token keyword\">const</span> <span class=\"token function-variable function\">initPinecone</span> <span class=\"token operator\">=</span> <span class=\"token keyword\">async</span> <span class=\"token punctuation\">(</span><span class=\"token punctuation\">)</span> <span class=\"token arrow operator\">=&gt;</span> <span class=\"token punctuation\">{</span>\n  <span class=\"token keyword control-flow\">if</span> <span class=\"token punctuation\">(</span><span class=\"token operator\">!</span>process<span class=\"token punctuation\">.</span><span class=\"token property-access\">env</span><span class=\"token punctuation\">.</span><span class=\"token constant\">PINECONE_API_KEY</span> <span class=\"token operator\">||</span> <span class=\"token operator\">!</span>process<span class=\"token punctuation\">.</span><span class=\"token property-access\">env</span><span class=\"token punctuation\">.</span><span class=\"token constant\">PINECONE_ENVIRONMENT</span><span class=\"token punctuation\">)</span> <span class=\"token punctuation\">{</span>\n    <span class=\"token keyword control-flow\">throw</span> <span class=\"token keyword\">new</span> <span class=\"token class-name\"><span class=\"token known-class-name class-name\">Error</span></span><span class=\"token punctuation\">(</span>\n      <span class=\"token string\">&#x27;PINECONE_API_KEY and PINECONE_ENVIRONMENT environment variables must be set&#x27;</span>\n    <span class=\"token punctuation\">)</span>\n  <span class=\"token punctuation\">}</span>\n\n  <span class=\"token keyword control-flow\">await</span> pinecone<span class=\"token punctuation\">.</span><span class=\"token method function property-access\">init</span><span class=\"token punctuation\">(</span><span class=\"token punctuation\">{</span>\n    apiKey<span class=\"token operator\">:</span> process<span class=\"token punctuation\">.</span><span class=\"token property-access\">env</span><span class=\"token punctuation\">.</span><span class=\"token constant\">PINECONE_API_KEY</span><span class=\"token punctuation\">,</span>\n    environment<span class=\"token operator\">:</span> process<span class=\"token punctuation\">.</span><span class=\"token property-access\">env</span><span class=\"token punctuation\">.</span><span class=\"token constant\">PINECONE_ENVIRONMENT</span><span class=\"token punctuation\">,</span>\n  <span class=\"token punctuation\">}</span><span class=\"token punctuation\">)</span>\n<span class=\"token punctuation\">}</span>\n</code></pre>\n<p>We&#x27;ll use this function to connect our application to Pinecone and perform semantic searches with LangChain. For now, let&#x27;s set it aside and create a function to instantiate our Upstash database.</p>\n<h2>Creating a function to instantiate our Upstash database</h2>\n<p>Now that we&#x27;ve managed to connect our application to Pinecone, let&#x27;s create a function to instantiate our Upstash database. For this, let&#x27;s create a file named <code>lib/upstash.ts</code> with the following content:</p>\n<pre class=\"language-ts\"><code class=\"language-ts\"><span class=\"token keyword module\">import</span> <span class=\"token imports\"><span class=\"token punctuation\">{</span> <span class=\"token maybe-class-name\">Redis</span> <span class=\"token punctuation\">}</span></span> <span class=\"token keyword module\">from</span> <span class=\"token string\">&#x27;@upstash/redis&#x27;</span>\n\n<span class=\"token keyword\">let</span> cachedDb<span class=\"token operator\">:</span> <span class=\"token maybe-class-name\">Redis</span>\n\n<span class=\"token keyword module\">export</span> <span class=\"token keyword\">async</span> <span class=\"token keyword\">function</span> <span class=\"token function\">getRedisClient</span><span class=\"token punctuation\">(</span><span class=\"token punctuation\">)</span> <span class=\"token punctuation\">{</span>\n  <span class=\"token keyword control-flow\">if</span> <span class=\"token punctuation\">(</span>cachedDb<span class=\"token punctuation\">)</span> <span class=\"token punctuation\">{</span>\n    <span class=\"token keyword control-flow\">return</span> cachedDb\n  <span class=\"token punctuation\">}</span>\n\n  <span class=\"token keyword control-flow\">if</span> <span class=\"token punctuation\">(</span><span class=\"token operator\">!</span>process<span class=\"token punctuation\">.</span><span class=\"token property-access\">env</span><span class=\"token punctuation\">.</span><span class=\"token constant\">UPSTASH_ENDPOINT</span> <span class=\"token operator\">||</span> <span class=\"token operator\">!</span>process<span class=\"token punctuation\">.</span><span class=\"token property-access\">env</span><span class=\"token punctuation\">.</span><span class=\"token constant\">UPSTASH_TOKEN</span><span class=\"token punctuation\">)</span> <span class=\"token punctuation\">{</span>\n    <span class=\"token keyword control-flow\">throw</span> <span class=\"token keyword\">new</span> <span class=\"token class-name\"><span class=\"token known-class-name class-name\">Error</span></span><span class=\"token punctuation\">(</span>\n      <span class=\"token string\">&#x27;Please define the UPSTASH_ENDPOINT and UPSTASH_TOKEN environment variables inside .env.local&#x27;</span>\n    <span class=\"token punctuation\">)</span>\n  <span class=\"token punctuation\">}</span>\n\n  <span class=\"token keyword\">const</span> client <span class=\"token operator\">=</span> <span class=\"token keyword\">new</span> <span class=\"token class-name\"><span class=\"token maybe-class-name\">Redis</span></span><span class=\"token punctuation\">(</span><span class=\"token punctuation\">{</span>\n    url<span class=\"token operator\">:</span> process<span class=\"token punctuation\">.</span><span class=\"token property-access\">env</span><span class=\"token punctuation\">.</span><span class=\"token constant\">UPSTASH_ENDPOINT</span><span class=\"token punctuation\">,</span>\n    token<span class=\"token operator\">:</span> process<span class=\"token punctuation\">.</span><span class=\"token property-access\">env</span><span class=\"token punctuation\">.</span><span class=\"token constant\">UPSTASH_TOKEN</span><span class=\"token punctuation\">,</span>\n  <span class=\"token punctuation\">}</span><span class=\"token punctuation\">)</span>\n\n  cachedDb <span class=\"token operator\">=</span> client\n\n  <span class=\"token keyword control-flow\">return</span> client\n<span class=\"token punctuation\">}</span>\n</code></pre>\n<p>With this function, we can now connect our application to Upstash and save the history of message exchanges between the user and AI. For now, let&#x27;s set it aside and focus on implementing LangChain, connecting to Pinecone, and saving the history of message exchanges between the user and AI in Upstash, all through a single chain. Sounds powerful, right? Let&#x27;s get down to the heavy lifting.</p>\n<h2>Creating an API to interact with the AI</h2>\n<p>Now that we&#x27;ve managed to connect our application to both Pinecone and Upstash, let&#x27;s create an API to interact with the AI. For this, let&#x27;s create a file named <code>app/api/chat/route.ts</code> with the following content:</p>\n<pre class=\"language-ts\"><code class=\"language-ts\"><span class=\"token keyword module\">import</span> <span class=\"token imports\"><span class=\"token punctuation\">{</span> <span class=\"token maybe-class-name\">StreamingTextResponse</span><span class=\"token punctuation\">,</span> <span class=\"token maybe-class-name\">LangChainStream</span> <span class=\"token punctuation\">}</span></span> <span class=\"token keyword module\">from</span> <span class=\"token string\">&#x27;ai&#x27;</span>\n<span class=\"token keyword module\">import</span> <span class=\"token imports\"><span class=\"token punctuation\">{</span> <span class=\"token maybe-class-name\">ChatOpenAI</span> <span class=\"token punctuation\">}</span></span> <span class=\"token keyword module\">from</span> <span class=\"token string\">&#x27;langchain/chat_models/openai&#x27;</span>\n<span class=\"token keyword module\">import</span> <span class=\"token imports\"><span class=\"token punctuation\">{</span> <span class=\"token maybe-class-name\">PineconeStore</span> <span class=\"token punctuation\">}</span></span> <span class=\"token keyword module\">from</span> <span class=\"token string\">&#x27;langchain/vectorstores/pinecone&#x27;</span>\n<span class=\"token keyword module\">import</span> <span class=\"token imports\"><span class=\"token punctuation\">{</span> <span class=\"token maybe-class-name\">OpenAIEmbeddings</span> <span class=\"token punctuation\">}</span></span> <span class=\"token keyword module\">from</span> <span class=\"token string\">&#x27;langchain/embeddings/openai&#x27;</span>\n<span class=\"token keyword module\">import</span> <span class=\"token imports\"><span class=\"token punctuation\">{</span> <span class=\"token maybe-class-name\">ConversationalRetrievalQAChain</span> <span class=\"token punctuation\">}</span></span> <span class=\"token keyword module\">from</span> <span class=\"token string\">&#x27;langchain/chains&#x27;</span>\n<span class=\"token keyword module\">import</span> <span class=\"token imports\"><span class=\"token punctuation\">{</span> <span class=\"token maybe-class-name\">BufferMemory</span> <span class=\"token punctuation\">}</span></span> <span class=\"token keyword module\">from</span> <span class=\"token string\">&#x27;langchain/memory&#x27;</span>\n\n<span class=\"token keyword module\">import</span> <span class=\"token imports\"><span class=\"token punctuation\">{</span> initPinecone<span class=\"token punctuation\">,</span> pinecone <span class=\"token punctuation\">}</span></span> <span class=\"token keyword module\">from</span> <span class=\"token string\">&#x27;@/lib/pinecone&#x27;</span>\n\n<span class=\"token keyword module\">export</span> <span class=\"token keyword\">const</span> runtime <span class=\"token operator\">=</span> <span class=\"token string\">&#x27;edge&#x27;</span>\n\n<span class=\"token keyword module\">export</span> <span class=\"token keyword\">async</span> <span class=\"token keyword\">function</span> <span class=\"token constant\">POST</span><span class=\"token punctuation\">(</span>req<span class=\"token operator\">:</span> <span class=\"token maybe-class-name\">Request</span><span class=\"token punctuation\">)</span> <span class=\"token punctuation\">{</span>\n  <span class=\"token keyword\">const</span> <span class=\"token punctuation\">{</span> messages <span class=\"token punctuation\">}</span> <span class=\"token operator\">=</span> <span class=\"token keyword control-flow\">await</span> req<span class=\"token punctuation\">.</span><span class=\"token method function property-access\">json</span><span class=\"token punctuation\">(</span><span class=\"token punctuation\">)</span>\n\n  <span class=\"token keyword\">const</span> <span class=\"token punctuation\">{</span> stream<span class=\"token punctuation\">,</span> handlers <span class=\"token punctuation\">}</span> <span class=\"token operator\">=</span> <span class=\"token function\"><span class=\"token maybe-class-name\">LangChainStream</span></span><span class=\"token punctuation\">(</span><span class=\"token punctuation\">)</span>\n\n  <span class=\"token keyword control-flow\">await</span> <span class=\"token function\">initPinecone</span><span class=\"token punctuation\">(</span><span class=\"token punctuation\">)</span>\n\n  <span class=\"token keyword\">const</span> pineconeIndex <span class=\"token operator\">=</span> pinecone<span class=\"token punctuation\">.</span><span class=\"token method function property-access\"><span class=\"token maybe-class-name\">Index</span></span><span class=\"token punctuation\">(</span><span class=\"token string\">&#x27;my-index&#x27;</span><span class=\"token punctuation\">)</span>\n  <span class=\"token keyword\">const</span> vectorStore <span class=\"token operator\">=</span> <span class=\"token keyword control-flow\">await</span> <span class=\"token maybe-class-name\">PineconeStore</span><span class=\"token punctuation\">.</span><span class=\"token method function property-access\">fromExistingIndex</span><span class=\"token punctuation\">(</span>\n    <span class=\"token keyword\">new</span> <span class=\"token class-name\"><span class=\"token maybe-class-name\">OpenAIEmbeddings</span></span><span class=\"token punctuation\">(</span><span class=\"token punctuation\">)</span><span class=\"token punctuation\">,</span>\n    <span class=\"token punctuation\">{</span>\n      pineconeIndex<span class=\"token punctuation\">,</span>\n      namespace<span class=\"token operator\">:</span> <span class=\"token string\">&#x27;my-namespace&#x27;</span><span class=\"token punctuation\">,</span>\n      textKey<span class=\"token operator\">:</span> <span class=\"token string\">&#x27;content&#x27;</span><span class=\"token punctuation\">,</span>\n    <span class=\"token punctuation\">}</span>\n  <span class=\"token punctuation\">)</span>\n\n  <span class=\"token keyword\">const</span> mainLLM <span class=\"token operator\">=</span> <span class=\"token keyword\">new</span> <span class=\"token class-name\"><span class=\"token maybe-class-name\">ChatOpenAI</span></span><span class=\"token punctuation\">(</span><span class=\"token punctuation\">{</span>\n    streaming<span class=\"token operator\">:</span> <span class=\"token boolean\">true</span><span class=\"token punctuation\">,</span>\n    modelName<span class=\"token operator\">:</span> <span class=\"token string\">&#x27;gpt-4&#x27;</span><span class=\"token punctuation\">,</span>\n    callbacks<span class=\"token operator\">:</span> <span class=\"token punctuation\">[</span>handlers<span class=\"token punctuation\">]</span><span class=\"token punctuation\">,</span>\n  <span class=\"token punctuation\">}</span><span class=\"token punctuation\">)</span>\n\n  <span class=\"token keyword\">const</span> underlyingLLM <span class=\"token operator\">=</span> <span class=\"token keyword\">new</span> <span class=\"token class-name\"><span class=\"token maybe-class-name\">ChatOpenAI</span></span><span class=\"token punctuation\">(</span><span class=\"token punctuation\">{</span>\n    modelName<span class=\"token operator\">:</span> <span class=\"token string\">&#x27;gpt-4&#x27;</span><span class=\"token punctuation\">,</span>\n  <span class=\"token punctuation\">}</span><span class=\"token punctuation\">)</span>\n\n  <span class=\"token keyword\">const</span> chain <span class=\"token operator\">=</span> <span class=\"token maybe-class-name\">ConversationalRetrievalQAChain</span><span class=\"token punctuation\">.</span><span class=\"token method function property-access\">fromLLM</span><span class=\"token punctuation\">(</span>\n    mainLLM<span class=\"token punctuation\">,</span>\n    vectorStore<span class=\"token punctuation\">.</span><span class=\"token method function property-access\">asRetriever</span><span class=\"token punctuation\">(</span><span class=\"token punctuation\">)</span><span class=\"token punctuation\">,</span>\n    <span class=\"token punctuation\">{</span>\n      memory<span class=\"token operator\">:</span> <span class=\"token keyword\">new</span> <span class=\"token class-name\"><span class=\"token maybe-class-name\">BufferMemory</span></span><span class=\"token punctuation\">(</span><span class=\"token punctuation\">{</span>\n        memoryKey<span class=\"token operator\">:</span> <span class=\"token string\">&#x27;chat_history&#x27;</span><span class=\"token punctuation\">,</span>\n        inputKey<span class=\"token operator\">:</span> <span class=\"token string\">&#x27;question&#x27;</span><span class=\"token punctuation\">,</span>\n        outputKey<span class=\"token operator\">:</span> <span class=\"token string\">&#x27;text&#x27;</span><span class=\"token punctuation\">,</span>\n        returnMessages<span class=\"token operator\">:</span> <span class=\"token boolean\">true</span><span class=\"token punctuation\">,</span>\n      <span class=\"token punctuation\">}</span><span class=\"token punctuation\">)</span><span class=\"token punctuation\">,</span>\n      questionGeneratorChainOptions<span class=\"token operator\">:</span> <span class=\"token punctuation\">{</span>\n        llm<span class=\"token operator\">:</span> underlyingLLM<span class=\"token punctuation\">,</span>\n      <span class=\"token punctuation\">}</span><span class=\"token punctuation\">,</span>\n    <span class=\"token punctuation\">}</span>\n  <span class=\"token punctuation\">)</span>\n\n  chain\n    <span class=\"token punctuation\">.</span><span class=\"token method function property-access\">call</span><span class=\"token punctuation\">(</span><span class=\"token punctuation\">{</span>\n      question<span class=\"token operator\">:</span> messages<span class=\"token punctuation\">[</span>messages<span class=\"token punctuation\">.</span><span class=\"token property-access\">length</span> <span class=\"token operator\">-</span> <span class=\"token number\">1</span><span class=\"token punctuation\">]</span><span class=\"token punctuation\">.</span><span class=\"token property-access\">content</span><span class=\"token punctuation\">,</span>\n    <span class=\"token punctuation\">}</span><span class=\"token punctuation\">)</span>\n    <span class=\"token punctuation\">.</span><span class=\"token keyword control-flow\">catch</span><span class=\"token punctuation\">(</span><span class=\"token console class-name\">console</span><span class=\"token punctuation\">.</span><span class=\"token property-access\">error</span><span class=\"token punctuation\">)</span>\n\n  <span class=\"token keyword control-flow\">return</span> <span class=\"token keyword\">new</span> <span class=\"token class-name\"><span class=\"token maybe-class-name\">StreamingTextResponse</span></span><span class=\"token punctuation\">(</span>stream<span class=\"token punctuation\">)</span>\n<span class=\"token punctuation\">}</span>\n</code></pre>\n<p>Here we need to pay attention to some important points:</p>\n<h3>Using the correct namespace</h3>\n<p>In the above code, you&#x27;ll need to replace <code>YOUR_NAMESPACE_HERE</code> with the namespace of your Pinecone index. You can find your Pinecone index&#x27;s namespace on the index page within Pinecone.</p>\n<h3>Using the correct value for <code>textKey</code></h3>\n<p>In the above code, you&#x27;ll need to replace the <code>content</code> value with the value of the field you used to save the text of your document in your Pinecone index. When performing the vector upsert in Pinecone, you can define some metadata. It&#x27;s important to save the content of each vector in the metadata so you can perform a semantic search using the created vectors and retrieve the document content. This key will be used internally by LangChain, accessing the vector metadata to retrieve the document content.</p>\n<h3>Using the right model</h3>\n<p>Depending on the purpose of your AI chatbot, you may need the AI to perform more complex tasks, so you might choose to use a more powerful model like <code>gpt-4</code> or a faster and simpler model like <code>gpt-3.5-turbo</code>. In this example, we&#x27;ll proceed with <code>gpt-4</code> and end up using both later on.</p>\n<h2>Unoptimized result</h2>\n<p>Vamos ver o que temos construído até então:</p>\n<img alt=\"Demo with what we have so far\" loading=\"lazy\" width=\"600\" height=\"496\" decoding=\"async\" data-nimg=\"1\" style=\"color:transparent\" srcSet=\"/_next/image?url=%2F_next%2Fstatic%2Fmedia%2Ffirst-demo.52b58243.gif&amp;w=640&amp;q=75 1x, /_next/image?url=%2F_next%2Fstatic%2Fmedia%2Ffirst-demo.52b58243.gif&amp;w=1200&amp;q=75 2x\" src=\"/_next/image?url=%2F_next%2Fstatic%2Fmedia%2Ffirst-demo.52b58243.gif&amp;w=1200&amp;q=75\"/>\n<p>With what we have built so far, we have a chat with an AI that has interesting capabilities, such as responding to questions about a context that is indexed in the Pinecone vector database. Let&#x27;s review what we have so far step by step.</p>\n<ol>\n<li>First, our implementation connects to our Pinecone database.</li>\n<li>We instantiate an AI model using the OpenAI model, <code>gpt-4</code>.</li>\n<li>We create a chain with LangChain, specifying the steps that the LangChain should follow:\n<ol>\n<li>Store all messages exchanged by the user and the AI in memory.</li>\n<li>Perform a semantic search in the Pinecone vector database to find the vectors that have the highest similarity with the user&#x27;s question.</li>\n<li>Ask the AI to refactor the user&#x27;s question based on the memory history.</li>\n<li>With the refactored response, use the context found in Pinecone to answer the user&#x27;s question.</li>\n<li>Return the response through text streaming.</li>\n</ol>\n</li>\n</ol>\n<p>One thing that may confuse you is the third step of the chain we created. What exactly does it mean for the LangChain to refactor the user&#x27;s question? Let&#x27;s understand this better.</p>\n<h3>Refactoring the user&#x27;s question</h3>\n<p>Imagine we have the following sequence of messages exchanged between the user and the AI:</p>\n<pre><code>User: Who is Guillermo Rauch?\nAI: Guillermo Rauch is an Argentine programmer and the CEO of Vercel.\nUser: Where does he live?\nAI: He lives in San Francisco.\n</code></pre>\n<p>Notice how the AI answered the user&#x27;s question based on the context it has about Guillermo Rauch. Now, imagine having only the following question in the history:</p>\n<pre><code>User: Where does he work?\n</code></pre>\n<p>The AI would not know that the pronoun <code>he</code> refers to Guillermo Rauch and therefore couldn&#x27;t provide information about him.</p>\n<p>That&#x27;s why the LangChain refactors the user&#x27;s question based on the memory history. This way, the AI can understand the context of the question and respond accordingly. With this intelligence, the AI can refactor the final user&#x27;s question to something like:</p>\n<pre><code>User: Where does Guillermo Rauch work?\n</code></pre>\n<p>Here&#x27;s a real example of how the AI refactors the user&#x27;s question:</p>\n<img alt=\"AI thoughts to rephrase human questions based on memory\" loading=\"lazy\" width=\"1482\" height=\"1756\" decoding=\"async\" data-nimg=\"1\" style=\"color:transparent\" srcSet=\"/_next/image?url=%2F_next%2Fstatic%2Fmedia%2Frephrased-question-by-ai.6334af5c.png&amp;w=1920&amp;q=75 1x, /_next/image?url=%2F_next%2Fstatic%2Fmedia%2Frephrased-question-by-ai.6334af5c.png&amp;w=3840&amp;q=75 2x\" src=\"/_next/image?url=%2F_next%2Fstatic%2Fmedia%2Frephrased-question-by-ai.6334af5c.png&amp;w=3840&amp;q=75\"/>\n<p>My original question was &quot;<strong>How old is he?</strong>,&quot; but the AI refactored it to &quot;<strong>How old is João?</strong>&quot; so that the context search in Pinecone would be more effective.</p>\n<p>Now that we understand how the LangChain uses the AI to refactor the question, it is easier to understand why we need to create two AI models. One is used to generate the final answer, while the other is used for the step of refactoring the user&#x27;s question. Since we want only the final answer to be returned through streaming, we provide the <code>streaming: true</code> configuration only to the <code>mainLLM</code>, which is the model that will generate the final answer.</p>\n<p>Remember that the step of refactoring the user&#x27;s question occurs only when there is some history of messages exchanged between the user and the AI. If there is no history, the AI will not refactor the user&#x27;s question. This means that for the first question asked to the AI, this step won&#x27;t occur because there is no history. However, starting from the second question, this step will happen since there is already history.</p>\n<h3>Returning to our chat</h3>\n<p>With the current version of our chat, we have something that can provide some value but will encounter some problems. Let&#x27;s see what these problems are and how we can solve them.</p>\n<h2>Problem 1: Chat history is lost with every new request</h2>\n<p>Since we are using only <code>BufferMemory</code> in our chain, it means that we keep the message history only in memory. This implies that with every new request, the message history is lost. This becomes a problem because we cannot leverage the context of the message history to refactor the user&#x27;s question.</p>\n<p>One solution could be to use the <code>messages</code> variable we receive in the request to build the message history. However, that is not a good idea because the <code>messages</code> variable is just an array of messages stored in the user&#x27;s browser. This means that the user can easily manipulate the message history or completely lose the message history by closing the chat page. Yes, we can solve this by using some form of disk storage on the user&#x27;s machine, such as <code>localStorage</code>, but it is still not the ideal scenario because the message history of that user would be available only in that browser and computer, not across all devices the user uses.</p>\n<blockquote>\n<p>&quot;But João, what if I store the message history in a database?&quot; - You.</p>\n</blockquote>\n<p>Yes, that&#x27;s a good idea. Let&#x27;s see how we can solve the first problem of our chain.</p>\n<h3>Introducing <code>UpstashRedisChatMessageHistory</code></h3>\n<p>LangChain provides us with a memory implementation that stores the message history in external databases. I recommend you take a look at the options they offer. In this article, we will use <code>UpstashRedisChatMessageHistory</code>, which stores the message history in Upstash, a Redis database that is extremely performant and has low latency.</p>\n<p>All we need to do is:</p>\n<ol>\n<li>Import <code>UpstashRedisChatMessageHistory</code> from <code>langchain</code>.</li>\n<li>Import the function we created at the beginning of this article to connect to Upstash.</li>\n<li>Create an instance of <code>UpstashRedisChatMessageHistory</code>.</li>\n<li>Pass the <code>UpstashRedisChatMessageHistory</code> instance to the <code>BufferMemory</code> in our chain.</li>\n</ol>\n<p>And that&#x27;s it! Here&#x27;s how our code looks:</p>\n<pre class=\"language-ts\"><code class=\"language-ts\"><span class=\"token comment\">// ...your other imports</span>\n<span class=\"token keyword module\">import</span> <span class=\"token imports\"><span class=\"token punctuation\">{</span> <span class=\"token maybe-class-name\">UpstashRedisChatMessageHistory</span> <span class=\"token punctuation\">}</span></span> <span class=\"token keyword module\">from</span> <span class=\"token string\">&#x27;langchain/stores/message/upstash_redis&#x27;</span>\n\n<span class=\"token keyword module\">import</span> <span class=\"token imports\"><span class=\"token punctuation\">{</span> getRedisClient <span class=\"token punctuation\">}</span></span> <span class=\"token keyword module\">from</span> <span class=\"token string\">&#x27;@/lib/upstash&#x27;</span>\n\n<span class=\"token comment\">// ...your code</span>\n\n<span class=\"token keyword\">const</span> chatHistory <span class=\"token operator\">=</span> <span class=\"token keyword\">new</span> <span class=\"token class-name\"><span class=\"token maybe-class-name\">UpstashRedisChatMessageHistory</span></span><span class=\"token punctuation\">(</span><span class=\"token punctuation\">{</span>\n  sessionId<span class=\"token operator\">:</span> <span class=\"token string\">&#x27;chat-session-1&#x27;</span><span class=\"token punctuation\">,</span> <span class=\"token comment\">// you can use the user id here, for example</span>\n  client<span class=\"token operator\">:</span> <span class=\"token keyword control-flow\">await</span> <span class=\"token function\">getRedisClient</span><span class=\"token punctuation\">(</span><span class=\"token punctuation\">)</span><span class=\"token punctuation\">,</span>\n<span class=\"token punctuation\">}</span><span class=\"token punctuation\">)</span>\n\n<span class=\"token keyword\">const</span> chain <span class=\"token operator\">=</span> <span class=\"token maybe-class-name\">ConversationalRetrievalQAChain</span><span class=\"token punctuation\">.</span><span class=\"token method function property-access\">fromLLM</span><span class=\"token punctuation\">(</span>\n  mainLLM<span class=\"token punctuation\">,</span>\n  vectorStore<span class=\"token punctuation\">.</span><span class=\"token method function property-access\">asRetriever</span><span class=\"token punctuation\">(</span><span class=\"token punctuation\">)</span><span class=\"token punctuation\">,</span>\n  <span class=\"token punctuation\">{</span>\n    memory<span class=\"token operator\">:</span> <span class=\"token keyword\">new</span> <span class=\"token class-name\"><span class=\"token maybe-class-name\">BufferMemory</span></span><span class=\"token punctuation\">(</span><span class=\"token punctuation\">{</span>\n      memoryKey<span class=\"token operator\">:</span> <span class=\"token string\">&#x27;chat_history&#x27;</span><span class=\"token punctuation\">,</span>\n      inputKey<span class=\"token operator\">:</span> <span class=\"token string\">&#x27;question&#x27;</span><span class=\"token punctuation\">,</span>\n      outputKey<span class=\"token operator\">:</span> <span class=\"token string\">&#x27;text&#x27;</span><span class=\"token punctuation\">,</span>\n      returnMessages<span class=\"token operator\">:</span> <span class=\"token boolean\">true</span><span class=\"token punctuation\">,</span>\n      chatHistory<span class=\"token punctuation\">,</span>\n    <span class=\"token punctuation\">}</span><span class=\"token punctuation\">)</span><span class=\"token punctuation\">,</span>\n    questionGeneratorChainOptions<span class=\"token operator\">:</span> <span class=\"token punctuation\">{</span>\n      llm<span class=\"token operator\">:</span> underlyingLLM<span class=\"token punctuation\">,</span>\n    <span class=\"token punctuation\">}</span><span class=\"token punctuation\">,</span>\n  <span class=\"token punctuation\">}</span>\n<span class=\"token punctuation\">)</span>\n\n<span class=\"token comment\">// ...your code</span>\n</code></pre>\n<p>Now, we can see that the message history is stored in Upstash, not in memory. This means that the message history is not lost with every new request, and we can leverage the context of the message history to refactor the user&#x27;s question.</p>\n<img alt=\"Upstash screenshot\" loading=\"lazy\" width=\"1372\" height=\"764\" decoding=\"async\" data-nimg=\"1\" style=\"color:transparent\" srcSet=\"/_next/image?url=%2F_next%2Fstatic%2Fmedia%2Fupstash-screenshot.15efd332.png&amp;w=1920&amp;q=75 1x, /_next/image?url=%2F_next%2Fstatic%2Fmedia%2Fupstash-screenshot.15efd332.png&amp;w=3840&amp;q=75 2x\" src=\"/_next/image?url=%2F_next%2Fstatic%2Fmedia%2Fupstash-screenshot.15efd332.png&amp;w=3840&amp;q=75\"/>\n<h2>Problem 2: High costs and low performance</h2>\n<p>Now that we have solved the first problem, let&#x27;s look at the second problem we face with our chain. Let&#x27;s see what happens when we ask a question to the AI:</p>\n<img alt=\"GIF showing the delay that the AI has in providing an answer\" loading=\"lazy\" width=\"576\" height=\"800\" decoding=\"async\" data-nimg=\"1\" style=\"color:transparent\" srcSet=\"/_next/image?url=%2F_next%2Fstatic%2Fmedia%2Fsecond-demo.e041a033.gif&amp;w=640&amp;q=75 1x, /_next/image?url=%2F_next%2Fstatic%2Fmedia%2Fsecond-demo.e041a033.gif&amp;w=1200&amp;q=75 2x\" src=\"/_next/image?url=%2F_next%2Fstatic%2Fmedia%2Fsecond-demo.e041a033.gif&amp;w=1200&amp;q=75\"/>\n<p>The delay before starting to write a response is due to two main factors:</p>\n<ol>\n<li>Semantic search in Pinecone</li>\n<li>Refactoring step of the user&#x27;s question</li>\n</ol>\n<p>In the semantic search, there isn&#x27;t much we can do. But in the refactoring step of the user&#x27;s question, we can make a small change to make the process faster.</p>\n<p>Let&#x27;s change the model we are using in <code>underlyingLLM</code> to <code>gpt-3.5-turbo</code>. This model is faster and simpler, and it will help us refactor the user&#x27;s question more quickly.</p>\n<pre class=\"language-ts\"><code class=\"language-ts\"><span class=\"token comment\">// ...your code</span>\n\n<span class=\"token keyword\">const</span> underlyingLLM <span class=\"token operator\">=</span> <span class=\"token keyword\">new</span> <span class=\"token class-name\"><span class=\"token maybe-class-name\">ChatOpenAI</span></span><span class=\"token punctuation\">(</span><span class=\"token punctuation\">{</span>\n  modelName<span class=\"token operator\">:</span> <span class=\"token string\">&#x27;gpt-3.5-turbo&#x27;</span><span class=\"token punctuation\">,</span>\n<span class=\"token punctuation\">}</span><span class=\"token punctuation\">)</span>\n\n<span class=\"token comment\">// ...your code</span>\n</code></pre>\n<p>Since this step does not require such a powerful model because it involves simple reasoning, we can use a simpler and faster model, and thus speed up the process.</p>\n<h2>Problem 3: Relevant context from the message history is not properly utilized</h2>\n<p>Take a look at what happens when we ask the AI a question about something mentioned in the message history:</p>\n<img alt=\"GIF showing the AI answering a question with the wrong chat history context\" loading=\"lazy\" width=\"576\" height=\"800\" decoding=\"async\" data-nimg=\"1\" style=\"color:transparent\" srcSet=\"/_next/image?url=%2F_next%2Fstatic%2Fmedia%2Fdemo-with-wrong-history-context.68adc81e.gif&amp;w=640&amp;q=75 1x, /_next/image?url=%2F_next%2Fstatic%2Fmedia%2Fdemo-with-wrong-history-context.68adc81e.gif&amp;w=1200&amp;q=75 2x\" src=\"/_next/image?url=%2F_next%2Fstatic%2Fmedia%2Fdemo-with-wrong-history-context.68adc81e.gif&amp;w=1200&amp;q=75\"/>\n<p>This happens because in the step of refactoring the user&#x27;s question, LangChain provides instructions only to refactor the question and make it clearer and more concise. This means that if the person is mentioning any information that was said in the message history, that information is not effectively utilized to refactor the user&#x27;s question.</p>\n<p>To address this, we can make a small adjustment to the AI instruction in this step to consider the relevant portion of the message history according to the user&#x27;s question, if there is any relevant portion.</p>\n<p>To make this adjustment, we create a new constant with a prompt that has clearer and stronger instructions, which will prompt the AI to use relevant excerpts from the message history that may be useful in answering the question. This way, the AI will not solely depend on the context obtained from Pinecone but also consider any important excerpts from the message history. Here&#x27;s how our code looks like:</p>\n<pre class=\"language-ts\"><code class=\"language-ts\"><span class=\"token comment\">// ...your code</span>\n\n<span class=\"token keyword\">const</span> <span class=\"token constant\">QA_UNDERLYING_PROMPT_TEMPLATE</span> <span class=\"token operator\">=</span> <span class=\"token template-string\"><span class=\"token template-punctuation string\">`</span><span class=\"token string\">Given the following conversation and a follow up question, return the conversation history excerpt that includes any relevant context to the question if it exists and rephrase the follow up question to be a standalone question.\nChat History:\n{chat_history}\nFollow Up Input: {question}\nYour answer should follow the following format:\n\\`\\`\\`\nUse the following pieces of conversation context to answer the users question.\nIf you don&#x27;t know the answer, just say that you don&#x27;t know, don&#x27;t try to make up an answer.\n----------------\nRelevant chat history excerpt:\n&lt;Relevant chat history excerpt as context here or &quot;N/A&quot; if nothing found&gt;\n\nQuestion: &lt;Rephrased question here&gt;\n\\`\\`\\`\nYour answer:\n</span><span class=\"token template-punctuation string\">`</span></span>\n\n<span class=\"token comment\">// ...your code</span>\n\n<span class=\"token keyword\">const</span> chain <span class=\"token operator\">=</span> <span class=\"token maybe-class-name\">ConversationalRetrievalQAChain</span><span class=\"token punctuation\">.</span><span class=\"token method function property-access\">fromLLM</span><span class=\"token punctuation\">(</span>\n  mainLLM<span class=\"token punctuation\">,</span>\n  vectorStore<span class=\"token punctuation\">.</span><span class=\"token method function property-access\">asRetriever</span><span class=\"token punctuation\">(</span><span class=\"token punctuation\">)</span><span class=\"token punctuation\">,</span>\n  <span class=\"token punctuation\">{</span>\n    memory<span class=\"token operator\">:</span> <span class=\"token keyword\">new</span> <span class=\"token class-name\"><span class=\"token maybe-class-name\">BufferMemory</span></span><span class=\"token punctuation\">(</span><span class=\"token punctuation\">{</span>\n      memoryKey<span class=\"token operator\">:</span> <span class=\"token string\">&#x27;chat_history&#x27;</span><span class=\"token punctuation\">,</span>\n      inputKey<span class=\"token operator\">:</span> <span class=\"token string\">&#x27;question&#x27;</span><span class=\"token punctuation\">,</span>\n      outputKey<span class=\"token operator\">:</span> <span class=\"token string\">&#x27;text&#x27;</span><span class=\"token punctuation\">,</span>\n      returnMessages<span class=\"token operator\">:</span> <span class=\"token boolean\">true</span><span class=\"token punctuation\">,</span>\n      chatHistory<span class=\"token punctuation\">,</span>\n    <span class=\"token punctuation\">}</span><span class=\"token punctuation\">)</span><span class=\"token punctuation\">,</span>\n    questionGeneratorChainOptions<span class=\"token operator\">:</span> <span class=\"token punctuation\">{</span>\n      llm<span class=\"token operator\">:</span> underlyingLLM<span class=\"token punctuation\">,</span>\n      template<span class=\"token operator\">:</span> <span class=\"token constant\">QA_UNDERLYING_PROMPT_TEMPLATE</span><span class=\"token punctuation\">,</span>\n    <span class=\"token punctuation\">}</span><span class=\"token punctuation\">,</span>\n  <span class=\"token punctuation\">}</span>\n<span class=\"token punctuation\">)</span>\n\n<span class=\"token comment\">// ...your code</span>\n</code></pre>\n<p>With this change, we are telling the AI that if there is any relevant excerpt in the message history, it should be used to answer the user&#x27;s question. Here&#x27;s the result:</p>\n<img alt=\"GIF showing the AI answering a question with the correct chat history context\" loading=\"lazy\" width=\"1482\" height=\"2060\" decoding=\"async\" data-nimg=\"1\" style=\"color:transparent\" srcSet=\"/_next/image?url=%2F_next%2Fstatic%2Fmedia%2Ffixed-history-context-issue-screenshot.fb637ea7.png&amp;w=1920&amp;q=75 1x, /_next/image?url=%2F_next%2Fstatic%2Fmedia%2Ffixed-history-context-issue-screenshot.fb637ea7.png&amp;w=3840&amp;q=75 2x\" src=\"/_next/image?url=%2F_next%2Fstatic%2Fmedia%2Ffixed-history-context-issue-screenshot.fb637ea7.png&amp;w=3840&amp;q=75\"/>\n<h2>Problem 4: Exceeding LLM token limit</h2>\n<p>As your users continue to use your chat, the memory of each chat session becomes increasingly larger. This means that with each new request, the LangChain will include the message history in the context of the AI, which can cause you to exceed the AI&#x27;s token limits. To address this scenario, we have a few options:</p>\n<ol>\n<li>Limit the size of the message history, so that your users have a clean message history after a certain number of exchanged messages.</li>\n<li>Instead of using <code>BufferMemory</code>, you can use other memory implementations provided by LangChain to, for example, keep only the most recent <code>N</code> messages or always summarize the message history.</li>\n</ol>\n<p>If you want to offer a good user experience, I recommend exploring the <a href=\"https://js.langchain.com/docs/modules/memory/\">memory options that LangChain provides</a>. The tool offers ways to optimize this.</p>\n<h2>Optimized result</h2>\n<p>Now that we have addressed all the problems encountered with our chain, we have a well-functioning chat system that can provide significant value to our users. Our AI has the main optimizations we need to deliver a good user experience, with valid and contextualized responses, access to previous conversation memory, and good performance.</p>\n<p>Here&#x27;s the final code of our chat:</p>\n<pre class=\"language-ts\"><code class=\"language-ts\"><span class=\"token keyword module\">import</span> <span class=\"token imports\"><span class=\"token punctuation\">{</span> <span class=\"token maybe-class-name\">StreamingTextResponse</span><span class=\"token punctuation\">,</span> <span class=\"token maybe-class-name\">LangChainStream</span> <span class=\"token punctuation\">}</span></span> <span class=\"token keyword module\">from</span> <span class=\"token string\">&#x27;ai&#x27;</span>\n<span class=\"token keyword module\">import</span> <span class=\"token imports\"><span class=\"token punctuation\">{</span> <span class=\"token maybe-class-name\">ChatOpenAI</span> <span class=\"token punctuation\">}</span></span> <span class=\"token keyword module\">from</span> <span class=\"token string\">&#x27;langchain/chat_models/openai&#x27;</span>\n<span class=\"token keyword module\">import</span> <span class=\"token imports\"><span class=\"token punctuation\">{</span> <span class=\"token maybe-class-name\">PineconeStore</span> <span class=\"token punctuation\">}</span></span> <span class=\"token keyword module\">from</span> <span class=\"token string\">&#x27;langchain/vectorstores/pinecone&#x27;</span>\n<span class=\"token keyword module\">import</span> <span class=\"token imports\"><span class=\"token punctuation\">{</span> <span class=\"token maybe-class-name\">OpenAIEmbeddings</span> <span class=\"token punctuation\">}</span></span> <span class=\"token keyword module\">from</span> <span class=\"token string\">&#x27;langchain/embeddings/openai&#x27;</span>\n<span class=\"token keyword module\">import</span> <span class=\"token imports\"><span class=\"token punctuation\">{</span> <span class=\"token maybe-class-name\">UpstashRedisChatMessageHistory</span> <span class=\"token punctuation\">}</span></span> <span class=\"token keyword module\">from</span> <span class=\"token string\">&#x27;langchain/stores/message/upstash_redis&#x27;</span>\n<span class=\"token keyword module\">import</span> <span class=\"token imports\"><span class=\"token punctuation\">{</span> <span class=\"token maybe-class-name\">ConversationalRetrievalQAChain</span> <span class=\"token punctuation\">}</span></span> <span class=\"token keyword module\">from</span> <span class=\"token string\">&#x27;langchain/chains&#x27;</span>\n\n<span class=\"token keyword module\">import</span> <span class=\"token imports\"><span class=\"token punctuation\">{</span> initPinecone<span class=\"token punctuation\">,</span> pinecone <span class=\"token punctuation\">}</span></span> <span class=\"token keyword module\">from</span> <span class=\"token string\">&#x27;@/lib/pinecone&#x27;</span>\n<span class=\"token keyword module\">import</span> <span class=\"token imports\"><span class=\"token punctuation\">{</span> getRedisClient <span class=\"token punctuation\">}</span></span> <span class=\"token keyword module\">from</span> <span class=\"token string\">&#x27;@/lib/upstash&#x27;</span>\n<span class=\"token keyword module\">import</span> <span class=\"token imports\"><span class=\"token punctuation\">{</span> <span class=\"token maybe-class-name\">BufferMemory</span> <span class=\"token punctuation\">}</span></span> <span class=\"token keyword module\">from</span> <span class=\"token string\">&#x27;langchain/memory&#x27;</span>\n\n<span class=\"token keyword module\">export</span> <span class=\"token keyword\">const</span> runtime <span class=\"token operator\">=</span> <span class=\"token string\">&#x27;edge&#x27;</span>\n\n<span class=\"token keyword\">const</span> <span class=\"token constant\">QA_UNDERLYING_PROMPT_TEMPLATE</span> <span class=\"token operator\">=</span> <span class=\"token template-string\"><span class=\"token template-punctuation string\">`</span><span class=\"token string\">Given the following conversation and a follow up question, return the conversation history excerpt that includes any relevant context to the question if it exists and rephrase the follow up question to be a standalone question.\nChat History:\n{chat_history}\nFollow Up Input: {question}\nYour answer should follow the following format:\n\\`\\`\\`\nUse the following pieces of conversation context to answer the users question.\nIf you don&#x27;t know the answer, just say that you don&#x27;t know, don&#x27;t try to make up an answer.\n----------------\nRelevant chat history excerpt:\n&lt;Relevant chat history excerpt as context here or &quot;N/A&quot; if nothing found&gt;\n\nQuestion: &lt;Rephrased question here&gt;\n\\`\\`\\`\nYour answer:\n</span><span class=\"token template-punctuation string\">`</span></span>\n\n<span class=\"token keyword module\">export</span> <span class=\"token keyword\">async</span> <span class=\"token keyword\">function</span> <span class=\"token constant\">POST</span><span class=\"token punctuation\">(</span>req<span class=\"token operator\">:</span> <span class=\"token maybe-class-name\">Request</span><span class=\"token punctuation\">)</span> <span class=\"token punctuation\">{</span>\n  <span class=\"token keyword\">const</span> <span class=\"token punctuation\">{</span> messages <span class=\"token punctuation\">}</span> <span class=\"token operator\">=</span> <span class=\"token keyword control-flow\">await</span> req<span class=\"token punctuation\">.</span><span class=\"token method function property-access\">json</span><span class=\"token punctuation\">(</span><span class=\"token punctuation\">)</span>\n\n  <span class=\"token keyword\">const</span> <span class=\"token punctuation\">{</span> stream<span class=\"token punctuation\">,</span> handlers <span class=\"token punctuation\">}</span> <span class=\"token operator\">=</span> <span class=\"token function\"><span class=\"token maybe-class-name\">LangChainStream</span></span><span class=\"token punctuation\">(</span><span class=\"token punctuation\">)</span>\n\n  <span class=\"token keyword control-flow\">await</span> <span class=\"token function\">initPinecone</span><span class=\"token punctuation\">(</span><span class=\"token punctuation\">)</span>\n\n  <span class=\"token keyword\">const</span> pineconeIndex <span class=\"token operator\">=</span> pinecone<span class=\"token punctuation\">.</span><span class=\"token method function property-access\"><span class=\"token maybe-class-name\">Index</span></span><span class=\"token punctuation\">(</span><span class=\"token string\">&#x27;my-index&#x27;</span><span class=\"token punctuation\">)</span>\n  <span class=\"token keyword\">const</span> vectorStore <span class=\"token operator\">=</span> <span class=\"token keyword control-flow\">await</span> <span class=\"token maybe-class-name\">PineconeStore</span><span class=\"token punctuation\">.</span><span class=\"token method function property-access\">fromExistingIndex</span><span class=\"token punctuation\">(</span>\n    <span class=\"token keyword\">new</span> <span class=\"token class-name\"><span class=\"token maybe-class-name\">OpenAIEmbeddings</span></span><span class=\"token punctuation\">(</span><span class=\"token punctuation\">)</span><span class=\"token punctuation\">,</span>\n    <span class=\"token punctuation\">{</span>\n      pineconeIndex<span class=\"token punctuation\">,</span>\n      namespace<span class=\"token operator\">:</span> <span class=\"token string\">&#x27;demo-ai-chat&#x27;</span><span class=\"token punctuation\">,</span>\n      textKey<span class=\"token operator\">:</span> <span class=\"token string\">&#x27;content&#x27;</span><span class=\"token punctuation\">,</span>\n    <span class=\"token punctuation\">}</span>\n  <span class=\"token punctuation\">)</span>\n\n  <span class=\"token keyword\">const</span> slowerModel <span class=\"token operator\">=</span> <span class=\"token keyword\">new</span> <span class=\"token class-name\"><span class=\"token maybe-class-name\">ChatOpenAI</span></span><span class=\"token punctuation\">(</span><span class=\"token punctuation\">{</span>\n    streaming<span class=\"token operator\">:</span> <span class=\"token boolean\">true</span><span class=\"token punctuation\">,</span>\n    modelName<span class=\"token operator\">:</span> <span class=\"token string\">&#x27;gpt-4&#x27;</span><span class=\"token punctuation\">,</span>\n    callbacks<span class=\"token operator\">:</span> <span class=\"token punctuation\">[</span>handlers<span class=\"token punctuation\">]</span><span class=\"token punctuation\">,</span>\n  <span class=\"token punctuation\">}</span><span class=\"token punctuation\">)</span>\n\n  <span class=\"token keyword\">const</span> fasterModel <span class=\"token operator\">=</span> <span class=\"token keyword\">new</span> <span class=\"token class-name\"><span class=\"token maybe-class-name\">ChatOpenAI</span></span><span class=\"token punctuation\">(</span><span class=\"token punctuation\">{</span>\n    streaming<span class=\"token operator\">:</span> <span class=\"token boolean\">false</span><span class=\"token punctuation\">,</span>\n    modelName<span class=\"token operator\">:</span> <span class=\"token string\">&#x27;gpt-3.5-turbo&#x27;</span><span class=\"token punctuation\">,</span>\n  <span class=\"token punctuation\">}</span><span class=\"token punctuation\">)</span>\n\n  <span class=\"token keyword\">const</span> chatHistory <span class=\"token operator\">=</span> <span class=\"token keyword\">new</span> <span class=\"token class-name\"><span class=\"token maybe-class-name\">UpstashRedisChatMessageHistory</span></span><span class=\"token punctuation\">(</span><span class=\"token punctuation\">{</span>\n    sessionId<span class=\"token operator\">:</span> <span class=\"token string\">&#x27;chat-session-1&#x27;</span><span class=\"token punctuation\">,</span>\n    client<span class=\"token operator\">:</span> <span class=\"token keyword control-flow\">await</span> <span class=\"token function\">getRedisClient</span><span class=\"token punctuation\">(</span><span class=\"token punctuation\">)</span><span class=\"token punctuation\">,</span>\n  <span class=\"token punctuation\">}</span><span class=\"token punctuation\">)</span>\n\n  <span class=\"token keyword\">const</span> chain <span class=\"token operator\">=</span> <span class=\"token maybe-class-name\">ConversationalRetrievalQAChain</span><span class=\"token punctuation\">.</span><span class=\"token method function property-access\">fromLLM</span><span class=\"token punctuation\">(</span>\n    slowerModel<span class=\"token punctuation\">,</span>\n    vectorStore<span class=\"token punctuation\">.</span><span class=\"token method function property-access\">asRetriever</span><span class=\"token punctuation\">(</span><span class=\"token punctuation\">)</span><span class=\"token punctuation\">,</span>\n    <span class=\"token punctuation\">{</span>\n      memory<span class=\"token operator\">:</span> <span class=\"token keyword\">new</span> <span class=\"token class-name\"><span class=\"token maybe-class-name\">BufferMemory</span></span><span class=\"token punctuation\">(</span><span class=\"token punctuation\">{</span>\n        memoryKey<span class=\"token operator\">:</span> <span class=\"token string\">&#x27;chat_history&#x27;</span><span class=\"token punctuation\">,</span>\n        inputKey<span class=\"token operator\">:</span> <span class=\"token string\">&#x27;question&#x27;</span><span class=\"token punctuation\">,</span>\n        outputKey<span class=\"token operator\">:</span> <span class=\"token string\">&#x27;text&#x27;</span><span class=\"token punctuation\">,</span>\n        returnMessages<span class=\"token operator\">:</span> <span class=\"token boolean\">true</span><span class=\"token punctuation\">,</span>\n        chatHistory<span class=\"token punctuation\">,</span>\n      <span class=\"token punctuation\">}</span><span class=\"token punctuation\">)</span><span class=\"token punctuation\">,</span>\n      questionGeneratorChainOptions<span class=\"token operator\">:</span> <span class=\"token punctuation\">{</span>\n        llm<span class=\"token operator\">:</span> fasterModel<span class=\"token punctuation\">,</span>\n        template<span class=\"token operator\">:</span> <span class=\"token constant\">QA_UNDERLYING_PROMPT_TEMPLATE</span><span class=\"token punctuation\">,</span>\n      <span class=\"token punctuation\">}</span><span class=\"token punctuation\">,</span>\n    <span class=\"token punctuation\">}</span>\n  <span class=\"token punctuation\">)</span>\n\n  chain\n    <span class=\"token punctuation\">.</span><span class=\"token method function property-access\">call</span><span class=\"token punctuation\">(</span><span class=\"token punctuation\">{</span>\n      question<span class=\"token operator\">:</span> messages<span class=\"token punctuation\">[</span>messages<span class=\"token punctuation\">.</span><span class=\"token property-access\">length</span> <span class=\"token operator\">-</span> <span class=\"token number\">1</span><span class=\"token punctuation\">]</span><span class=\"token punctuation\">.</span><span class=\"token property-access\">content</span><span class=\"token punctuation\">,</span>\n    <span class=\"token punctuation\">}</span><span class=\"token punctuation\">)</span>\n    <span class=\"token punctuation\">.</span><span class=\"token keyword control-flow\">catch</span><span class=\"token punctuation\">(</span><span class=\"token console class-name\">console</span><span class=\"token punctuation\">.</span><span class=\"token property-access\">error</span><span class=\"token punctuation\">)</span>\n\n  <span class=\"token keyword control-flow\">return</span> <span class=\"token keyword\">new</span> <span class=\"token class-name\"><span class=\"token maybe-class-name\">StreamingTextResponse</span></span><span class=\"token punctuation\">(</span>stream<span class=\"token punctuation\">)</span>\n<span class=\"token punctuation\">}</span>\n</code></pre>\n<h2>GitHub repository</h2>\n<p>If you want to see the code in action, you can access the <a href=\"https://github.com/joaopcm/demo-ai-chat\">GitHub repository</a> of this project.</p>\n<h2>Conclusion</h2>\n<p>In this article, we&#x27;ve learned how to create a chatbot using LangChain, Pinecone, and Upstash, with Next.js and streaming. We&#x27;ve learned how to create a chain with LangChain, connect to Pinecone, and save the history of message exchanges between the user and AI in Upstash, all through a single chain. We&#x27;ve also learned how to use the <code>UpstashRedisChatMessageHistory</code> to save the history of message exchanges between the user and AI in Upstash, and how to use the <code>gpt-3.5-turbo</code> model to speed up the process of refactoring the user&#x27;s question. Also, we&#x27;ve walked through how to optimized the chain to take advantage of the relevant context of the history of message exchanges between the user and AI.</p>\n<p>I still have a great optimization I&#x27;d like to share with you, but I&#x27;ll leave that for the next post. This optimization makes context injection into AI brought from Pinecone more effective and we just use the amount of context needed without consuming more tokens than necessary to answer the user&#x27;s query. It will be a very interesting article, so stay tuned for it!</p>\n<p>I hope you enjoyed this article and that it helps you create your own AI chatbot. If you have any questions, feel free to reach out to me on Twitter at <a href=\"https://go.jopcmelo.dev/twitter\">@joaomelo</a>.</p>",
            "url": "https://jopcmelo.dev/articles/ai-chat-with-langchain-pinecone-memory",
            "title": "How to create an AI chat chain with LangChain, Pinecone, and memory",
            "summary": "Master the art of AI chat chains with LangChain, Pinecone, and Upstash, using Next.js. Elevate communication, harness the potential of intelligent conversations, and unlock the future of interaction.",
            "date_modified": "2023-10-16T00:00:00.000Z",
            "author": {
                "name": "João Melo"
            }
        },
        {
            "id": "https://jopcmelo.dev/articles/understanding-aws-lambda-a-comprehensive-guide-to-serverless-computing-for-everyone",
            "content_html": "<p>Are you looking for an easy-to-understand, comprehensive guide to serverless computing? You&#x27;ve come to the right place! In this article, we will explore AWS Lambda, one of the most popular serverless computing services. With AWS Lambda, you can build applications without worrying about managing servers or infrastructure. By the end of this post, you&#x27;ll have a solid understanding of AWS Lambda and how it can benefit your projects. Let&#x27;s dive in!</p>\n<h2>What is serverless computing?</h2>\n<p>Serverless computing is a cloud computing model that allows you to build and run applications without managing servers. Instead, you focus on writing code, while the cloud provider (in this case, AWS) takes care of the underlying infrastructure, scaling, and maintenance. This enables you to develop faster, reduce costs, and improve resource utilization.</p>\n<p>In recent years, serverless computing has gained significant popularity due to its simplicity, flexibility, and cost-effectiveness. By eliminating the need to manage servers, developers can concentrate on their core competencies and deliver applications quickly and efficiently.</p>\n<h2>Introducing AWS Lambda</h2>\n<p>AWS Lambda is a serverless compute service offered by Amazon Web Services (AWS). It allows you to run your code in response to events such as HTTP requests, changes in a database, or file uploads. Lambda automatically manages the compute resources, so you only pay for the actual execution time of your functions.</p>\n<p>AWS Lambda provides developers with several benefits:</p>\n<ul>\n<li><strong>Automatic scaling</strong>: AWS Lambda automatically scales your applications, handling any increase or decrease in traffic.</li>\n<li><strong>Cost-effective</strong>: Pay only for the compute time you consume, with no upfront costs or ongoing maintenance fees.</li>\n<li><strong>Event-driven</strong>: Lambda functions can be triggered by various AWS services or custom events.</li>\n<li><strong>Language support</strong>: Write Lambda functions in your preferred programming language, such as Node.js, Python, or Java.</li>\n<li><strong>Built-in fault tolerance</strong>: AWS Lambda is designed for high availability and automatically retries failed executions.</li>\n</ul>\n<h2>Getting started with AWS Lambda</h2>\n<p>To get started with AWS Lambda, you&#x27;ll need to follow these general steps:</p>\n<ol>\n<li><strong>Create a Lambda function</strong>: Write your code in a supported language and package it with any required dependencies.</li>\n<li><strong>Set up an event source</strong>: Configure a trigger for your Lambda function, such as an API Gateway, S3 bucket, or DynamoDB stream.</li>\n<li><strong>Test and deploy</strong>: Test your function within the AWS Management Console or using the AWS CLI, and deploy it to your desired environment.</li>\n</ol>\n<p>Each step involves specific actions and configurations that you&#x27;ll need to understand and implement. There are plenty of resources and tutorials available online to help you through the process.</p>\n<h2>Common use cases for AWS Lambda</h2>\n<p>AWS Lambda can be used for a variety of tasks and applications. Here are some common use cases:</p>\n<ol>\n<li><strong>Data processing</strong>: Perform real-time or batch data processing, such as transforming files or analyzing streaming data. AWS Lambda can be used to process data from various sources like S3, Kinesis, or DynamoDB.</li>\n<li><strong>APIs and microservices</strong>: Build scalable APIs and microservices using AWS Lambda and API Gateway. By combining the two services, you can create powerful and flexible APIs that can handle a wide range of requests.</li>\n<li><strong>Automation and orchestration</strong>: Automate tasks, like resizing images or sending notifications, in response to specific events. AWS Lambda can be triggered by various AWS services or custom events, making it an excellent choice for automation and orchestration tasks.</li>\n<li><strong>Machine learning</strong>: Integrate Lambda with AWS machine learning services for model training and inference. You can use AWS Lambda to preprocess data, invoke machine learning models, and process the results before returning them to the user. This integration allows you to leverage the power of machine learning without the need for managing complex infrastructure.</li>\n</ol>\n<h2>Best practices for AWS Lambda</h2>\n<p>To make the most out of AWS Lambda, it&#x27;s essential to follow some best practices:</p>\n<ol>\n<li><strong>Write stateless functions</strong>: AWS Lambda functions should be stateless to ensure scalability and fault tolerance. Store any required state information in external storage like DynamoDB or S3.</li>\n<li><strong>Optimize function performance</strong>: Monitor and optimize the performance of your Lambda functions by fine-tuning the memory allocation, setting appropriate timeouts, and reducing the function package size.</li>\n<li><strong>Use the right triggers</strong>: Choose the right event sources and triggers for your Lambda functions based on your use case. This ensures that your functions are executed in response to the correct events.</li>\n<li><strong>Implement proper error handling</strong>: Implement proper error handling and logging in your Lambda functions to ensure that you can quickly identify and resolve issues.</li>\n</ol>\n<h2>Conclusion</h2>\n<p>AWS Lambda is a powerful and flexible solution for building serverless applications. By leveraging its automatic scaling, cost-effectiveness, and event-driven capabilities, you can focus on writing code while AWS handles the operational aspects. With a better understanding of AWS Lambda and its various use cases, you&#x27;re now ready to embark on your serverless journey! Don&#x27;t forget to share this article with your friends and colleagues who might find it useful as well. Happy coding!</p>",
            "url": "https://jopcmelo.dev/articles/understanding-aws-lambda-a-comprehensive-guide-to-serverless-computing-for-everyone",
            "title": "Understanding AWS Lambda: A comprehensive guide to serverless computing for everyone",
            "summary": "A comprehensive guide to serverless computing with AWS Lambda, including key features, use cases, and best practices for building serverless applications.",
            "date_modified": "2023-03-15T00:00:00.000Z",
            "author": {
                "name": "João Melo"
            }
        },
        {
            "id": "https://jopcmelo.dev/articles/how-to-create-a-winning-professional-profile-on-linkedin-github-and-stack-overflow",
            "content_html": "<p>Creating a profile that stands out is crucial when searching for job opportunities, freelancing work, or building a professional network. Your profile is the first impression that potential employers or clients have of you, so it is important to ensure it is well-presented, relevant, and highlights your expertise. In this article, we will provide you with tips for creating a professional profile on LinkedIn, GitHub, and Stack Overflow.</p>\n<h2>Tips for creating a LinkedIn profile</h2>\n<p>LinkedIn is a social media platform designed for professionals to connect, showcase their work, and find job opportunities. Here are some tips to make your profile stand out:</p>\n<ol>\n<li><strong>Choose your profile picture carefully</strong>: Your profile picture is the first thing that potential employers or clients will see. Ensure your picture is professional, looks good, and represents your personal brand.</li>\n<li><strong>Write a compelling headline</strong>: Use a short, concise headline that summarizes your current role, skills, and what you offer. This will help you stand out in search results and make it easier for potential employers or clients to understand what you have to offer.</li>\n<li><strong>Craft an impactful About section</strong>: Use this section to give a brief overview of your career, what you bring to the table, and what you want to accomplish in the future. Remember to write in the first person and include your contact email here so recruiters can reach you faster.</li>\n<li><strong>Highlight your experience</strong>: Detail your past roles and responsibilities, showcasing your skills and achievements. Use relevant keywords from the job description to increase visibility to recruiters.</li>\n<li><strong>Add your education</strong>: List your degrees, certifications, and other relevant courses. This will provide potential employers or clients with a clear understanding of your educational background.</li>\n<li><strong>Include media</strong>: Share documents, presentations, videos, and other media that demonstrate your expertise. This will help to make your profile more engaging and stand out.</li>\n<li><strong>Ask for endorsements and recommendations</strong>: Build your credibility by asking your network to endorse your skills or write a recommendation. This will help to establish trust with potential employers or clients.</li>\n<li><strong>Engage with your network</strong>: Respond to messages, comment on posts, and share relevant content to keep your profile active and engaging.</li>\n<li><strong>Stay current</strong>: Regularly update your profile, add new skills and experiences, and engage with your network to keep your profile updated. Additionally, proofread your profile for spelling and grammar.</li>\n<li><strong>Maintain an English-language profile</strong>: Your LinkedIn profile can be in two different languages for different audiences. Carefully proofread each profile for spelling and grammar.</li>\n</ol>\n<h2>Tips for creating a GitHub profile</h2>\n<p>GitHub is a platform for developers to host and review code, manage projects, and build software. Here are some tips to make your profile stand out:</p>\n<ol>\n<li><strong>Choose a username</strong>: Use something that represents you and that is easy to remember and find. This will make it easier for potential employers or clients to find you.</li>\n<li><strong>Complete your profile</strong>: Add a profile picture, bio, and location to help others get to know you better. Additionally, add your contact email here so recruiters can reach you faster.</li>\n<li><strong>Showcase your projects</strong>: Add repositories that demonstrate your skills and show your projects. This will help potential employers or clients understand your coding skills.</li>\n<li><strong>Make your repositories readable</strong>: Write clear, concise documentation and comments to make it easy for others to understand your code. This will help potential employers or clients to quickly understand your coding skills.</li>\n<li><strong>Participate in open source projects</strong>: Collaborate with other developers by contributing to open source projects and sharing your code with the community. This will help to build your reputation and gain recognition in the community.</li>\n<li><strong>Stay active</strong>: Regularly commit code, participate in pull requests, and engage with other developers to keep your profile active and up to date.</li>\n<li><strong>Highlight your skills</strong>: Use GitHub&#x27;s built-in skills endorsements feature to showcase your expertise. This can help you stand out to potential employers or clients.</li>\n<li><strong>Connect with other developers</strong>: Following other developers, joining GitHub communities, and engaging with others can help you build your network and expand your skill set.</li>\n<li><strong>Write a blog</strong>: Using GitHub Pages to create a blog and share your thoughts, insights, and experiences with others can help you gain recognition and establish yourself as an expert in your field.</li>\n<li><strong>Keep your code organized</strong>: Use GitHub&#x27;s features such as issues, pull requests, and projects to keep your code organized and manageable.</li>\n</ol>\n<h2>Tips for creating a Stack Overflow profile</h2>\n<ol>\n<li><strong>Choose a user-friendly display name</strong>: Using your real name or a recognizable moniker that reflects your personality and skills is recommended.</li>\n<li><strong>Complete your profile</strong>: Adding a profile picture, bio, and location can help others get to know you better.</li>\n<li><strong>Participate in the community</strong>: Adding a profile picture, bio, and location can help others get to know you better.</li>\n<li><strong>Be helpful and concice</strong>: Providing clear and concise answers to questions and always striving to help others in a friendly and professional manner is essential for building a positive reputation on Stack Overflow.</li>\n<li><strong>Share your knowledge</strong>: Sharing your expertise by writing articles, blog posts, and other content related to your areas of interest can help you gain recognition and establish yourself as an expert in your field.</li>\n<li><strong>Gain reputation</strong>: Building your reputation by answering questions, getting upvotes, and contributing to the community in other ways can help you stand out to potential employers or clients.</li>\n<li><strong>Stay up to date</strong>: Keeping up with the latest developments in your field by following relevant tags and reading the latest questions and answers is important for staying relevant and knowledgeable.</li>\n<li><strong>Participate in events</strong>: Attending or participating in sponsored Stack Overflow events can help you network with other developers and expand your knowledge.</li>\n<li><strong>Showcase your skills</strong>: Using Stack Overflow&#x27;s built-in skills endorsement feature to showcase your expertise can help you stand out to potential employers or clients.</li>\n<li><strong>Keep your profile updated</strong>: Regularly updating your profile with new information, skills, and achievements can help you stay relevant and showcase your growth and development.</li>\n</ol>\n<p>In today&#x27;s highly competitive job market, having a strong and well-structured profile on professional networking sites like LinkedIn, GitHub, and Stack Overflow is more important than ever. Recruiters and hiring managers often turn to these platforms to find and evaluate potential job candidates. A concise and complete profile that showcases your skills, expertise, and accomplishments can help you stand out from the crowd and catch the attention of recruiters.</p>\n<p>By following the tips mentioned in this article, you can create a profile that highlights your strengths and achievements, presents your work in a professional and organized manner, and positions you as a valuable asset to potential employers. Whether you are a software developer, data scientist, or business professional, having a strong presence on these platforms can help you connect with other professionals, build your network, and ultimately land your dream job.</p>\n<p>So, take the time to optimize your profile on LinkedIn, GitHub, and Stack Overflow by adding a profile picture, bio, and your work history. Show off your skills and experience by sharing your projects and contributing to open source projects. Keep your profile up-to-date with the latest information and engage with the community to build your reputation and expand your network. With a little effort and attention, you can create a profile that gets you noticed by recruiters and helps you achieve your career goals.</p>",
            "url": "https://jopcmelo.dev/articles/how-to-create-a-winning-professional-profile-on-linkedin-github-and-stack-overflow",
            "title": "How to create a winning professional profile on LinkedIn, GitHub, and Stack Overflow",
            "summary": "Tips for creating a professional profile on LinkedIn, GitHub, and Stack Overflow",
            "date_modified": "2023-02-24T00:00:00.000Z",
            "author": {
                "name": "João Melo"
            }
        },
        {
            "id": "https://jopcmelo.dev/articles/is-nodejs-single-threaded-or-not",
            "content_html": "<p>There is a very common question in the NodeJS developer community about whether NodeJS is single-threaded. We first need to understand how NodeJS works underneath the scenes to find the answer.</p>\n<p>Let&#x27;s get started!</p>\n<h2>Getting to Know the Event Loop</h2>\n<p>The Event Loop is a built-in feature of NodeJS built around a cycle of events. This is how NodeJS executes all instructions in its algorithm and passes these instructions to the machine processor.</p>\n<p>Event Loop is single-threaded. That is, all instructions are sent to a single thread, called the Event Queue, and then either each instruction in that list is processed in order, or they are handed off to another thread (Thread Pool) that will execute them in the background. This second thread that executes instructions in the background is made possible by <a href=\"https://www.geeksforgeeks.org/libuv-in-node-js/\">libuv</a> (a C library originally written for NodeJS to abstract non-blocking input/output operations).</p>\n<p>As soon as each Event Loop operation is finished, NodeJS returns to the list of next tasks and focuses on executing the next non-blocking task.</p>\n<h3>Step by step</h3>\n<p>NodeJS is event-based (like requests, calls, etc). <strong>All these events are processed primarily in a single thread and may vary according to the type of operation (such as whether it is blocking I/O or not)</strong>.</p>\n<p>The step-by-step that NodeJS performs are:</p>\n<ol>\n<li>The operation arrives in the Event Queue;</li>\n<li>If it is the first operation in the list, the Event Loop consumes it immediately;</li>\n<li>The Event Loop checks whether this operation is fast or not to be executed;</li>\n<li>If it is a fast operation, it is processed and returns the answer so that the consumption of the next operations can be performed;</li>\n<li>If it is not a fast operation to be executed (such as operations involving filesystem, network, process, and other modules), the operation is sent to the Thread Pool so that the Event Loop is not blocked for too long;</li>\n<li><strong>While the Thread Pool is executing longer tasks, the Event Loop keeps consuming the lightweight tasks from the Event Queue, so there is no blockage in the processing of the code</strong>;</li>\n</ol>\n<img alt=\"Event Loop representation\" loading=\"lazy\" width=\"2759\" height=\"1424\" decoding=\"async\" data-nimg=\"1\" style=\"color:transparent\" srcSet=\"/_next/image?url=%2F_next%2Fstatic%2Fmedia%2Fimage-1.484c92da.webp&amp;w=3840&amp;q=75 1x\" src=\"/_next/image?url=%2F_next%2Fstatic%2Fmedia%2Fimage-1.484c92da.webp&amp;w=3840&amp;q=75\"/>\n<h3>What makes NodeJS different from other languages?</h3>\n<p>The Thread Pool (where slower operations are executed in the background) <strong>has 4 threads by default</strong>, but <a href=\"https://stackoverflow.com/questions/17554688/has-anyone-tried-using-the-uv-threadpool-size-environment-variable\">this can be configured by hand to have varying threads</a>. In other words, <strong>the Thread Pool is not single-threaded but is part of the NodeJS core</strong>.</p>\n<p>The Thread Pool does not create a new thread for each operation but rather shares a pool of threads. This makes NodeJS more efficient concerning the consumption of computer resources. Because of this, NodeJS will use much less computational resources than an application made in PHP or .NET, for example (This does not mean that NodeJS is better or worse than PHP or .NET).</p>\n<h3>Here are some examples of how the NodeJS architecture works with single and multi-threaded operations</h3>\n<p>1 request on Google&#x27;s website executes about 88 million instructions on the CPU. So NodeJS delegates to someone else (Thread Pool) to execute this instruction so that while this is happening in the background, NodeJS can execute another 88 million instructions in parallel through the Event Loop instead of blocking 100% of the operations.</p>\n<p>Or when reading 1KB of data from a file, it takes 1.4 microseconds on an SSD that reads 200-730MB/s. On a 2GHz processor, this results in an execution of 28,000 instructions. Because of this, NodeJS does not block consumption and keeps this heavier operation in a background process.</p>\n<h2>Conclusion</h2>\n<p>NodeJS is single-threaded, but it relies on the help of the libuv library to perform some multi-threaded operations in the background.</p>",
            "url": "https://jopcmelo.dev/articles/is-nodejs-single-threaded-or-not",
            "title": "Is NodeJS single threaded or not?",
            "summary": "After all, what is the truth about this discussion? Let's discuss how NodeJS works behind the scenes and draw a conclusion about it",
            "date_modified": "2022-02-15T00:00:00.000Z",
            "author": {
                "name": "João Melo"
            }
        },
        {
            "id": "https://jopcmelo.dev/articles/how-to-work-remotely-while-earning-in-dollars",
            "content_html": "<p>The subject of this publication may seem an impossible or very difficult reality to achieve, right? It did for me too. Today I will share how I became an international developer and give some golden tips that would have helped me absurdly if I had received them while working in my home country.</p>\n<p>Remote work became a strong reality for us programmers a while ago because of this difficult time we are going through in history, however along with it came some problems, such as:</p>\n<ul>\n<li>Separating personal and professional life; and</li>\n<li>Face-to-face contact with friends and colleagues; and</li>\n<li>Among others;</li>\n</ul>\n<p>With these challenges coming all at once, we need to be careful and keep a close eye on things, so we don&#x27;t develop burnout from overwork, for example. But what is the relationship between the problems that the pandemic has brought to us and remote work? A company has to know how to deal with remote work to energize its community and achieve incredible milestones without putting its employees through delicate and bad situations. I started following X-Team a little over 1 year ago in this relationship.</p>\n<h2>What is the X-Team?</h2>\n<p>X-Team is a 100% remote company that has been improving its community for 15 years. X-Team hires people worldwide to form high-quality engineering teams and allocates these teams to large companies like FOX, Riot Games, Coinbase, Twitter, Dell, etc. X-Team could stop at the part about assigning teams to their customers, but they go much further than that, following their philosophy:</p>\n<blockquote>\n<p>&quot;Live your life like a great adventure again because when you can work from anywhere and you commit to using that flexibility to do more of what energizes you.&quot; - Ryan Chartrand, CEO of X-Team.</p>\n</blockquote>\n<h2>How does X-Team energize you?</h2>\n<p>The company invests heavily in the employee community to ensure everyone works happily, is energized, and is motivated. It is a fact that when someone works happy, energized, and motivated; consequently that person will deliver the best version of their work. But how do I feel energized? Let&#x27;s talk about some of the X-Team&#x27;s key incentive methods.</p>\n<h3>Unleash+</h3>\n<p><a href=\"https://x-team.com/blog/unleash/\">Unleash+</a> is a $2,500 credit that X-Team gives you once you join the team to spend on a variety of categories, whether it&#x27;s buying equipment for a podcast, buying an accessory for your bike, paying for therapy sessions, buying a course, or even building your own smart home. You use this credit to spend on things that will energize you and make you evolve more and more as a person.</p>\n<p>This credit renews every year, so as long as you are an X-Teamer, you can use this credit to energize yourself and evolve.</p>\n<h3>The Vault</h3>\n<p><a href=\"https://x-team.com/blog/vault/\">The Vault</a> is the X-Team&#x27;s store for exclusive and collectible items. You can exchange coins for exclusive items such as t-shirts, sweatshirts, mugs, backpacks, and hats. The most amazing thing about it is that these items are so whimsical that you always want to buy as many as possible.</p>\n<p>But how to get coins? There are some &quot;challenges&quot; called bounties on the X-Team&#x27;s collaborator platform. They are very diverse, ranging from &quot;Eat a pizza on a Saturday&quot; to &quot;Cycle 100km&quot;. When you complete a challenge, take a picture or screenshot and share it on the company&#x27;s Slack server, and you will be rewarded with some coins directly in your balance to spend in The Vault.</p>\n<p>Best of all, the items are renewed following a theme of <a href=\"https://x-team.com/blog/seasons/\">seasons</a> that last around 3 months. In other words, every 3 months, there are new exclusive, and amazing collectibles.</p>\n<h3>X-Outposts</h3>\n<p><a href=\"https://x-team.com/blog/x-outpost/\">X-Outposts</a> are the most famous events of the X-Team community. They organize monthly hacker houses worldwide so X-Teamers can meet, share experiences, and see new places worldwide. These events have occurred in some amazing places like <a href=\"https://x-team.com/blog/x-outpost-costa-rica/\">Costa Rica</a>, <a href=\"https://x-team.com/blog/x-outpost-austria/\">Austria</a>, <a href=\"https://x-team.com/blog/x-outpost-bali/\">Bali</a>, <a href=\"https://x-team.com/blog/x-outpost-mexico/\">Mexico</a>, <a href=\"https://x-team.com/blog/x-outpost-japan/\">Japan</a>, and <a href=\"https://x-team.com/blog/x-outpost-south-africa/\">South Africa</a>.</p>\n<h2>Who are X-Team&#x27;s clients?</h2>\n<p>X-Team has several clients that can place you in their internal team, like Riot Games, FOX, Coinbase, Twitter, Dell, etc.</p>\n<p>Besides large companies as clients, the opportunities to work with technologies on the rise in the market, such as React Native, ReactJS, VueJS, NodeJS, Python, Go, Scala, Serverless, and various other technologies.</p>\n<h2>How to join X-Team?</h2>\n<p>X-Team is a rapidly growing company, which also makes the demand for new developers within the community great. In other words, the company is constantly hiring programmers for various positions.</p>\n<p>The company has a <a href=\"https://x-team.com/developers/\">platform</a> where you can create an account, fill in some data about your career, and apply for any available position. However, as said before, X-Team is growing a lot and consequently receives thousands of applications weekly, making it difficult for the recruiting team to see them. Because of this, in this part of this post, I will explain how the <a href=\"https://x-team.com/blog/x-team-hiring-process/\">X-Team recruitment process</a> works and also give you some tips on how to become a top candidate for the X-Team recruitment team.</p>\n<h2>Recruitment process</h2>\n<h3>First contact</h3>\n<p>Once you have created an account on the X-Team vacancy platform, filled out your profile, and applied for a vacancy, the process starts with an introductory meeting where the X-Team recruitment team will talk to you by video call to understand more about your career moment, your plans and your projects. They will also introduce how the &quot;X-Team world&quot; works and answer any questions you might have.</p>\n<p>Here are some tips:</p>\n<ul>\n<li><strong>If you have any open-source collaborations, personal projects, or anything that could be community-driven, don&#x27;t hesitate to comment about it! X-Team loves to hear about side projects and their collaborations;</strong>;</li>\n<li>Communication is essential. Most applications that do not follow the process are because of a lack of English proficiency or a lack of a cultural match between the company and the candidate;</li>\n<li>If English is not your native language, I recommend practicing and warming up your English before starting the process; this will help you express yourself better and convey more reliability to the recruiting team;</li>\n</ul>\n<p>It is also very important to know <a href=\"https://x-team.com/blog/how-to-present-yourself-in-a-remote-developer-interview/\">how to present yourself to avoid mistakes that can make you fail to move on to the next stage</a>, such as bad lighting, bad audio, and improper dress.</p>\n<h3>Technical interview</h3>\n<p>After passing the first screening and X-Team identifying that you have a cultural fit with the company, a second stage will be scheduled, defined by a technical interview, but rest assured; there is usually no live coding, but usually, some technical questions focused on the technologies of the position you applied for.</p>\n<h3>Getting to know the clients</h3>\n<p>Going through the technical interview, X-Team will present your profile to their clients, and you may have some technical meetings with some clients, as they usually want to get to know you and ask more targeted questions for their work stack.</p>\n<h3>Final step</h3>\n<p>Suppose any client wants you on their team; congratulations! X-Team will contact you to finalize some contractual processes, and you will have a start date lined up with the recruitment team.</p>\n<p>If no client is sure they want you on their team, don&#x27;t worry; if X-Team feels confident in you and feels there is a good cultural match between you and X-Team, you may receive an offer to work on the company&#x27;s internal team. In contrast, searching for a client for you continues in the background, and you will follow the same contractual process.</p>\n<p>If none of the above scenarios occur, there is nothing to worry about! You can work on some <a href=\"https://x-team.com/blog/improve-your-chances-of-an-x-team-invite/\">issues to increase your chances of receiving an X-Team invitation</a> and <a href=\"https://x-team.com/blog/improve-your-x-team-profile/\">improve the information you provided when creating your account on the X-Team job platform</a>. <strong>Always update your profile; it will help you find an opportunity that is right for you!</strong></p>\n<h2>I&#x27;m applying for a vacancy but have doubts</h2>\n<p>Remember that you can contact X-Team anytime with your questions or even ask them during a video call. However, X-Team has already prepared the <a href=\"https://x-team.com/blog/applicants-faq/\">main questions about the company</a>; this can help you understand more about the company before you even start an interview.</p>\n<h2>Wrapping up</h2>\n<p>I hope this post has answered most of the questions of the people who have contacted me asking for help. The fact that there is now a post about how I joined X-Team and giving some tips for getting ahead doesn&#x27;t mean that you can&#x27;t contact me via social media (at the bottom of this platform) for any questions. I&#x27;ll be happy to talk to you 🙂 I&#x27;ll be glad to talk to you.</p>\n<p>In case this post has helped you in any way, I strongly urge you to share it with a friend who desires to work remotely, earning in dollars but doesn&#x27;t know how or has some doubts; it would be of great help.</p>",
            "url": "https://jopcmelo.dev/articles/how-to-work-remotely-while-earning-in-dollars",
            "title": "How to work remotely while earning in dollars",
            "summary": "How I became an international developer, and some golden tips that would have helped me absurdly if I had received them while working in my home country.",
            "date_modified": "2021-08-10T00:00:00.000Z",
            "author": {
                "name": "João Melo"
            }
        },
        {
            "id": "https://jopcmelo.dev/articles/optimizing-react-components",
            "content_html": "<h2>Getting ready</h2>\n<p>To understand when we should use the memo, we first need to <a href=\"https://www.jopcmelo.dev/articles/understanding-react-renderings\">understand how React works with rendering</a>.</p>\n<h2>What is the <code>memo</code> for?</h2>\n<p>Since you already know how React works under the hood, let&#x27;s move on to the applicability of the <code>memo</code> and take our applications to the next level. The <code>memo</code> will prevent React from re-rendering the child component if it hasn&#x27;t changed when the parent component changes.</p>\n<p>A clear example of the problem that <code>memo</code> solves in React is: whenever a parent component undergoes a change (whether in properties, state, css, etc.), the child components are also rendered again.</p>\n<p>Now that we know what the <code>memo</code> is for within the React world, let&#x27;s go for a hands on!</p>\n<h3>Hands on</h3>\n<p>Let&#x27;s take the following code as an example:</p>\n<pre class=\"language-jsx\"><code class=\"language-jsx\"><span class=\"token comment\">// pages/Home.tsx</span>\n\n<span class=\"token keyword module\">import</span> <span class=\"token imports\"><span class=\"token punctuation\">{</span> useState <span class=\"token punctuation\">}</span></span> <span class=\"token keyword module\">from</span> <span class=\"token string\">&#x27;react&#x27;</span><span class=\"token punctuation\">;</span>\n<span class=\"token keyword module\">import</span> <span class=\"token imports\"><span class=\"token punctuation\">{</span> api <span class=\"token punctuation\">}</span></span> <span class=\"token keyword module\">from</span> <span class=\"token string\">&#x27;../services/api&#x27;</span><span class=\"token punctuation\">;</span>\n<span class=\"token keyword module\">import</span> <span class=\"token imports\"><span class=\"token punctuation\">{</span> <span class=\"token maybe-class-name\">Item</span> <span class=\"token punctuation\">}</span></span> <span class=\"token keyword module\">from</span> <span class=\"token string\">&#x27;../components/Item&#x27;</span><span class=\"token punctuation\">;</span>\n\n<span class=\"token keyword\">function</span> <span class=\"token function\"><span class=\"token maybe-class-name\">List</span></span><span class=\"token punctuation\">(</span><span class=\"token punctuation\">)</span> <span class=\"token punctuation\">{</span>\n\t<span class=\"token keyword\">const</span> <span class=\"token punctuation\">[</span>items<span class=\"token punctuation\">,</span> setItems<span class=\"token punctuation\">]</span> <span class=\"token operator\">=</span> <span class=\"token function\">useState</span><span class=\"token punctuation\">(</span><span class=\"token punctuation\">[</span><span class=\"token punctuation\">]</span><span class=\"token punctuation\">)</span><span class=\"token punctuation\">;</span>\n\n\t<span class=\"token keyword\">async</span> <span class=\"token keyword\">function</span> <span class=\"token function\">handleClick</span><span class=\"token punctuation\">(</span><span class=\"token punctuation\">)</span> <span class=\"token punctuation\">{</span>\n\t\t<span class=\"token keyword\">const</span> response <span class=\"token operator\">=</span> <span class=\"token keyword control-flow\">await</span> api<span class=\"token punctuation\">.</span><span class=\"token method function property-access\">get</span><span class=\"token punctuation\">(</span><span class=\"token string\">&#x27;/items&#x27;</span><span class=\"token punctuation\">)</span>\n\t\t<span class=\"token function\">setItems</span><span class=\"token punctuation\">(</span>response<span class=\"token punctuation\">)</span><span class=\"token punctuation\">;</span>\n\t<span class=\"token punctuation\">}</span><span class=\"token punctuation\">;</span>\n\n\t<span class=\"token keyword control-flow\">return</span> <span class=\"token punctuation\">(</span>\n\t\t<span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;</span>div</span><span class=\"token punctuation\">&gt;</span></span><span class=\"token plain-text\">\n\t\t\t</span><span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;</span>div</span><span class=\"token punctuation\">&gt;</span></span><span class=\"token plain-text\">\n\t\t\t\t</span><span class=\"token punctuation\">{</span>items<span class=\"token punctuation\">.</span><span class=\"token method function property-access\">map</span><span class=\"token punctuation\">(</span><span class=\"token punctuation\">(</span><span class=\"token parameter\">item</span><span class=\"token punctuation\">)</span> <span class=\"token arrow operator\">=&gt;</span> <span class=\"token punctuation\">(</span>\n\t\t\t\t\t<span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;</span><span class=\"token class-name\">Item</span></span> <span class=\"token attr-name\">key</span><span class=\"token script language-javascript\"><span class=\"token script-punctuation punctuation\">=</span><span class=\"token punctuation\">{</span>item<span class=\"token punctuation\">.</span><span class=\"token property-access\">title</span><span class=\"token punctuation\">}</span></span> <span class=\"token attr-name\">item</span><span class=\"token script language-javascript\"><span class=\"token script-punctuation punctuation\">=</span><span class=\"token punctuation\">{</span>item<span class=\"token punctuation\">}</span></span> <span class=\"token punctuation\">/&gt;</span></span>\n\t\t\t\t<span class=\"token punctuation\">)</span><span class=\"token punctuation\">)</span><span class=\"token punctuation\">}</span><span class=\"token plain-text\">\n\t\t\t</span><span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;/</span>div</span><span class=\"token punctuation\">&gt;</span></span><span class=\"token plain-text\">\n\n\t\t\t</span><span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;</span>button</span> <span class=\"token attr-name\">type</span><span class=\"token attr-value\"><span class=\"token punctuation attr-equals\">=</span><span class=\"token punctuation\">&quot;</span>button<span class=\"token punctuation\">&quot;</span></span> <span class=\"token attr-name\">onClick</span><span class=\"token script language-javascript\"><span class=\"token script-punctuation punctuation\">=</span><span class=\"token punctuation\">{</span>handleClick<span class=\"token punctuation\">}</span></span><span class=\"token punctuation\">&gt;</span></span><span class=\"token plain-text\">Load items</span><span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;/</span>button</span><span class=\"token punctuation\">&gt;</span></span><span class=\"token plain-text\">\n\t\t</span><span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;/</span>div</span><span class=\"token punctuation\">&gt;</span></span>\n\t<span class=\"token punctuation\">)</span><span class=\"token punctuation\">;</span>\n<span class=\"token punctuation\">}</span><span class=\"token punctuation\">;</span>\n</code></pre>\n<pre class=\"language-jsx\"><code class=\"language-jsx\"><span class=\"token comment\">// components/Item.tsx</span>\n\n<span class=\"token keyword module\">import</span> <span class=\"token imports\"><span class=\"token punctuation\">{</span> memo <span class=\"token punctuation\">}</span></span> <span class=\"token keyword module\">from</span> <span class=\"token string\">&#x27;react&#x27;</span><span class=\"token punctuation\">;</span>\n\n<span class=\"token keyword\">interface</span> <span class=\"token class-name\">ItemComponentProps</span> <span class=\"token punctuation\">{</span>\n\t<span class=\"token literal-property property\">item</span><span class=\"token operator\">:</span> <span class=\"token punctuation\">{</span>\n\t\t<span class=\"token literal-property property\">title</span><span class=\"token operator\">:</span> string<span class=\"token punctuation\">;</span>\n\t<span class=\"token punctuation\">}</span>\n<span class=\"token punctuation\">}</span><span class=\"token punctuation\">;</span>\n\n<span class=\"token keyword\">function</span> <span class=\"token function\"><span class=\"token maybe-class-name\">ItemComponent</span></span><span class=\"token punctuation\">(</span><span class=\"token parameter\"><span class=\"token punctuation\">{</span> item <span class=\"token punctuation\">}</span><span class=\"token operator\">:</span> <span class=\"token maybe-class-name\">ItemComponentProps</span></span><span class=\"token punctuation\">)</span> <span class=\"token punctuation\">{</span>\n\t<span class=\"token keyword control-flow\">return</span> <span class=\"token punctuation\">(</span>\n\t\t<span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;</span>div</span><span class=\"token punctuation\">&gt;</span></span><span class=\"token plain-text\">\n\t\t\t</span><span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;</span>h1</span><span class=\"token punctuation\">&gt;</span></span><span class=\"token punctuation\">{</span>item<span class=\"token punctuation\">.</span><span class=\"token property-access\">title</span><span class=\"token punctuation\">}</span><span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;/</span>h1</span><span class=\"token punctuation\">&gt;</span></span><span class=\"token plain-text\">\n\t\t</span><span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;/</span>div</span><span class=\"token punctuation\">&gt;</span></span>\n\t<span class=\"token punctuation\">)</span>\n<span class=\"token punctuation\">}</span><span class=\"token punctuation\">;</span>\n\n<span class=\"token keyword module\">export</span> <span class=\"token keyword\">const</span> <span class=\"token maybe-class-name\">Item</span> <span class=\"token operator\">=</span> <span class=\"token function\">memo</span><span class=\"token punctuation\">(</span><span class=\"token maybe-class-name\">ItemComponent</span><span class=\"token punctuation\">,</span> <span class=\"token punctuation\">(</span><span class=\"token parameter\">prevProps<span class=\"token punctuation\">,</span> nextProps</span><span class=\"token punctuation\">)</span> <span class=\"token arrow operator\">=&gt;</span> <span class=\"token punctuation\">{</span>\n\t<span class=\"token keyword control-flow\">return</span> <span class=\"token known-class-name class-name\">Object</span><span class=\"token punctuation\">.</span><span class=\"token method function property-access\">is</span><span class=\"token punctuation\">(</span>preProps<span class=\"token punctuation\">.</span><span class=\"token property-access\">item</span><span class=\"token punctuation\">,</span> nextProps<span class=\"token punctuation\">.</span><span class=\"token property-access\">item</span><span class=\"token punctuation\">)</span><span class=\"token punctuation\">;</span>\n<span class=\"token punctuation\">}</span><span class=\"token punctuation\">)</span><span class=\"token punctuation\">;</span>\n</code></pre>\n<p>In this example, the following scenario takes place:</p>\n<ol>\n<li>When clicking the button, we&#x27;ll make a call to the API and store the response in the local state of the component;</li>\n<li>When a local state is updated, React re-renders the Home page displaying an <code>&lt;Item /&gt;</code> for each record returned from the API;</li>\n<li>If we click the button to reload the data, the API will return us the most up-to-date data and consequently we&#x27;ll have more data displayed on screen;</li>\n<li>Using <code>memo</code>, React will behave as fallows when it starts the process of creating the Virtual DOM for each child component:\n<ol>\n<li>Have the properties of that component changed?</li>\n<li>If yes, I&#x27;ll render those changes;</li>\n<li>If no, I will do nothing with this child component;</li>\n</ol>\n</li>\n</ol>\n<h3>Shallow compare</h3>\n<p>Did you know that the code snippet <code>{} === {}</code> returns <code>false</code> in JavaScript? This is because the equality operator <code>===</code> considers the comparison of memory and not just of value. That is, if you compare two objects that occupy different memory locations but have the same value, JavaScript will identify that they are different because they occupy different memory locations. For that reason, the memo can still re-render the child components since <code>prevProps</code>, and next props can occupy different memory locations.</p>\n<p>To solve this problem, memo gets a second parameter, a function in which we will define what it means for a property to have been changed or not for React. With this, we use <code>Object.is()</code> to do a deep comparison considering only the values of the object we received as a property in the component. If all values are equal, our function will return a true value, and React will not render the child component unnecessarily.</p>\n<h3>Use cases</h3>\n<p>Don&#x27;t use <code>memo</code> prematurely without real need. Unnecessary use of <code>memo</code> can cause your application to lose performance because it has to execute all the memo logic even when it is unnecessary.</p>\n<p><code>Memo</code> is used in some main situations:</p>\n<ul>\n<li><a href=\"https://blog.logrocket.com/react-pure-components-functional/#whatisareactpurecomponent\">Pure functional components</a>;</li>\n<li>Frequently rendered components;</li>\n<li>Re-renderings with the same properties;</li>\n<li>Medium or large components;</li>\n</ul>\n<h2>The <code>useMemo</code> hook</h2>\n<p>The use of <code>useMemo</code> prevents unnecessary heavy processing from being re-run along with the re-rendering of the component. Let&#x27;s see an example of how we can apply this hook!</p>\n<h3>Hands on</h3>\n<p>Let&#x27;s assume the following code:</p>\n<pre class=\"language-tsx\"><code class=\"language-tsx\"><span class=\"token keyword\">interface</span> <span class=\"token class-name\"><span class=\"token maybe-class-name\">CartShoppingProps</span></span> <span class=\"token punctuation\">{</span>\n\titems<span class=\"token operator\">:</span> <span class=\"token punctuation\">{</span>\n\t\tid<span class=\"token operator\">:</span> <span class=\"token builtin\">string</span><span class=\"token punctuation\">;</span>\n\t\tprice<span class=\"token operator\">:</span> <span class=\"token builtin\">string</span><span class=\"token punctuation\">;</span>\n\t<span class=\"token punctuation\">}</span><span class=\"token punctuation\">;</span>\n<span class=\"token punctuation\">}</span><span class=\"token punctuation\">;</span>\n\n<span class=\"token keyword module\">export</span> <span class=\"token keyword\">function</span> <span class=\"token function\"><span class=\"token maybe-class-name\">CartShopping</span></span><span class=\"token punctuation\">(</span><span class=\"token punctuation\">{</span> items <span class=\"token punctuation\">}</span><span class=\"token operator\">:</span> <span class=\"token maybe-class-name\">CartShoppingProps</span><span class=\"token punctuation\">)</span> <span class=\"token punctuation\">{</span>\n\t<span class=\"token keyword\">const</span> total <span class=\"token operator\">=</span> items<span class=\"token punctuation\">.</span><span class=\"token method function property-access\">reduce</span><span class=\"token punctuation\">(</span><span class=\"token punctuation\">(</span>accumulator<span class=\"token punctuation\">,</span> item<span class=\"token punctuation\">)</span> <span class=\"token arrow operator\">=&gt;</span> <span class=\"token punctuation\">{</span>\n\t\t<span class=\"token keyword control-flow\">return</span> accumulator <span class=\"token operator\">+</span> item<span class=\"token punctuation\">.</span><span class=\"token property-access\">price</span><span class=\"token punctuation\">;</span>\n\t<span class=\"token punctuation\">}</span><span class=\"token punctuation\">,</span> <span class=\"token number\">0</span><span class=\"token punctuation\">)</span><span class=\"token punctuation\">;</span>\n\n\t<span class=\"token keyword control-flow\">return</span> <span class=\"token punctuation\">(</span>\n\t\t<span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;</span>h1</span><span class=\"token punctuation\">&gt;</span></span><span class=\"token plain-text\">Total price: </span><span class=\"token punctuation\">{</span>total<span class=\"token punctuation\">}</span><span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;/</span>h1</span><span class=\"token punctuation\">&gt;</span></span>\n\t<span class=\"token punctuation\">)</span><span class=\"token punctuation\">;</span>\n<span class=\"token punctuation\">}</span><span class=\"token punctuation\">;</span>\n</code></pre>\n<ul>\n<li>\n<p>If some change causes the <code>&lt;CartShopping /&gt;</code> component to be re-rendered, <code>reduce()</code> will be executed again even if the final value is the same;</p>\n</li>\n<li>\n<p>With <code>useMemo</code>, React avoids running <code>reduce()</code> again if the result remains the same. See the example below:</p>\n<pre class=\"language-tsx\"><code class=\"language-tsx\"><span class=\"token keyword module\">import</span> <span class=\"token imports\"><span class=\"token punctuation\">{</span> useMemo <span class=\"token punctuation\">}</span></span> <span class=\"token keyword module\">from</span> <span class=\"token string\">&#x27;react&#x27;</span><span class=\"token punctuation\">;</span>\n\n<span class=\"token keyword\">interface</span> <span class=\"token class-name\"><span class=\"token maybe-class-name\">CartShoppingProps</span></span> <span class=\"token punctuation\">{</span>\n  items<span class=\"token operator\">:</span> <span class=\"token punctuation\">{</span>\n    id<span class=\"token operator\">:</span> <span class=\"token builtin\">string</span><span class=\"token punctuation\">;</span>\n    price<span class=\"token operator\">:</span> <span class=\"token builtin\">string</span><span class=\"token punctuation\">;</span>\n  <span class=\"token punctuation\">}</span><span class=\"token punctuation\">;</span>\n<span class=\"token punctuation\">}</span><span class=\"token punctuation\">;</span>\n\n<span class=\"token keyword module\">export</span> <span class=\"token keyword\">function</span> <span class=\"token function\"><span class=\"token maybe-class-name\">CartShopping</span></span><span class=\"token punctuation\">(</span><span class=\"token punctuation\">{</span> items <span class=\"token punctuation\">}</span><span class=\"token operator\">:</span> <span class=\"token maybe-class-name\">CartShoppingProps</span><span class=\"token punctuation\">)</span> <span class=\"token punctuation\">{</span>\n  <span class=\"token keyword\">const</span> total <span class=\"token operator\">=</span> <span class=\"token function\">useMemo</span><span class=\"token punctuation\">(</span><span class=\"token punctuation\">(</span><span class=\"token punctuation\">)</span> <span class=\"token arrow operator\">=&gt;</span> <span class=\"token punctuation\">{</span>\n    <span class=\"token keyword control-flow\">return</span> items<span class=\"token punctuation\">.</span><span class=\"token method function property-access\">reduce</span><span class=\"token punctuation\">(</span><span class=\"token punctuation\">(</span>accumulator<span class=\"token punctuation\">,</span> item<span class=\"token punctuation\">)</span> <span class=\"token arrow operator\">=&gt;</span> <span class=\"token punctuation\">{</span>\n      <span class=\"token keyword control-flow\">return</span> accumulator <span class=\"token operator\">+</span> item<span class=\"token punctuation\">.</span><span class=\"token property-access\">price</span><span class=\"token punctuation\">;</span>\n    <span class=\"token punctuation\">}</span><span class=\"token punctuation\">,</span> <span class=\"token number\">0</span><span class=\"token punctuation\">)</span><span class=\"token punctuation\">;</span>\n  <span class=\"token punctuation\">}</span><span class=\"token punctuation\">)</span>\n\n  <span class=\"token keyword control-flow\">return</span> <span class=\"token punctuation\">(</span>\n    <span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;</span>h1</span><span class=\"token punctuation\">&gt;</span></span><span class=\"token plain-text\">Total price: </span><span class=\"token punctuation\">{</span>total<span class=\"token punctuation\">}</span><span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;/</span>h1</span><span class=\"token punctuation\">&gt;</span></span>\n  <span class=\"token punctuation\">)</span><span class=\"token punctuation\">;</span>\n<span class=\"token punctuation\">}</span><span class=\"token punctuation\">;</span>\n</code></pre>\n</li>\n<li>\n<p>In this scenario, if the component is re-rendered, but the values remain in the properties, <code>reduce()</code> will not run again, and the application will consume less processing;</p>\n</li>\n<li>\n<p>With <code>useMemo</code>, React avoids a variable occupying a new memory location when we use it to pass on to a child component;</p>\n</li>\n</ul>\n<h3>Use cases</h3>\n<ul>\n<li>Heavy processing;</li>\n<li>Referential equality (when we pass information to a child component);</li>\n</ul>\n<h2>The <code>useCallback</code> hook</h2>\n<p>We use <code>useCallback</code> when we want to remember a function, not a value. For values we use <code>useMemo</code>.</p>\n<p>When we create a function and this function is going to be passed on to the child components of our application, it is important that this function uses <code>useCallback</code> because every time a function is re-created in memory, React will re-render the component that receives the function, even if it has not changed.</p>\n<p><strong>The <code>useCallback</code> receives 2 parameters</strong>:</p>\n<ol>\n<li>The first is the function that will be managed by the <code>useCallback</code> hook;</li>\n<li>The second is an array of dependencies that will cause the function to be re-rendered;</li>\n</ol>\n<h2>Data formatting</h2>\n<p>Even though we use <code>useMemo</code> to avoid unnecessary calculations, React has comparison logic to identify whether calculations should be redone or not through <code>useMemo</code>. However, if I know when I should do the calculations, it is more interesting for me not to use <code>useMemo</code> so that it is possible to format the data at the interface build level and perform this only when I know we will need it (when getting the response from an API, for example).</p>\n<h2>Code splitting</h2>\n<p>When you generate the build of your React application, the process is: <strong>to take the entire import file tree and implement it in your bundle</strong>. In other words, the bundle contains <strong>all</strong> the code required for our application to run.</p>\n<p>However, there is a scenario where we only want to import a file if some condition is met (e.g., display a formatted date <strong>if</strong> the user clicks to open a modal). This becomes a problem because the bundle code will include code that will be used only in a specific condition, and not always.</p>\n<p>To solve this problem we can do lazy loading only when we need it. Here is some sample code for this implementation:</p>\n<h3>1. Import the method that works with lazy loading of code.</h3>\n<p>For applications with pure ReactJS:</p>\n<pre class=\"language-tsx\"><code class=\"language-tsx\"><span class=\"token keyword module\">import</span> <span class=\"token imports\"><span class=\"token punctuation\">{</span> lazy <span class=\"token keyword module\">as</span> lazyLoading <span class=\"token punctuation\">}</span></span> <span class=\"token keyword module\">from</span> <span class=\"token string\">&#x27;react&#x27;</span><span class=\"token punctuation\">;</span>\n</code></pre>\n<p>For applications with NextJS:</p>\n<pre class=\"language-tsx\"><code class=\"language-tsx\"><span class=\"token keyword module\">import</span> <span class=\"token imports\">lazyLoading</span> <span class=\"token keyword module\">from</span> <span class=\"token string\">&#x27;next/dynamic&#x27;</span><span class=\"token punctuation\">;</span>\n</code></pre>\n<h3>2. Turn your component into a lazy loading compatible component</h3>\n<pre class=\"language-tsx\"><code class=\"language-tsx\"><span class=\"token keyword\">const</span> <span class=\"token maybe-class-name\">MyLazyComponent</span> <span class=\"token operator\">=</span> <span class=\"token function\">lazyLoading</span><span class=\"token punctuation\">(</span><span class=\"token punctuation\">(</span><span class=\"token punctuation\">)</span> <span class=\"token arrow operator\">=&gt;</span> <span class=\"token punctuation\">{</span>\n\t<span class=\"token keyword control-flow\">return</span> <span class=\"token keyword module\">import</span><span class=\"token punctuation\">(</span><span class=\"token string\">&#x27;../components/MyComponent&#x27;</span><span class=\"token punctuation\">)</span><span class=\"token punctuation\">;</span>\n  <span class=\"token punctuation\">}</span><span class=\"token punctuation\">,</span> <span class=\"token punctuation\">{</span>\n    <span class=\"token function-variable function\">loading</span><span class=\"token operator\">:</span> <span class=\"token punctuation\">(</span><span class=\"token punctuation\">)</span> <span class=\"token arrow operator\">=&gt;</span> <span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;</span>span</span><span class=\"token punctuation\">&gt;</span></span><span class=\"token plain-text\">Loading...</span><span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;/</span>span</span><span class=\"token punctuation\">&gt;</span></span><span class=\"token punctuation\">,</span> <span class=\"token comment\">// here you can define a loading component to be shown when the application is &quot;downloading&quot; the component to be shown.</span>\n  <span class=\"token punctuation\">}</span><span class=\"token punctuation\">)</span><span class=\"token punctuation\">;</span>\n</code></pre>\n<p>And now, just use your component, and it will be loaded only when it actually needs to be used.</p>\n<h2>Virtualization</h2>\n<p>Let&#x27;s imagine a list of 1,000 items. Once a user accesses this list, it will take a lot of effort for the browser to render all the items in the list. Considering that not all 1,000 items will fit inside the end user&#x27;s browser view, we can work with a virtualization solution, in which React will display only the elements that the user has a field-of-view view of, thus drastically reducing the processing to display the full list.</p>\n<p>For this, I like to use a library called <a href=\"https://github.com/bvaughn/react-virtualized\">react-virtualized</a>. So let&#x27;s go through step by step how to implement this functionality!</p>\n<h3>Hands on</h3>\n<p>Install the library:</p>\n<pre class=\"language-bash\"><code class=\"language-bash\"><span class=\"token function\">yarn</span> <span class=\"token function\">add</span> react-virtualized <span class=\"token operator\">&amp;&amp;</span> <span class=\"token function\">yarn</span> <span class=\"token function\">add</span> @types/react-virtualized -D\n</code></pre>\n<p>Create a component that will be responsible for rendering the list:</p>\n<pre class=\"language-tsx\"><code class=\"language-tsx\"><span class=\"token keyword module\">import</span> <span class=\"token imports\"><span class=\"token punctuation\">{</span> <span class=\"token maybe-class-name\">List</span><span class=\"token punctuation\">,</span> <span class=\"token maybe-class-name\">AutoSizer</span><span class=\"token punctuation\">,</span> <span class=\"token maybe-class-name\">ListRowRenderer</span> <span class=\"token punctuation\">}</span></span> <span class=\"token keyword module\">from</span> <span class=\"token string\">&#x27;react-virtualized&#x27;</span><span class=\"token punctuation\">;</span>\n\n<span class=\"token keyword\">interface</span> <span class=\"token class-name\"><span class=\"token maybe-class-name\">MyComponentProps</span></span> <span class=\"token punctuation\">{</span>\n\titems<span class=\"token operator\">:</span> <span class=\"token builtin\">string</span><span class=\"token punctuation\">[</span><span class=\"token punctuation\">]</span><span class=\"token punctuation\">;</span>\n<span class=\"token punctuation\">}</span><span class=\"token punctuation\">;</span>\n\n<span class=\"token keyword module\">export</span> <span class=\"token keyword\">function</span> <span class=\"token function\"><span class=\"token maybe-class-name\">MyComponent</span></span><span class=\"token punctuation\">(</span><span class=\"token punctuation\">{</span> items <span class=\"token punctuation\">}</span><span class=\"token operator\">:</span> <span class=\"token maybe-class-name\">MyComponentProps</span><span class=\"token punctuation\">)</span> <span class=\"token punctuation\">{</span>\n\t<span class=\"token keyword\">const</span> rowRenderer<span class=\"token operator\">:</span> <span class=\"token function-variable function\"><span class=\"token maybe-class-name\">ListRowRenderer</span></span> <span class=\"token operator\">=</span> <span class=\"token punctuation\">(</span><span class=\"token punctuation\">{</span> index<span class=\"token punctuation\">,</span> key<span class=\"token punctuation\">,</span> style <span class=\"token punctuation\">}</span><span class=\"token punctuation\">)</span> <span class=\"token arrow operator\">=&gt;</span> <span class=\"token punctuation\">{</span>\n\t\t<span class=\"token keyword control-flow\">return</span> <span class=\"token punctuation\">(</span>\n\t\t\t<span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;</span>div</span> <span class=\"token attr-name\">key</span><span class=\"token script language-javascript\"><span class=\"token script-punctuation punctuation\">=</span><span class=\"token punctuation\">{</span>key<span class=\"token punctuation\">}</span></span> <span class=\"token attr-name\">style</span><span class=\"token script language-javascript\"><span class=\"token script-punctuation punctuation\">=</span><span class=\"token punctuation\">{</span>style<span class=\"token punctuation\">}</span></span><span class=\"token punctuation\">&gt;</span></span><span class=\"token plain-text\">\n\t\t\t\t</span><span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;</span>li</span><span class=\"token punctuation\">&gt;</span></span><span class=\"token punctuation\">{</span>items<span class=\"token punctuation\">[</span>index<span class=\"token punctuation\">]</span><span class=\"token punctuation\">}</span><span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;/</span>li</span><span class=\"token punctuation\">&gt;</span></span><span class=\"token plain-text\">\n\t\t\t</span><span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;/</span>div</span><span class=\"token punctuation\">&gt;</span></span>\n\t\t<span class=\"token punctuation\">)</span><span class=\"token punctuation\">;</span>\n\t<span class=\"token punctuation\">}</span><span class=\"token punctuation\">;</span>\n\n\t<span class=\"token keyword control-flow\">return</span> <span class=\"token punctuation\">(</span>\n\t\t<span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;</span><span class=\"token class-name\">AutoSizer</span></span><span class=\"token punctuation\">&gt;</span></span><span class=\"token plain-text\">\n\t    </span><span class=\"token punctuation\">{</span><span class=\"token punctuation\">(</span><span class=\"token punctuation\">{</span>height<span class=\"token punctuation\">,</span> width<span class=\"token punctuation\">}</span><span class=\"token punctuation\">)</span> <span class=\"token arrow operator\">=&gt;</span> <span class=\"token punctuation\">(</span>\n\t      <span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;</span><span class=\"token class-name\">List</span></span>\n\t        <span class=\"token attr-name\">height</span><span class=\"token script language-javascript\"><span class=\"token script-punctuation punctuation\">=</span><span class=\"token punctuation\">{</span>height<span class=\"token punctuation\">}</span></span>\n\t        <span class=\"token attr-name\">width</span><span class=\"token script language-javascript\"><span class=\"token script-punctuation punctuation\">=</span><span class=\"token punctuation\">{</span>width<span class=\"token punctuation\">}</span></span>\n\t        <span class=\"token attr-name\">rowCount</span><span class=\"token script language-javascript\"><span class=\"token script-punctuation punctuation\">=</span><span class=\"token punctuation\">{</span>list<span class=\"token punctuation\">.</span><span class=\"token property-access\">length</span><span class=\"token punctuation\">}</span></span>\n\t        <span class=\"token attr-name\">rowHeight</span><span class=\"token script language-javascript\"><span class=\"token script-punctuation punctuation\">=</span><span class=\"token punctuation\">{</span><span class=\"token number\">20</span><span class=\"token punctuation\">}</span></span>\n\t        <span class=\"token attr-name\">rowRenderer</span><span class=\"token script language-javascript\"><span class=\"token script-punctuation punctuation\">=</span><span class=\"token punctuation\">{</span>rowRenderer<span class=\"token punctuation\">}</span></span>\n\t\t\t\t\t<span class=\"token attr-name\">overscanRowCount</span><span class=\"token script language-javascript\"><span class=\"token script-punctuation punctuation\">=</span><span class=\"token punctuation\">{</span><span class=\"token number\">5</span><span class=\"token punctuation\">}</span></span> <span class=\"token comment\">// prefetch next N items to be shown</span>\n\t      <span class=\"token punctuation\">/&gt;</span></span>\n\t    <span class=\"token punctuation\">)</span><span class=\"token punctuation\">}</span><span class=\"token plain-text\">\n\t  </span><span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;/</span><span class=\"token class-name\">AutoSizer</span></span><span class=\"token punctuation\">&gt;</span></span>\n\t<span class=\"token punctuation\">)</span><span class=\"token punctuation\">;</span>\n<span class=\"token punctuation\">}</span><span class=\"token punctuation\">;</span>\n</code></pre>\n<p>With this, we will always show the number of items needed to fill the client&#x27;s screen, and we will always have the next 5 items pre-loaded to be displayed if the user scrolls to see more records. This makes the rendering of many elements more performant.</p>\n<h2>Bundle analyzer with NextJS</h2>\n<p>When we generate our build for production, it can get very heavy and get in the way of other steps in the deployment. But, how can we solve this? How about we analyze the size of our bundle and identify which modules have the largest size so we can act upon this and optimize our deployment? This is possible and it&#x27;s very easy to apply in a NextJS application! Let&#x27;s see how to do it in practice 😉</p>\n<h3>Hands on</h3>\n<p>Installing the library:</p>\n<pre class=\"language-bash\"><code class=\"language-bash\"><span class=\"token function\">yarn</span> <span class=\"token function\">add</span> @next/bundle-analyzer\n</code></pre>\n<p>In the root of your project, create a file called next.config.js with the following information:</p>\n<pre class=\"language-js\"><code class=\"language-js\"><span class=\"token keyword\">const</span> withBundleAnalyzer <span class=\"token operator\">=</span> <span class=\"token function\">require</span><span class=\"token punctuation\">(</span><span class=\"token string\">&#x27;@next/bundle-analyzer&#x27;</span><span class=\"token punctuation\">)</span><span class=\"token punctuation\">(</span><span class=\"token punctuation\">{</span>\n\t<span class=\"token literal-property property\">enabled</span><span class=\"token operator\">:</span> process<span class=\"token punctuation\">.</span><span class=\"token property-access\">env</span><span class=\"token punctuation\">.</span><span class=\"token constant\">ANALYZE</span> <span class=\"token operator\">===</span> <span class=\"token string\">&#x27;true&#x27;</span><span class=\"token punctuation\">,</span>\n<span class=\"token punctuation\">}</span><span class=\"token punctuation\">)</span><span class=\"token punctuation\">;</span>\n\nmodule<span class=\"token punctuation\">.</span><span class=\"token property-access\">exports</span> <span class=\"token operator\">=</span> <span class=\"token function\">withBundleAnalyzer</span><span class=\"token punctuation\">(</span><span class=\"token punctuation\">{</span><span class=\"token punctuation\">}</span><span class=\"token punctuation\">)</span><span class=\"token punctuation\">;</span>\n</code></pre>\n<p>Now, to analyze the bundle generated in your project build, just run the following command in your terminal:</p>\n<pre class=\"language-bash\"><code class=\"language-bash\"><span class=\"token assign-left variable\">ANALYZE</span><span class=\"token operator\">=</span>true <span class=\"token function\">yarn</span> build\n</code></pre>\n<p>The command will open a window in your browser to show you which packages weigh the most in your bundle.</p>\n<h2>Finishing up</h2>\n<p>I hope you have enjoyed this content and that you have learned something to take you to the next level and perform your projects.</p>\n<p>This post took a few hours to complete and if you have any questions, leave them in the comments below and I or any other member that knows the answer will answer them as soon as possible.</p>\n<p>Finally, here are some references for you to further explore this performance-oriented content in React:</p>\n<ul>\n<li><a href=\"https://blog.logrocket.com/react-pure-components-functional/#whatisareactpurecomponent\">Pure functional components</a>;</li>\n<li><a href=\"https://reactjs.org/docs/code-splitting.html\">Code splitting</a>;</li>\n<li><a href=\"https://github.com/bvaughn/react-virtualized\">react-virtualized</a>;</li>\n<li><a href=\"https://www.npmjs.com/package/@next/bundle-analyzer\">bundle-analyzer</a>;</li>\n</ul>",
            "url": "https://jopcmelo.dev/articles/optimizing-react-components",
            "title": "Optimizing ReactJS components",
            "summary": "Understand how to optimize ReactJS components using hooks the right way.",
            "date_modified": "2021-06-19T00:00:00.000Z",
            "author": {
                "name": "João Melo"
            }
        },
        {
            "id": "https://jopcmelo.dev/articles/understanding-react-renderings",
            "content_html": "<h2>Main causes of renderings</h2>\n<p>Today we’re going to get a better understanding of the main rendering concepts within React. For that, we need to understand what are the main causes that cause a component to be rendered.</p>\n<p>Let&#x27;s start this journey!</p>\n<h3>Parent to children</h3>\n<p>Whenever the parent component has a new rendering (be it for any reason like change of state, context, called the API, etc ...), the child component will automatically be rendered.</p>\n<h3>Property</h3>\n<p>When any component property has a changed value, that component is rendered again.</p>\n<h3>Hooks</h3>\n<p>When we call a hook in which it has a data-altering effect (useState, useContext, useReducer, etc...), the component responsible for the call is also rendered again.</p>\n<h2>Render flow steps</h2>\n<p>Now that we know the main reasons why React renders a component, let&#x27;s understand how React does it.</p>\n<p>Let&#x27;s imagine that one of the situations mentioned above happened in a component. Now let&#x27;s see the step by step that React would do to render the updated component:</p>\n<ol>\n<li>Generate a new version of the component that needs to be rendered (Virtual DOM, saved in memory and is a representation of that DOM that is saved in memory);</li>\n<li>Compare the new version with the previous version already saved on the page;</li>\n<li><a href=\"https://reactjs.org/docs/reconciliation.html\">If there are changes</a>, React <a href=\"https://reactjs.org/docs/rendering-elements.html#react-only-updates-whats-necessary\">&quot;renders&quot;</a> (transforms the Virtual DOM representation into HTML, this happens only where React identified changes) this new screen version;</li>\n</ol>\n<h3>Why not check if the current HTML is different from the new one?</h3>\n<p>Assuming we have the following list structure in a list component:</p>\n<pre class=\"language-html\"><code class=\"language-html\"><span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;</span>ul</span><span class=\"token punctuation\">&gt;</span></span>\n\t<span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;</span>li</span> <span class=\"token attr-name\">className</span><span class=\"token attr-value\"><span class=\"token punctuation attr-equals\">=</span><span class=\"token punctuation\">&quot;</span>1<span class=\"token punctuation\">&quot;</span></span><span class=\"token punctuation\">&gt;</span></span>1<span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;/</span>li</span><span class=\"token punctuation\">&gt;</span></span>\n\t<span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;</span>li</span> <span class=\"token attr-name\">className</span><span class=\"token attr-value\"><span class=\"token punctuation attr-equals\">=</span><span class=\"token punctuation\">&quot;</span>2<span class=\"token punctuation\">&quot;</span></span><span class=\"token punctuation\">&gt;</span></span>2<span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;/</span>li</span><span class=\"token punctuation\">&gt;</span></span>\n\t<span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;</span>li</span> <span class=\"token attr-name\">className</span><span class=\"token attr-value\"><span class=\"token punctuation attr-equals\">=</span><span class=\"token punctuation\">&quot;</span>3<span class=\"token punctuation\">&quot;</span></span><span class=\"token punctuation\">&gt;</span></span>3<span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;/</span>li</span><span class=\"token punctuation\">&gt;</span></span>\n    <span class=\"token comment\">&lt;!-- ...N --&gt;</span>\n\t<span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;</span>li</span> <span class=\"token attr-name\">className</span><span class=\"token attr-value\"><span class=\"token punctuation attr-equals\">=</span><span class=\"token punctuation\">&quot;</span>N<span class=\"token punctuation\">&quot;</span></span><span class=\"token punctuation\">&gt;</span></span>N<span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;/</span>li</span><span class=\"token punctuation\">&gt;</span></span>\n<span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;/</span>ul</span><span class=\"token punctuation\">&gt;</span></span>\n</code></pre>\n<p>Imagine that a customer deleted the item from className=&quot;532&quot;. For React, when it does the new rendering, it will:</p>\n<ol>\n<li>Compare the two HTML trees and you will notice that item 532 is not in the new generated tree (Virtual DOM);</li>\n<li>It will render the entire list with N elements, which can cost a lot of processing on the client side (or on the server, if the solution used occurs on the server side);</li>\n<li>With the reconciliation algorithm, React uses this technique to find elements that have changed during the comparison. With that, it will understand that only that component should be changed. This happens not only for a removal of an element from HTML, but any changes related to it, be it some altered attribute, stylization, addition of new components, etc.</li>\n</ol>\n<h2>The best tool to analyze renderings in React</h2>\n<p>If you don&#x27;t already know the React DevTools browser extension, you need to know it now! This tool gives you &quot;super powers&quot; to analyze your ReactJS applications.</p>\n<p>We will address the main features that it provides us and why we should use them.</p>\n<p>First of all, know that this extension exists for several browsers, such as Google Chrome, Firefox, Microsoft Edge, etc. So, I will leave the installation link only for Google Chrome (since it is the most used browser), but be aware that searching the internet you can find the installation link for your browser without any problems.</p>\n<p><a href=\"https://chrome.google.com/webstore/detail/react-developer-tools/fmkadmapgofadopljbjfkapdkoienihi\">Link to install on Google Chrome</a></p>\n<h3>Using React DevTools extension</h3>\n<p>Once installed on your browser, just your browser&#x27;s developer console and you will notice that the extension added two new tabs: <strong>&quot;Components&quot;</strong> and <strong>&quot;Profiler&quot;</strong>.</p>\n<p>Now, let&#x27;s cover each of the tabs added by the extension.</p>\n<h3>Components tab:</h3>\n<p>Here it is possible to inspect each element that we have in our applications.</p>\n<p>Within each component, we can see:</p>\n<ol>\n<li>Its properties;</li>\n<li>Who is rendering it (parent component) by clicking on a component in the displayed component tree;</li>\n</ol>\n<p>To highlight components that are rendered in the Virtual DOM due to diffing checks, click on the gear icon → General → Enable the <strong>&quot;Highlight updates when components render&quot;</strong> option.</p>\n<img alt=\"Components tab screenshot\" loading=\"lazy\" width=\"564\" height=\"240\" decoding=\"async\" data-nimg=\"1\" style=\"color:transparent\" srcSet=\"/_next/image?url=%2F_next%2Fstatic%2Fmedia%2Fimage-1.e648348e.webp&amp;w=640&amp;q=75 1x, /_next/image?url=%2F_next%2Fstatic%2Fmedia%2Fimage-1.e648348e.webp&amp;w=1200&amp;q=75 2x\" src=\"/_next/image?url=%2F_next%2Fstatic%2Fmedia%2Fimage-1.e648348e.webp&amp;w=1200&amp;q=75\"/>\n<h3>Profiler tab</h3>\n<p>It serves to understand why a component was rendered. To enable this functionality, click on the gear icon → Profiler → Enable the <strong>&quot;Record why each component rendered while profiling&quot;</strong> option.</p>\n<img alt=\"Profiler tab screenshot\" loading=\"lazy\" width=\"508\" height=\"200\" decoding=\"async\" data-nimg=\"1\" style=\"color:transparent\" srcSet=\"/_next/image?url=%2F_next%2Fstatic%2Fmedia%2Fimage-2.63d91e5e.webp&amp;w=640&amp;q=75 1x, /_next/image?url=%2F_next%2Fstatic%2Fmedia%2Fimage-2.63d91e5e.webp&amp;w=1080&amp;q=75 2x\" src=\"/_next/image?url=%2F_next%2Fstatic%2Fmedia%2Fimage-2.63d91e5e.webp&amp;w=1080&amp;q=75\"/>\n<p>By default, the Profiler is recording the behavior of the components as soon as the page is loaded. To stop recording and see the results, we need to click on the recording icon (ball) at the top left of DevTools.</p>\n<p>After stopping recording, we will see a result with the reasons why a component was rendered, see an example:</p>\n<img alt=\"Recording result screenshot\" loading=\"lazy\" width=\"506\" height=\"348\" decoding=\"async\" data-nimg=\"1\" style=\"color:transparent\" srcSet=\"/_next/image?url=%2F_next%2Fstatic%2Fmedia%2Fimage-3.a44052d5.webp&amp;w=640&amp;q=75 1x, /_next/image?url=%2F_next%2Fstatic%2Fmedia%2Fimage-3.a44052d5.webp&amp;w=1080&amp;q=75 2x\" src=\"/_next/image?url=%2F_next%2Fstatic%2Fmedia%2Fimage-3.a44052d5.webp&amp;w=1080&amp;q=75\"/>\n<h2>Conclusion</h2>\n<p>That&#x27;s all, folks! Today we learn advanced rendering concepts in React and we also know React DevTools, a super powerful tool that we can use to measure performance and understand what happens behind the scenes in our React applications.</p>\n<p>I hope you guys enjoyed this content and we’re leaving next week! Peace out!</p>",
            "url": "https://jopcmelo.dev/articles/understanding-react-renderings",
            "title": "Understanding React renderings",
            "summary": "Understand advanced React rendering concepts and learn powerful tools to analyze the performance of your application.",
            "date_modified": "2021-05-21T00:00:00.000Z",
            "author": {
                "name": "João Melo"
            }
        }
    ]
}