<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Samuel Guo on Medium]]></title>
        <description><![CDATA[Stories by Samuel Guo on Medium]]></description>
        <link>https://medium.com/@guosamuel1114?source=rss-71ed97db9a59------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*9V5bhaUHU2RJDpWclhfXRw.png</url>
            <title>Stories by Samuel Guo on Medium</title>
            <link>https://medium.com/@guosamuel1114?source=rss-71ed97db9a59------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 08:24:15 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@guosamuel1114/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[An Introduction to Linked Lists]]></title>
            <link>https://medium.com/better-programming/an-introduction-to-d1957df2f406?source=rss-71ed97db9a59------2</link>
            <guid isPermaLink="false">https://medium.com/p/d1957df2f406</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[linked-lists]]></category>
            <category><![CDATA[data-structures]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Samuel Guo]]></dc:creator>
            <pubDate>Sun, 15 Mar 2020 02:17:01 GMT</pubDate>
            <atom:updated>2020-03-17T15:32:15.196Z</atom:updated>
            <content:encoded><![CDATA[<h4>What are linked lists and what should we use them for?</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XpV61fs6dtQPjuEuCHRVYQ.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@timberfoster?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Tim Foster</a> on <a href="https://unsplash.com/s/photos/patterns?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><h3>Background</h3><p>Over the past few days, I’ve been studying data structures. This time, rather than a niche data structure, we’ll dive into the more common linked list.</p><p>There are two types of linked lists: single and double. As this is intended as an introduction to data structures, we’ll focus on the easier one — singly-linked lists. If you are able to understand singly-linked lists, doubly linked lists will come naturally to you. For the purposes of clarity in this blog, a linked list is the same as a singly linked list, unless otherwise stated.</p><h3>What is a Linked List?</h3><p>According to Wikipedia,</p><blockquote>In <a href="https://en.wikipedia.org/wiki/Computer_science">computer science</a>, a <strong>linked list</strong> is a linear collection of data elements, whose order is not given by their physical placement in memory. Instead, each element <a href="https://en.wikipedia.org/wiki/Pointer_(computer_programming)">points</a> to the next. It is a <a href="https://en.wikipedia.org/wiki/Data_structure">data structure</a> consisting of a collection of <a href="https://en.wikipedia.org/wiki/Node_(computer_science)">nodes</a> which together represent a <a href="https://en.wikipedia.org/wiki/Sequence">sequence</a>. In its most basic form, each node contains: <a href="https://en.wikipedia.org/wiki/Data_(computing)">data</a>, and a <a href="https://en.wikipedia.org/wiki/Reference_(computer_science)">reference</a> (in other words, a <em>link</em>) to the next node in the sequence.</blockquote><p>If that just confused you more, don’t worry about it. We’re going to break each sentence down and unravel what it all means.</p><h3>A Linked List Has no Order in Memory</h3><p>Let’s start with the first sentence,</p><blockquote>In <a href="https://en.wikipedia.org/wiki/Computer_science">computer science</a>, a <strong>linked list</strong> is a linear collection of data elements, whose order is not given by their physical placement in memory.</blockquote><p>Some visuals to help us grasp this sentence:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/829/1*mkiVuw-gG5Qg_N3b88RMyw.png" /><figcaption>Physical Memory</figcaption></figure><p>This 10x5 grid is a representation of physical memory. It represents the physical memory of a computer, with the numbers standing for locations of memory. These particular numbers are strictly for illustration purposes (i.e. this is not how physical memory is numbered).</p><p>When the sentence says “their physical placement in memory,” it means that literally. So for example, if I have an array that has a length of five, [“A”, “B&quot;, “C&quot;, “D&quot;, “E&quot;] the array would take up five slots of memory in the physical memory. The physical memory will now look like the following:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/829/1*LzghDidBfFUxI8BNCXx07A.png" /><figcaption>Physical Memory of Array</figcaption></figure><p>The array took up five slots of memory, each element taking up one slot. “A” takes up slot one, “B” takes up slot two, “C” takes up slot 3, etc. By the nature of an array, this is <em>ordered</em> because it follows the sequential order of the slots in memory. This is necessary because the order in an array matters due to accessing an element via index. If I had a separate array that was [&quot;E&quot;, &quot;D&quot;, &quot;A&quot;, &quot;B&quot;, &quot;C&quot;] , this would be different than the array shown above because this array would be in a different place in memory (i.e., slots 1–5 are already occupied so that array would occupy different slots).</p><p>So what does it mean to be <em>unordered</em>? This means that there is no sequential order in memory to store the data. A linked list can be represented by the following: Z -&gt; Y -&gt; X -&gt; W . In regards to physical memory, look at the figure below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/819/1*-CqqO-WRsjlEAcarJxjK2A.png" /><figcaption>Physical Memory of an Array and Linked List</figcaption></figure><p>The physical memory of “Z” is in slot 22, “Y” in slot 34, “X” in slot 16, and “W” in slot 49. If you follow this sequence, the slots in memory are represented as 22 -&gt; 34 -&gt; 16 -&gt; 49 . There’s no order to this. Each slot represents a single value of the linked list with its respective pointer.</p><h3>Elements of a Linked List</h3><p>Other than the value, what else does an element of a linked list contain?</p><blockquote>Instead, each element <a href="https://en.wikipedia.org/wiki/Pointer_(computer_programming)">points</a> to the next.</blockquote><p>Essentially, a linked list contains two pieces of data: the value that it holds and a pointer that points to the next element.</p><p>The pointer is how a linked list knows what is the next element in its sequence. It points to the next location or slot in memory for the next element. When it reaches the end of the sequence, the pointer will typically point to null.</p><p>The pointer in a linked list is analogous to an index for an array. When you access an element in an array, you use its index because the index “points” to that element.</p><p>To update the visuals for a linked list, I’m going to represent each element in the linked list as an object with two keys: val and next. val represents the value in the memory and next is the pointer that will point to the next element in memory of the linked list sequence.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/829/1*uYPztM6BxEAzZOiGG2C3jQ.png" /><figcaption>Updated Linked List in Memory</figcaption></figure><p>Notice how an element only points to the next element. This implies that when you traverse a linked list, you can only traverse it in one direction (i.e., only forward).</p><h3>Nodes and Sequence</h3><p>For the last two sentences, they go together.</p><blockquote>It is a <a href="https://en.wikipedia.org/wiki/Data_structure">data structure</a> consisting of a collection of <a href="https://en.wikipedia.org/wiki/Node_(computer_science)">nodes</a> which together represent a <a href="https://en.wikipedia.org/wiki/Sequence">sequence</a>. In its most basic form, each node contains: <a href="https://en.wikipedia.org/wiki/Data_(computing)">data</a>, and a <a href="https://en.wikipedia.org/wiki/Reference_(computer_science)">reference</a> (in other words, a <em>link</em>) to the next node in the sequence.</blockquote><p>At this point, the concept of a linked list is established and this is more about clarifying terminology.</p><p>A node contains data and a reference. As I mentioned in the previous section, the data can also be the val in the object and the reference can also be the next. The object is called a node .</p><p>A sequence is a collection of nodes. Recall how I used Z -&gt; Y -&gt; X -&gt; W as an example. This is how a sequence is typically represented.</p><p>Great — you now have a basic understanding of a linked list! But what’s so great about it?</p><h3>Major Benefit of a Linked List</h3><p>The major benefit of a linked list is that inserting or deleting a node does not require reorganizing or reallocating memory. This is due to the nature of a linked list being unordered. You can insert a node anywhere in the physical memory that has the open space for it. This does not need to be localized, unlike an array.</p><p>A node is “deleted” by reassigning the pointer of the previous node to the next node that is after the “deleted” node. The reason why I quoted deleted is that the node won’t exist in the sequence anymore but will still be in memory with nothing referencing to it.</p><p>When you insert a node in a linked list, you typically don’t choose where in memory to store that node, similar when you instantiate an array.</p><h3>Major Disadvantage of a Linked List</h3><p>The major disadvantage of a linked list is traversing through the sequence to find a specific value. Since the nodes are scattered throughout the physical memory, there is no easy access to a specific node, unlike an array by accessing its elements via index.</p><p>When you are given a linked list, typically the only access you have is its head. The head is the first node of the linked list. From the head, you will need to start traversing by going through each node until you find the node you need.</p><h3>Doubly Linked List</h3><p>If you were able to follow everything up to this point, awesome! This means that you already understand 95% of what a doubly-linked list is. A doubly linked list is a sequence of nodes that have two references/pointers, one that points to the next node and one that points to the previous node. In a singly linked list, each node only has one pointer, which points to the next node.</p><p>A doubly linked list has nodes with two pointers, so you can traverse the linked list in both directions (i.e., forward and backward).</p><p>To represent this in our diagram, I am going to create the following doubly linked list: L &lt;-&gt; M &lt;-&gt; N &lt;-&gt; P &lt;-&gt; Q . Each node will be represented with three key-value pairs: val to represent the value, next to represent the memory location of the next node and prev to represent the memory location of the previous node. As for the head of the doubly linked list, I will default the previous node to null.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/820/1*4HznJCsTK2mXXrn_VxKJyQ.png" /><figcaption>Physical Memory of an Array, Singly Linked List, and Doubly Linked List</figcaption></figure><p>There you have it!</p><h3>Conclusion</h3><p>Now that you have a basic understanding of a singly and doubly linked list! If you’re a budding, new developer, linked lists are a data structure that you will definitely need to understand for interviews and whiteboarding.</p><p>Thanks for reading!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d1957df2f406" width="1" height="1" alt=""><hr><p><a href="https://medium.com/better-programming/an-introduction-to-d1957df2f406">An Introduction to Linked Lists</a> was originally published in <a href="https://betterprogramming.pub/">Better Programming</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[An Introduction to Binary Heaps]]></title>
            <link>https://levelup.gitconnected.com/an-introduction-to-binary-heaps-c95b3025977?source=rss-71ed97db9a59------2</link>
            <guid isPermaLink="false">https://medium.com/p/c95b3025977</guid>
            <category><![CDATA[insertion]]></category>
            <category><![CDATA[data-structures]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[extraction]]></category>
            <category><![CDATA[binary-heap]]></category>
            <dc:creator><![CDATA[Samuel Guo]]></dc:creator>
            <pubDate>Mon, 09 Mar 2020 03:49:36 GMT</pubDate>
            <atom:updated>2020-03-09T16:45:01.142Z</atom:updated>
            <content:encoded><![CDATA[<h3>Background</h3><p>Time for another introduction to a niche data structure! For this blog, this will be on binary heaps. If you are familiar with binary search trees, this data structure will look very familiar. If not, don’t worry, we’ll be going step by step on the concept of binary heaps.</p><h3>What Is A Heap?</h3><p>Before we dive into binary heaps, we should understand what a heap is in general. A heap is a tree-like data structure where there is a relationship between the parent and child nodes. The figure below is an example of a heap.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/740/1*hrTegmb_97-cVaXFb08Xew.png" /><figcaption>Heap Example</figcaption></figure><p>In this heap example, the relationship between the parent and child is the parent is always greater than all of its children. The parent node, 100, has two children, 90 and 80. 100 is greater than 90 and 80. The parent node, 90, has three children, 40, 50, and 1. 90 is greater than 40, 50, and 1.</p><p>The relationship across children with different parents <em>do not matter</em>. Let’s take a look at the parent 80. It only has one child, 10. Although 10 is greater than 1, but 1 is a child of the parent 90, this is still technically a heap. We only care about the relationship directly between the parent and children.</p><p>The heap example can also be called a max heap. This implies the parent is greater than all of its children. Due to this implication, the largest number will always be at the top of the heap, which is also called the root. In this example, 100, will be the root of this max heap.</p><p>In a similar way, a min heap implies the parent is less than all of its children. Due to this implication, the smallest number will always be at the top of the heap.</p><p>Now that we have a basic understanding of heaps, we can dive into binary heaps.</p><h3>What Is A Binary Heap?</h3><p>A binary heap is a heap where each parent has, at most, two (2) children (hence the “binary” in binary heap). In the previous heap example, that would be a standard heap because the parent, 90, had three children and the parent, 80, had one child.</p><p>Using the same numbers as before, the figure below shows what a binary heap looks like.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/651/1*CfAMqWfiekSpa11lQ4fmzw.png" /><figcaption>Binary Heap Example</figcaption></figure><p>In the binary heap example, each parent has two children. The parent, 100, has two children, 90 and 80. The parent, 90, has two children, 40 and 50. The parent, 80, has two children, 1 and 10.</p><p>The parent-child relationship is that the parent is greater than all of their children, which makes this a max binary heap.</p><p>A major constraint, which is heavily implied, is that binary heaps are <em>complete</em>. Complete means the tree is filled properly at all levels. From a shape perspective, this means spaces are filled, starting from left to right, at each level.</p><p>The screenshot below shows what it means for a heap to be incomplete.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/799/1*Jq9pw-rWkR9DDhautyfmEQ.png" /><figcaption>Incomplete Heap Example</figcaption></figure><p>There is an empty spot on the third level where 50, 1, and 10 are populated. The 40 started a new level, the fourth level, when there was an empty spot for it to be the second child of 90.</p><p>Typically for trees, we would represent that data structure using linked lists (e.g., binary search trees). However, due to the important constraint of a binary heap being complete, we can represent this data structure as an array.</p><p>In the binary heap example, it can be represented by the following array below:</p><pre>[100, 90, 80, 40, 50, 1, 10]</pre><p>But wait, how do you determine which parents have which children in the array form?</p><h3>Binary Heaps as an Array</h3><p>The secret is the index.</p><p>Let’s break down using the same binary heap example.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/760/1*mBouzzNUip5VbluAOjC2_g.png" /></figure><p>In the figure above, I am using the same binary heap. The red background represents the current parent we are looking at and the green background represents the children of the current parent. Here, the parent index is at 0 whereas the children are at index 1 and 2. There doesn’t seem to be much of a pattern to pick up from this yet but let’s keep track of it.</p><pre>Parent-Child Tracker<br>0 =&gt; 1, 2</pre><p>Let’s move onto the next parent, 90.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/780/1*zpTZtO_B09ddarOVXsPPxQ.png" /></figure><p>The parent is on index 1 and the children are on indices 3 and 4.</p><pre>Parent-Child Tracker<br>0 =&gt; 1, 2<br>1 =&gt; 3, 4</pre><p>Now, let’s do the last parent, 80.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/771/1*ZmBdY9ELbHhEc-T09yxoXg.png" /></figure><p>The parent is on index 2 and the children are on indices 5 and 6.</p><pre>Parent-Child Tracker<br>0 =&gt; 1, 2<br>1 =&gt; 3, 4<br>2 =&gt; 5, 6</pre><p>Hmmm, it looks like the relationship from parent to child is:</p><pre>childIndex = 2n+1 or 2n+2</pre><p>Where n represents the index of the parent. The left child would use 2n+1 whereas the right child would use 2n+2 .</p><p>But what if the index we have is a child and we want to find its parent?</p><p>The relationship from child to parent is:</p><pre>parentIndex = Math.floor((n-1)/2)</pre><p>Where n represents the index of the child.</p><p>Now we understand the relationship between child and parent for a binary heap in an array form!</p><h3>Insertion</h3><p>Although I won’t be diving into the code, I want to explain the concept of insertion and extraction of binary heaps.</p><p>For insertion, you can insert a new node into the existing binary heap. After the insertion, the binary heap may need to reorganize itself in order to maintain the relationship between parent and child.</p><p>To give a sense of insertion, let’s insert 95 into the example.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/746/1*WNYrsNCQSpkA90WXM6JG8w.png" /><figcaption>Inserting the 95 into the binary heap</figcaption></figure><p>Recall that binary heaps are complete. When we insert a new node, the heap is filled from left to right. Since there are no empty spots on the right most side on the third level, we would start a new level for the 95.</p><p>Next we need to check that the relationship between parent and child has been maintained. This is when the reorganization comes in. Since this is a max binary heap, the relationship is the parent must be greater than all of its children. The 95, which is a child of 40, is greater than its parent. Therefore we would need to swap the positions of 40 and 95.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/789/1*uqSGenC4NCL-mMzzo4fj1A.png" /><figcaption>Swapping the 40 and 95</figcaption></figure><p>Now, the 95 is the parent of the 40. Next, we check 95’s new parent, which is 90 in this case. If the new parent is less than 95, swap their positions. If not, then we are done reorganizing the binary heap. We keep repeating this process until the parent is greater than the node we’ve inserted or it reaches all the way to the root and becomes the new root.</p><p>Since 90 is less than 95, we need to swap their positions.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/786/1*rp66kd8WEuCaL8P-8afIqQ.png" /><figcaption>Swapping the 90 and 95</figcaption></figure><p>95’s new parent is 100, which is greater than 95. We can finally stop reorganizing the heap. The figure above is now our updated binary heap. With this updated binary heap, the array should now look like the following:</p><pre>[100, 95, 80, 90, 50, 1, 10, 40]</pre><p>As a quick sanity check, let’s use the parent-child formulas to see if this array is accurate using 95 as the example.</p><p>If 95 is the parent, then its children are 90 and 50. If 95 is the child, then its parent is 100. 95 is at index 1.</p><pre>Reference Index: n = 1<br>Left Child Index: 2n+1 = 2(1)+1 = 3<br>Right Child Index: 2n+2 = 2(1)+2 = 4<br>Parent Index: Math.floor((1-1)/2) = Math.floor((1-1)/2) = Math.floor(0/2) = 0</pre><p>Looks like everything checks out!</p><h3>Extraction</h3><p>By the nature of binary heaps, either the smallest number (i.e., min binary heaps) or the largest number (i.e., max binary heaps) will be the root. The main purpose of binary heaps, or heaps in general, is finding the maximum or minimum number. Since that number will always be at the root, this gives us a time complexity of O(1).</p><p>After using that number, it should be extracted, or removed, from the binary heap. However, now that the old root has been removed, how do we know which number in the heap should be the new root? It’s very similar to how insertion works.</p><p>In insertion, we “bubbled up” from the bottom of the heap to its appropriate position that maintained the proper parent child relationship. In extraction, we will “propagate” from the top of the heap to its appropriate position. We are going to use the same methodology as insertion except it will be going in the opposite direction.</p><p>To provide visuals, let’s extract 100 from our example. During the extraction process, we will swap the last node with the root before propagating through the heap. The last figure used will be where we start.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/770/1*58GfI9Igqki55wKzXUwi8Q.png" /><figcaption>Swapped the 40 and 100</figcaption></figure><p>In the figure above, 100, the old root, was swapped with 40. Next, we shall extract 100 from the heap. There are two reasons we would do this:</p><ol><li>This guarantees that the binary heap will still be complete.</li><li>Removing the last node from an array has a time complexity of O(1).</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/689/1*tQEn4eWOqKEp2ihXCEG8ng.png" /><figcaption>Removed the old root (100)</figcaption></figure><p>Next, we used the same methodology from insertion. We shall compare the parent, starting at the root, and confirm if the relationship between parent and child are maintained. If so, no action needs to be done. If not, then we need to swap the positions of the parent and child and start the process again with the new position.</p><p>If both children are larger than the parent, then swap with the larger child.</p><p>Starting at the new root of 40, this parent is smaller than both its children, 95 and 80. This means that 40 should be swapped with 95.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/703/1*v8nWBhlP0YCAlIDLBNxS0A.png" /><figcaption>Swapped the 40 and 95</figcaption></figure><p>Now, 40’s new children are 90 and 50. Both children are still larger than 40, which means 40 and 90 will need to be swapped.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/688/1*gnC1GvE-mm6SEyEA9yaIIQ.png" /><figcaption>Swapped 40 and 90. Final updated heap.</figcaption></figure><p>Now, if we check each and every parent child relationship in this updated heap, it satisfies the relationship where the parent is larger than both its children. The updated array should now look like the following:</p><pre>[95, 90, 80, 40, 50, 1, 10]</pre><p>As a quick sanity check, 95 is the largest number of the entire heap and is located in the root, as it should be.</p><h3>Conclusion</h3><p>Congratulations, now you understand binary heaps and its implementation! You understand how to insert a node/value into a binary heap while maintaining the parent-child relationship and how to update a binary heap after extracting its root.</p><p>If you want a challenge, try to create your own binary heap class with the insertion and extraction methods.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c95b3025977" width="1" height="1" alt=""><hr><p><a href="https://levelup.gitconnected.com/an-introduction-to-binary-heaps-c95b3025977">An Introduction to Binary Heaps</a> was originally published in <a href="https://levelup.gitconnected.com/">Level Up Coding</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Keeping Your Code DRY]]></title>
            <link>https://medium.com/better-programming/keeping-your-code-dry-1105377c9c80?source=rss-71ed97db9a59------2</link>
            <guid isPermaLink="false">https://medium.com/p/1105377c9c80</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[front-end-development]]></category>
            <category><![CDATA[nodejs]]></category>
            <dc:creator><![CDATA[Samuel Guo]]></dc:creator>
            <pubDate>Sat, 29 Feb 2020 21:14:53 GMT</pubDate>
            <atom:updated>2020-03-03T00:32:29.660Z</atom:updated>
            <content:encoded><![CDATA[<h4>Refactoring essentials</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ymfK0uoddsfn7JX-Q5znEA.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@franckinjapan?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Franck V.</a> on <a href="https://unsplash.com/s/photos/repeat?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><h3>Background</h3><p>This past week, the majority of my time was spent on working on a coding challenge. It was definitely tough, from understanding the user stories to wireframing out the application to implementing the code to debugging.</p><p>There was a lot of going back and forth between my components. I was slowly starting to realize that when I changed one part of my code, I would need to change all the other parts of the code that was dependent on it.</p><p>By having a downstream effect of manual changes from changing one part of my code, this was violating the DRY (Don’t Repeat Yourself) principle.</p><p>When you initially write out your code, this may happen a lot more than you think. Keeping your code DRY is part of the refactoring process, so if you don’t catch it right away, that’s not a problem.</p><h3>Keeping Your Code DRY Within a Component</h3><p>The first time I realized I wasn’t keeping my code DRY was when I had to make a log-in form. The gist below shows the code for my log-in form.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/72d8b3857d13dc6a784841c5ffbeb727/href">https://medium.com/media/72d8b3857d13dc6a784841c5ffbeb727/href</a></iframe><p>This is a generic form where you need to input your email and password. handleChange is the callback function that makes the form a controlled component.</p><p>If you are unfamiliar with a controlled component, it is essentially where the values from the React component are the same as what is shown on the DOM, adhering to the single source of truth principle.</p><p>Can you find where the code may not be DRY?</p><p>Hint: Take a look at the input attributes.</p><p>If you take a look at the input attributes and the switch/case statements, the strings “email” and “password” are repeated.</p><p>If you accidentally deleted a letter from those strings, the code will still compile, but now that would make debugging a nightmare when you need to send the email and password values to the back end.</p><p>Also, what if I decided to change my log-in form such that instead of using email as a credential, I wanted to use a username instead?</p><p>Now, I need to find all the places where “email” appears and change it to “username”. You might be thinking: “Wait, my text editor can find all instances of “name” and I can replace it all with “username” and call it a day.”</p><p>And I would say you are correct, but it doesn’t address the issue of any accidental errors mentioned in the previous paragraph.</p><p>So, how can this log-in form be DRY? You can save the repeated strings to a constant.</p><pre>const EMAIL = &quot;email&quot;<br>const PASSWORD = &quot;password&quot;</pre><p>This funnels all instances of those strings into a <em>single source of truth</em>, a constant. Please note that the constants are capitalized based on convention.</p><p>So now, if you replace all of the “email” and “password” strings with their respective constants, the code will look like the gist below.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5f6c7000a6de324db7d2bab9ebf739ed/href">https://medium.com/media/5f6c7000a6de324db7d2bab9ebf739ed/href</a></iframe><p>How does this adjudicate the issue of accidental errors? If you make an error with the constant name (e.g., EMAIL to EMAL), JavaScript will have a compilation error as the incorrect named constant is not defined.</p><p>If you make an error on the string, or the value of the constant, you can exactly pinpoint where the error is because there is only one line where that value is declared. This saves time and effort looking thoroughly through your code for potential minor errors.</p><h3>Keeping Your Code DRY Across Components</h3><p>So far, we talked about being DRY within a component. But what if the same values are used throughout multiple components?</p><p>Let’s bring in another component for demonstration purposes. We will be re-using the log-in form as well since we’re familiar with it at this point.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ca77c60aa96fcd93269b7828a1195439/href">https://medium.com/media/ca77c60aa96fcd93269b7828a1195439/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/aec1fab56021ba6696d4f37fad0ea335/href">https://medium.com/media/aec1fab56021ba6696d4f37fad0ea335/href</a></iframe><p>In the log-in form, the only thing I added was the first half of the fetch request that includes the URL. The rest of the fetch request will not be applicable to this topic.</p><p>In the Friends component, it makes a fetch request to the back end when the component is mounted to retrieve all of the friends associated with the user that has an ID of 1.</p><p>Notice how our code isn’t DRY as soon as I introduced the Friends component. But how?</p><p>If you look at the fetch request in both components, the URL uses the same domain: http://localhost:3001. Typically, domain names never change, which is a perfect application of pulling out the domain portion of the URL and saving it as a constant, just like what we did before!</p><p>But wait, this is across components, not within the same component. Assigning the domain portion of the URL to a variable and using it once within the same component is redundant.</p><p>So, how can we save the domain URL and use it across multiple components? In the same way as we do with libraries, we can import them! But instead of having a library of variables, we can create a file that holds all of the constants, and import them as needed.</p><p>So, first, let’s create the constants file and put the domain URL in it.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5b3529f85c12de5fa07626c5ed102c69/href">https://medium.com/media/5b3529f85c12de5fa07626c5ed102c69/href</a></iframe><p>Next, we import the DOMAIN constant in the files we need it in and then replace all instances of using http://localhost:3001 with DOMAIN.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3eadcb2e006ab1943a3d02366030456d/href">https://medium.com/media/3eadcb2e006ab1943a3d02366030456d/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1a1efdbe829bed8229521b7f8b3f45fa/href">https://medium.com/media/1a1efdbe829bed8229521b7f8b3f45fa/href</a></iframe><p>It was that easy keeping the code DRY across multiple components!</p><h3>Leveraging Constants.js</h3><p>At this point in the code, we made a separate file, Constants.js, to store constants that are used across multiple components.</p><p>The next question is this: “Do we want to use Constants.js to store constants that are only local to the component (e.g., the log-in form component) at this point in time?”</p><p>And the answer is…I don’t know. I can easily make the argument for both cases.</p><h4><strong>1. Storing all constants in Constants.js</strong></h4><p>By storing all constants in Constants.js, the file has only one responsibility. This also makes it easier to debug as the single source of truth for all constant values are in that file.</p><p>Scaleability will play a huge factor as well because if you were to create new components that use the same constants, we can directly import them and not have to worry about refactoring the component where the constants were first used at a local component level.</p><h4>2. <strong>Storing only constants in Constants.js that are used across multiple components</strong></h4><p>This implies that the constants used in the local component level will <em>only</em> be used for that component. This narrows the scope of where the constants are used.</p><p>If you see the same constant in a different component, that can indicate the constant is being used incorrectly or the component may not need the constant to begin with.</p><p>In both cases, I believe a design decision will need to be made before implementing code.</p><p>If you change your mind mid-implementation, you will need to parse through all your components and determine whether the constants should be at a local level or within the constants file.</p><h3>Conclusion</h3><p>Keeping your code DRY avoids code smells. It maintains clean and concise code with minimal effort when it comes to debugging and minimizes repetition.</p><p>Keep in mind that you do not have to apply the DRY principle in the way I did. I’m sure that there are other ways to go about keeping code DRY so, as long as you’re not repeating yourself, you’re on the right track!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1105377c9c80" width="1" height="1" alt=""><hr><p><a href="https://medium.com/better-programming/keeping-your-code-dry-1105377c9c80">Keeping Your Code DRY</a> was originally published in <a href="https://betterprogramming.pub/">Better Programming</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Data Structures: Improving Time Complexity on Stacks and Queues]]></title>
            <link>https://medium.com/better-programming/improving-time-complexity-on-stacks-and-queues-7396ab7b5a2b?source=rss-71ed97db9a59------2</link>
            <guid isPermaLink="false">https://medium.com/p/7396ab7b5a2b</guid>
            <category><![CDATA[big-o-notation]]></category>
            <category><![CDATA[arrays]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[data-structures]]></category>
            <dc:creator><![CDATA[Samuel Guo]]></dc:creator>
            <pubDate>Mon, 24 Feb 2020 04:40:42 GMT</pubDate>
            <atom:updated>2020-02-24T22:55:20.097Z</atom:updated>
            <content:encoded><![CDATA[<h4>How to use stacks and queues as your app scales</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Gkr_OjfkuzVvwduPRdzsDg.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@nooryounis?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">noor Younis</a> on <a href="https://unsplash.com/s/photos/time?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><h3>Background</h3><p>In my previous blog, I provided an introduction to a niche data structure called stacks and queues. If you are unfamiliar with it, please take a quick look at my blog <a href="https://medium.com/better-programming/stacks-and-queues-7c322b5f4e35"><em>Stacks and Queues</em></a>.</p><p>In a nutshell, stacks and queues follow the principle of first-in-last-out (stacks) and first-in-first-out (queues). However, for out-of-the-box JavaScript array methods, the time complexity for stacks is O(1) and the time complexity for queues is O(n).</p><p>Which led me to think, can we do better? Specifically, can we improve the time complexity for queues to be faster than O(n)?</p><h3>Inspiration</h3><p>Before we dive further, I would like to thank Rud, who introduced me to the concept of circular arrays to improve the time complexity for stacks and queues. My research on circular arrays was what inspired me to create my own stack and queue array class.</p><p>Although I am not diving deep into circular arrays for this blog, I am using the same principles I learned from studying circular arrays and leveraging them for my stack and queue array class.</p><h3>Stack and Queue Class Overview</h3><p>Before we dig too much into the weeds and code, let’s provide a general overview of how we’re going to create the StackQueueArray class.</p><p>For the stack portion, since the time complexity is O(1) with out-of-the-box Javascript array methods, I decided to keep using the same methods (i.e., .push() and .pop()). It doesn’t make sense to reinvent the wheel when it’s working perfectly fine, especially when its already optimized.</p><p>For the queue portion, that’s where I had to think outside the box. We will still be leveraging the .push() method but the .shift() method will need to change. After all, the .shift() method is the reason why the time complexity is O(n).</p><p>This is where leveraging principles from circular arrays come in. Based on my research, an implicit assumption made about circular arrays is that they have a fixed length.</p><p>Typically, a circular array has a pointer for the head and tail of the array. By keeping track of the pointers of where the head and tail are at all times, you can figure out if there is space in the array to add an additional element.</p><p>In other words, if the head and tail are <em>not</em> next to each other, then you can add the element.</p><p>However, in JavaScript, thanks to it being a dynamic language, we don’t have to worry about memory allocation. This dissuaded me from using circular arrays but inspired me to use a pointer to keep track of the head of the array.</p><p>We don’t need a pointer for the tail because the tail will always be the last element of the array.</p><p>So, how are we going to use a head pointer in conjunction with our custom .shift() method?</p><p>Let’s establish a new array with the StackQueueArray class and push some elements into them.</p><p>Don’t worry about the class methods for now as we will dive into detail about what those will be later. Recall that the .push() function will be the same as the out-of-box .push() function.</p><pre>let array = new StackQueueArray()<br>array.push(10)<br>array.push(20)<br>array.push(30)<br>console.log(array) // [10, 20, 30]</pre><p>In the StackQueueArray class, it will have an attribute called headIndex, which will be our head pointer. Currently, in array, the headIndex should be 0 because 10 was the first element push into the array as per the first-in principle.</p><pre>console.log(array.headIndex) // 0</pre><p>Now, with our custom .shift() method, we’re going to leverage another principle I learned from circular arrays.</p><p>In a circular array, whenever there was space between the head and tail pointers, the empty spaces were filled with null as placeholders. We’re going to do the same thing whenever we invoke our custom .shift() method.</p><p>When .shift() is invoked, it’ll swap the value at the headIndex with null, increase headIndex by 1 to assign the head pointer to the new head, and return the value.</p><p>So, in pseudo code, it will look like this:</p><pre>console.log(array) // [10, 20, 30]<br>console.log(array.headIndex) // 0<br>array.shift()<br>console.log(array) // [null, 20, 30]<br>console.log(array.headIndex) // 1</pre><p>Let’s really drive it home and invoke our custom .shift() method again to our current array to solidify what the method should be doing.</p><pre>array.shift() <br>console.log(array) // [null, null, 30]<br>console.log(array.headIndex) // 2</pre><p>Now that we have a more holistic understanding what the methods are supposed to do and the general idea of the class, let’s break it down into code.</p><p>Note: For the purposes of brevity and explanation, the code for the StackQueueArray class below will only take into account normal cases. There were many edge cases to consider, which I will go over in another section, and I will provide the complete code of the class at the end of this blog.</p><h3>Push and Pop Functions</h3><p>Let’s start with what we’ll need for the StackQueueArray class. We’re going to initialize an empty array and the headIndex.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/32786c1052ef4bd034541124775157a0/href">https://medium.com/media/32786c1052ef4bd034541124775157a0/href</a></iframe><p>So far, so good. We initialized the headIndex to null because the array is empty, so there is no need for a head pointer yet.</p><p>Next, let’s go into the .push() and .pop() functions. Recall that we will be leveraging the out-of-the-box methods that are already provided by JavaScript.</p><p>First, let’s do the .push() function.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b5919b799cb4b30210758f386af82220/href">https://medium.com/media/b5919b799cb4b30210758f386af82220/href</a></iframe><p>In the if statement, this only occurs when the array is empty. We would start the headIndex at 0 because when you push an element to an empty array, it will be at index 0.</p><p>Next, let’s do the .pop() function.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/57a2f10f782735cb729e3d5ee0c6c4a6/href">https://medium.com/media/57a2f10f782735cb729e3d5ee0c6c4a6/href</a></iframe><p>I am using the out-of-the-box .pop() function from JavaScript and using it as my own.</p><h3>Shift, Head, and Tail Functions</h3><p>Well, time for the hard part, making the custom .shift() function. For a normal case, let’s assume we already have [10, 20, 30] as our array. The headIndex is at 0 for this case.</p><p>The following are the three steps we need to do based on what I said in the “Stack and Queue Class Overview” section.</p><ol><li>Swap the value at the headIndex with null.</li><li>Increment the headIndex by 1.</li><li>Return the value at the previous headIndex (the value prior to incrementing headIndex).</li></ol><p>Since we need to return the value, we should save it in a separate variable.</p><p>For the sake of saving space, I am going to be working on the .shift() function separately and then inputting it into the class once it’s complete. The array and headIndex are still referenced from the previous code.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9500e4e711e22d971a70807631f9354b/href">https://medium.com/media/9500e4e711e22d971a70807631f9354b/href</a></iframe><p>Seems pretty good so far!</p><p>We can also include some helper functions to find what the head and tail are to alleviate the pain of parsing through the entire array.</p><p>Since we know the tail is always at the end of the array, we can use the length of the array as our reference point. For the head, we already have a head pointer, which is our headIndex.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7de0a499cba623474f7a36ee4a82df69/href">https://medium.com/media/7de0a499cba623474f7a36ee4a82df69/href</a></iframe><p>Great, now let’s add these methods to the StackQueueArray class!</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/35f8da1d8434fe70363538ea597cd1ff/href">https://medium.com/media/35f8da1d8434fe70363538ea597cd1ff/href</a></iframe><p>And viola! We’ve created the skeleton of the StackQueueArray class.</p><p>If you were able to follow along thus far, you’re more than halfway there! The next steps would be taking into account edge cases… and there are a lot of them.</p><p>If you want to challenge yourself, try to think of all the edge cases that could possibly happen with this class. This is especially good practice for code challenges and coding interviews since it is the developer’s responsibility to take into account all possible edge cases.</p><p>Personally, I don’t even know if I thought of all the edge cases myself.</p><h3>Edge Cases Galore</h3><p>There are six unique edge cases to consider. Some of these edge cases repeat in different methods.</p><p>The gist below shows the full code for the StackQueueArray class that I made. There is an additional method that I made, called cleanUp(), which I will explain later.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2329964c9b8d9d9160509a7c318b56a6/href">https://medium.com/media/2329964c9b8d9d9160509a7c318b56a6/href</a></iframe><h4>Edge case 1</h4><p>All of the elements are null. This typically occurs when .shift() is invoked all the way to the end of the array.</p><h4>Edge case 2</h4><p>There is only one non-null element in the array. This only occurs for the .pop() method because, after invoking it, the array will be empty, implying that headIndex should be null.</p><h4>Edge case 3</h4><p>The tail of the array is the last non-null element. This only occurs for the .pop() methods because after invoking it, we need to re-assign the headIndex by decrementing it by 1.</p><p>If we don’t decrement it, the headIndex will be outside the scope of the array itself.</p><h4>Edge case 4</h4><p>The array is either empty or all elements in the array are null.</p><h4>Edge case 5</h4><p>No parameter was used for the .push() method. This is geared towards user error where they may have forgotten to put in a value or decided to put in null as a value.</p><p>Without a parameter, .push() will push undefined into the array. Pushing undefined or null into the array will break the class and also violates the basis of a stack and queue data structure.</p><p>Before we jump into edge case 6, let me explain the purpose of the .cleanUp() method.</p><h3>cleanUp() Method</h3><p>I made .cleanUp() with the thought of what happens if you only invoke the .push() and .shift() methods multiple times. For example, the array could look like it has a bunch of null values and two non-null values at the end.</p><pre>console.log(array) <br>// [null, null, null, null, null, null, null, null, null, 10, 20]</pre><p>As mentioned before, the null values just represent a place holder for where the previous heads used to be. We don’t really care about these null values anymore.</p><p>But what if you have a memory requirement or you’re running out of memory to store this array?</p><p>This is where the inspiration for the .cleanUp() method came from. We can invoke this method to shorten our array to take up less memory by removing all the null values.</p><p>So, in pseudo code, it’ll look like the following:</p><pre>array.cleanUp()<br>console.log(array) // [10, 20]</pre><p>However, this introduces two edges cases: edge case 1 and edge case 6. We already took into account edge case 1, where all the elements in the array are null. For this edge case in this method, we would revert back to the initial conditions of the class.</p><h4>Edge case 6</h4><p>The array is empty or the array only contains non-null elements.</p><p>For edge case 6, we wouldn’t change the array in any way and let the user know that there are no more null values in the array.</p><h3>Time Complexity of the StackQueueArray Class</h3><p>Give yourself a pat on the back if you’ve made it this far. This is a lot of information to process, especially if you read my previous blog on stacks and queues on top of this one.</p><p>Remember, the original goal was to improve the time complexity from O(n) to O(1). Let’s take a look at the time complexity of each class method to see if we achieved that.</p><p>.push(): For this method, we’re doing five actions: declaration, incrementation, boolean comparisons, accessing an element in an array, and using the out-of-the-box .push() method.</p><p>Each of these actions has a time complexity of O(1), which means this method’s time complexity is O(1).</p><p>.pop(): For this method, we’re doing five actions: declaration, decrementation, boolean comparisons, accessing an element in an array, and using the out-of-the-box .pop() method.</p><p>Each of these actions has a time complexity of O(1), which means this method’s time complexity is O(1).</p><p>.shift(): For this method, we’re doing four actions: declaration, incrementation, boolean comparisons, and accessing an element in an array.</p><p>Each of these actions has a time complexity of O(1), which means this method’s time complexity is O(1).</p><p>.head(): For this method, we’re doing three actions: declaration, boolean comparisons, and accessing an element in an array.</p><p>Each of these actions has a time complexity of O(1), which means this method’s time complexity is O(1).</p><p>.tail(): For this method, we’re doing three actions: declaration, boolean comparisons, and accessing an element in an array.</p><p>Each of these actions has a time complexity of O(1), which means this method’s time complexity is O(1).</p><p>.cleanUp(): For this method, we’re doing four actions: declaration, boolean comparisons, accessing an element in an array, and using the out-of-the-box .slice() method.</p><p>Each of these actions has a time complexity of O(1) except for the .slice() method.</p><p>The .slice() method makes a copy of subarray based on the input range provided in the parameters. In the worse-case scenario, it can copy the entire array, which is dependent on the array’s length.</p><p>Based on this, the time complexity of the .slice() method is O(n). This implies that, in the worst-case scenario, the .cleanUp() method has a time complexity O(n).</p><p>It looks like every method, except for .cleanUp() , has a time complexity of O(1). Would we count this as a success? Yes! And here’s why.</p><p>Recall that .cleanUp() was originally made to help with allocation, not with time complexity. You can think of this method more as a nice-to-have method rather than a necessary method.</p><p>This method does not directly affect the crux of the stack and queue data structure. If we didn’t have the .cleanUp() method in the StackQueueArray class, the class can still be used for any data structure that implements stacks and queues assuming that memory is not an issue.</p><p>If we ignore the .cleanUp() method now, then the overall time complexity for the StackQueueArray class is O(1)!</p><p>We successfully improved the time complexity of stacks and queues from O(n) to O(1)!</p><h3>Conclusion</h3><p>Notice in the StackQueueArray class, we didn’t use any special functions or something uncommon. Everything we coded in the class was out-of-the-box methods, properties of an array, and boolean comparisons.</p><p>All it took was some creativity to build out a new class and now we have a class that is faster than using out-of-the-box methods for stacks and queues.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7396ab7b5a2b" width="1" height="1" alt=""><hr><p><a href="https://medium.com/better-programming/improving-time-complexity-on-stacks-and-queues-7396ab7b5a2b">Data Structures: Improving Time Complexity on Stacks and Queues</a> was originally published in <a href="https://betterprogramming.pub/">Better Programming</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[An Introduction to Stacks and Queues]]></title>
            <link>https://medium.com/better-programming/stacks-and-queues-7c322b5f4e35?source=rss-71ed97db9a59------2</link>
            <guid isPermaLink="false">https://medium.com/p/7c322b5f4e35</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[queue]]></category>
            <category><![CDATA[algorithms]]></category>
            <category><![CDATA[data-structures]]></category>
            <category><![CDATA[stack]]></category>
            <dc:creator><![CDATA[Samuel Guo]]></dc:creator>
            <pubDate>Mon, 17 Feb 2020 04:54:57 GMT</pubDate>
            <atom:updated>2020-02-19T04:19:27.532Z</atom:updated>
            <content:encoded><![CDATA[<h4>Improve your data structures</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*YOIGqoLx-fiP1Bm4" /><figcaption>Photo by <a href="https://unsplash.com/@pankajpatel?utm_source=medium&amp;utm_medium=referral">Pankaj Patel</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a>.</figcaption></figure><h3>Background</h3><p>Optimizing code is rarely an easy task. The code may be working as intended, but if it takes too long to execute, then the code is inefficient and needs to be optimized. Data structures — a necessary evil in the coding world — represent the main crux for optimization. Using the correct data structure for the correct scenario will make your code run considerably faster than using a brute-force method.</p><p>One of these data structures is stacks and queues. Personally, I feel like this is a lesser-known data structure that’s extremely easy to implement and doesn’t get enough love.</p><h3>Stacks and Queues</h3><p>Before we dive any deeper, let’s define what stacks and queues are. Stacks follow the first-in-last-out (FILO) pattern. Queues follow the first-in-first-out (FIFO) pattern. Although these two terms are typically bundled together as a phrase, they follow two different design patterns.</p><h3>Stacks</h3><p>Let’s take a deeper dive with stacks and start off with an empty stack.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/198/1*UOJtAG-6njgw3j8oMAHEnQ.png" /></figure><p>We don’t have anything at the moment. Next, let’s add 10 to the stack.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/467/1*M3exbxtssOrTtpVTNkgRug.png" /><figcaption>Adding “10” to the empty stack.</figcaption></figure><p>After adding the 10 to the stack, it falls to the bottom of the stack. Keep in mind that the 10 is the first one into the stack. If you add 20 and 30 in that order, the stack should now look like the pictures below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/474/1*6FIn12Zaj5y8tToiT6X4QQ.png" /><figcaption>Adding 20 to the current stack.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/453/1*vqjb1MobjWU7DFMqSpMAtg.png" /><figcaption>Adding 30 to the current stack.</figcaption></figure><p>The current stack, from bottom to top, is now 10, 20, and 30. What if I want to get the 10 out? Well, we can’t at the moment because 30 and 20 are blocking the way. We would need to take out the 30, then take out the 20, and then finally we would be able to take out the 10. The 10 would be the last one to come out of the current stack.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/477/1*a7isEiZTuwCKcfLHI3IdwA.png" /><figcaption>Removing 30 from the current stack.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/463/1*YGukPrdWRQO1TWV71EI_fw.png" /><figcaption>Removing 20 from the current stack.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/534/1*TadKWUyXlSpi51rmemcqJw.png" /><figcaption>Removing 10 from the current stack.</figcaption></figure><p>This is what it means to be first in, last out (FILO). The first element placed into the stack will be the last element to be removed from the stack. The 10 was the first element to be placed into the stack (first in) and it would be the last element to be removed from the stack (last out). I know this sounds redundant, but explaining these terms as explicitly as possible will help avoid any confusion.</p><h3>Stacks in Code Terms</h3><p>Now that we understand what it means to be FILO and how a stack works, it’s time to actually implement a stack in terms of code. I am going to be using JavaScript to demonstrate this. But first, to give a clearer picture, let’s reuse our previous example. For demonstration purposes, let’s rotate the stack 90 degrees clockwise so that it now looks like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/352/1*hEhr0NC6AF-tSVys2UGMKQ.png" /></figure><p>In regards to code, we can use an array to represent an empty stack.</p><pre>let stack = []</pre><p>Next, we can add 10 to the empty stack.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/457/1*CkCMDSJZ4GRRTwR4WNV-Ug.png" /><figcaption>Adding 10 to the empty stack.</figcaption></figure><p>In code terms, this is the same as the following:</p><pre>stack.push(10)<br>console.log(stack) // [10]</pre><p>Now let’s put in 20 and 30 in that order.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/420/1*zitNHzEdyPvCj5AYfMNHSA.png" /><figcaption>Adding 20 to the current stack.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/420/1*GFZEKnnCdCDREoeNynv5hg.png" /><figcaption>Adding 30 to the current stack.</figcaption></figure><p>In code terms, this is the same as the following:</p><pre>stack.push(20)<br>stack.push(30)<br>console.log(stack) // [10, 20, 30]</pre><p>Now let’s bring it back and start removing from the stack, starting with the most recent addition.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/419/1*-tNsyIuIviZKyk_Ap2Xy3A.png" /><figcaption>Removing 30 from the current stack.</figcaption></figure><p>In code, this is the same as:</p><pre>stack.pop()<br>console.log(stack) // [10, 20]</pre><p>For the sake of brevity, I’m going to skip the pictures, but we would do the same thing for 20 and then 10. In code, we would invoke the .pop() method two more times.</p><pre>stack.pop()<br>stack.pop()<br>console.log(stack) // []</pre><p>Implementing a stack is really that simple! Thanks to JavaScript’s built-in methods, we can implement a stack data structure by using an array and using .push() and .pop() to create our own stack.</p><h3>Queues</h3><p>So far, we’ve only talked about stacks and how stacks are FILO. If you were able to follow how stacks work, queues are very similar. Since queues follow the first-in-first-out (FIFO) design pattern, we can also use an array to represent the queue.</p><p>Another way of thinking of queues is queueing up on a line. Typically, the people in line are serviced based on the order in which they arrived — just like if you were queueing in line to get into a venue.</p><p>I am going to combine images with code to save some time and space.</p><p>Similarly to how we started an empty stack, let’s start off an empty queue.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/317/1*x-ndUBpzw32yANUcq1FJAw.png" /></figure><pre>let queue = []</pre><p>Next, we’re going to add 10, 20, and 30 to the queue in that order. You can use the same images we did for the stack as a reference for the queue, as it is literally doing the same thing. In terms of the code, we will still be using the .push() method.</p><pre>queue.push(10)<br>queue.push(20)<br>queue.push(30)<br>console.log(queue) // [10, 20, 30]</pre><p>So far, the first-in portion stayed the same. Since queues are first-out, this is where it diverges from stacks. Currently, our queue looks like the following:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/352/1*LxugiYny0-bO9fcbSSZGBA.png" /><figcaption>Current queue.</figcaption></figure><p>Since the 10 was the first element to be added, it will now be the first removed.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/409/1*YUG9danYFU2F48YYiJHeOQ.png" /><figcaption>Removing the 10 from the current queue.</figcaption></figure><p>So, how would we do this in code? Thankfully, JavaScript also has a built-in method that does this for us: .shift().</p><pre>queue.shift()<br>console.log(queue) // [20, 30]</pre><p>Now, if we were to empty out the queue in the same order as the elements were added in, we would keep invoking the .shift() method.</p><pre>queue.shift()<br>queue.shift()<br>console.log(queue) // []</pre><p>Implementing a queue is also that simple! As with the stack, we can use JavaScript’s built-in methods for first in with the .push() method and first out with .shift().</p><h3>Time Complexity of Stacks and Queues</h3><p>For this section, I am making the following assumptions:</p><ol><li>You understand time complexity and Big O notation.</li><li>You understand the memory allocation mechanism of arrays.</li></ol><p>If you don’t understand the two concepts mentioned above, I highly recommend reading about them before proceeding any further.</p><p>For stacks, the time complexity of using the .push() is <em>O(1)</em> because .push() always adds to the end of the array and indexing the pushed element is one operation, as it increases the index by one. Using the .pop() is also <em>O(1)</em> because .pop() accesses and removes the last element of the array. When the last element is removed, the rest of the elements are not affected because they don’t need to be re-indexed. So overall, the time complexity of stacks is <em>O(1)</em>.</p><p>For queues, since we are using .push() as well, that time complexity is still <em>O(1)</em> for the same reasons mentioned in the last paragraph. However, using the .shift() method has a time complexity of <em>O(n)</em>. This is because when you remove the first element from an array, the computer will need to re-index the rest of the elements, which is dependent on the length of the array. So overall, the time complexity of using queues is <em>O(n)</em>.</p><p>Hopefully, you’ll be able to implement this. If not, at least you walked away knowing an additional data structure!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7c322b5f4e35" width="1" height="1" alt=""><hr><p><a href="https://medium.com/better-programming/stacks-and-queues-7c322b5f4e35">An Introduction to Stacks and Queues</a> was originally published in <a href="https://betterprogramming.pub/">Better Programming</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Array and Object De-structuring in Javascript]]></title>
            <link>https://javascript.plainenglish.io/array-and-object-de-structuring-in-javascript-da3e73867781?source=rss-71ed97db9a59------2</link>
            <guid isPermaLink="false">https://medium.com/p/da3e73867781</guid>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[tech]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Samuel Guo]]></dc:creator>
            <pubDate>Mon, 10 Feb 2020 01:56:47 GMT</pubDate>
            <atom:updated>2020-02-19T09:14:06.314Z</atom:updated>
            <content:encoded><![CDATA[<h3>Array and Object De-structuring in JavaScript</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/0*ITvGnxQPw2gB46dz.png" /></figure><h3>Background</h3><p>Code isn’t just about making it work. Code is also about it being readable and concise such as proper indentation, appropriate naming conventions, etc. Code should also be self-documenting (which is another topic that I recommend you read into). A common convention for readable and concise code is array and object de-structuring. Array and object de-structuring is syntactic sugar for “taking apart” values and assigning those values to distinct variables.</p><h3>Array De-structuring</h3><p>From what I’ve seen thus far, array de-structuring is less common than object de-structuring but I do see it from time to time. So, how does array de-structuring work?</p><p>Typically, you would see an array like this:</p><pre>const colors = [&quot;red&quot;, &quot;blue&quot;, &quot;green&quot;]</pre><p>And to access the values in colors , you would access them based on their indicies. So,</p><pre>colors[0] = &quot;red&quot;<br>colors[1] = &quot;blue&quot;<br>colors[2] = &quot;green&quot;</pre><p>But let’s say you need to access these values multiple times throughout your code base. Trying to remember which index for their specific color can get confusing easily and lead to mistakes. Imagine constantly checking to make sure you put in the correct index number for the array. Let alone, if there was a mistake or you needed to change it, you would need to debug or look for it but all you see are colors[0] , colors[1] , or colors[2] . Array de-structuring will help you alleviate this conundrum.</p><p>First, I’m going to show you the array de-structuring syntax and then I’m going to break down what it’s doing.</p><pre>const [ red, blue, green ] = colors</pre><p>Wow… it’s just one line? Yup!</p><p>So, let’s unpack this one liner.</p><p>In the portion const [ red, blue, green ] , I am instantiating three new variables: red , blue , green . In the portion = colors , I am declaring values for the variables red , blue , and green based on the colors array. But how does JavaScript know which value in the colors array is declared to which variable?</p><p>Notice how red , blue , and green are within array brackets. <em>The index where the variable is declared is the same index used to determine which value to use from the array.</em> For example, blue is declared at index 1 . This means that blue will be equal to the value at color[1] , which is &quot;blue&quot; in this case. Here, the order in which the variables are instantiated is the determining factor. Essentially, the code below shows what the array de-structuring is doing.</p><pre>const red = colors[0]<br>const blue colors[1]<br>const green = colors[2]</pre><pre>console.log(red) // &quot;red&quot;<br>console.log(blue) // &quot;blue&quot;<br>console.log(green) // &quot;green&quot;</pre><p>So where might you find cases to use array de-structuring? The most common place I’ve seen it is for <a href="https://reactjs.org/docs/hooks-intro.html">React hooks</a>. You will need to understand array de-structuring if you intend to use strictly functional components that require state.</p><h3>Object De-structuring</h3><p>Object de-structuring works in the same vein as array de-structuring. But let’s take it from the top.</p><p>Typically, you would see an object declared like this:</p><pre>const colors = { red: &quot;red&quot;, blue: &quot;blue&quot;, green: &quot;green&quot; }</pre><p>And to access the values in the key-value pairs, you would access them based on their keys. So,</p><pre>colors.red = &quot;red&quot;<br>colors.blue = &quot;blue&quot;<br>colors.green = &quot;green&quot;</pre><p>Now, let’s de-structure this object!</p><pre>const { red, blue, green } = colors</pre><p>Thankfully object de-structuring is just one line as well! If you were able to follow array de-structuring, this will be very, very similar.</p><p>In the portion const { red, blue, green }, I am instantiating three new variables: red , blue , green . In the portion = colors , I am declaring values for the variables red , blue , and green based on the colors object. But how does JavaScript know which value in the colors object is declared to which variable?</p><p>Notice how red , blue , and green are within object brackets. <em>The variable name itself will be used as the key to determine which key-value pair to use from the object. </em>For example, I am declaring the variable with the name blue . This means in the colors object, JavaScript will look for a key called blue and assign the value associated with that key to the variable blue . Here, the variable name is the determining factor. Essentially, the code below shows what object de-structuring is doing.</p><pre>const red = colors.red<br>const blue = colors.blue<br>const green = colors.green</pre><pre>console.log(red) // &quot;red&quot;<br>console.log(blue) // &quot;blue&quot;<br>console.log(green) // &quot;green&quot;</pre><p>A very common instance when to use object de-structuring is when you are passing down props in a React component. Since props (in functional components) or this.props (in classes) are already objects, using the same variable name as the name you used in the parent component can help you de-structure the props. An example for that is shown below.</p><pre>// App.js</pre><pre>import React, { Component } from &#39;react&#39;<br>import Calendar from &#39;./Calender&#39;</pre><pre>class App extends Component {<br>  state = {<br>    month: Feburary<br>    date: 9<br>    year: 2020<br>  }</pre><pre>  render() {<br>    return (<br>      &lt;div&gt;<br>        &lt;Calendar <br>          month={this.state.month} <br>          date={this.state.date}<br>          year={this.state.year}<br>        /&gt;<br>      &lt;/div&gt;<br>    )<br>  }<br>}</pre><pre>// Calendar.js</pre><pre>import React from &#39;react&#39;</pre><pre>function Calendar(props) {<br>  // object de-structuring<br>  const { month, date, year } = props<br>  return (<br>    &lt;h1&gt;Today is {month} {date}, {year}&lt;/h1&gt;<br>  )<br>}</pre><pre>export default Calendar </pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=da3e73867781" width="1" height="1" alt=""><hr><p><a href="https://javascript.plainenglish.io/array-and-object-de-structuring-in-javascript-da3e73867781">Array and Object De-structuring in Javascript</a> was originally published in <a href="https://javascript.plainenglish.io/">JavaScript in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding the Nuances of Different Approaches That Achieve the Same Results]]></title>
            <link>https://medium.com/@guosamuel1114/understanding-the-nuances-of-different-approaches-that-achieve-the-same-results-1cdabb4509a9?source=rss-71ed97db9a59------2</link>
            <guid isPermaLink="false">https://medium.com/p/1cdabb4509a9</guid>
            <category><![CDATA[react]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[event-listener]]></category>
            <dc:creator><![CDATA[Samuel Guo]]></dc:creator>
            <pubDate>Mon, 03 Feb 2020 02:47:12 GMT</pubDate>
            <atom:updated>2020-02-12T17:19:14.263Z</atom:updated>
            <content:encoded><![CDATA[<h3>Background</h3><p>After using React for a while, one would think I would understand most of the mechanics and flow of the framework. For one of my code challenges, I ran into a new bug, one where I haven’t encountered before. At first, I was kind of clueless why this bug kept happening, and why it only happened sometimes. Was there a bug with the environment I was in? Was it because the current version of React I was using didn’t patch up this bug in the framework? Was the logic flow of my code flawed?</p><p>Coincidentally enough, this bug is also related to a lifecycle method, similar to the time where I learned I should be using the lifecycle method componentDidUpdate() .</p><h3>Re-creating the Bug</h3><p>As usual, in order to debug your code, you need to understand how the bug was created in the first place and approach from there. Re-creating the bug took three components, App , IncreaseCount , and StaticCount .</p><pre>// App.js<br>import React from &#39;react&#39;;</pre><pre>import IncreaseCount from &#39;./IncreaseCount&#39;<br>import StaticCount from &#39;./StaticCount&#39;</pre><pre>class App extends React.Component {<br>  state = {<br>    checked: false,<br>    count: 0<br>  }</pre><pre>  handleCheck = () =&gt; {<br>    this.setState({ checked: !this.state.checked})<br>  }</pre><pre>  increaseCount = () =&gt; {<br>    this.setState( {count: this.state.count + 1} )<br>  }</pre><pre>  render() {<br>    return (<br>      &lt;div className=&quot;App&quot;&gt;<br>        &lt;span&gt;Click to Switch Components&lt;/span&gt;<br>        &lt;input type=&quot;checkbox&quot; onChange={this.handleCheck}/&gt;<br>        &lt;br /&gt;<br>        { this.state.checked ? &lt;StaticCount /&gt; :&lt;IncreaseCount increaseCount={this.increaseCount} count={this.state.count}/&gt; }<br>      &lt;/div&gt;<br>    )<br>  }<br>}</pre><pre>export default App;</pre><pre>// IncreaseCount.js<br>import React from &#39;react&#39;</pre><pre>class IncreaseCount extends React.Component {</pre><pre>  componentDidMount() {<br>    document.addEventListener(&#39;click&#39;, this.props.increaseCount)<br>    document.addEventListener(&#39;click&#39;, this.showLeakedMessage)<br>  }</pre><pre>  showLeakedMessage = (e) =&gt; {<br>    if (e.target.className === &quot;button&quot;) {<br>      console.log(&quot;I&#39;m in the Increase Count component&quot;)<br>    }<br>  }</pre><pre>  render() {<br>    console.log(&quot;I AM IN THE INCREASE COUNT COMPONENT. THE COUNT IS:&quot;, this.props.count)<br>    return (<br>      &lt;div&gt;<br>        &lt;h1&gt;Increase Count!&lt;/h1&gt;<br>        &lt;h2&gt;Click anywhere on this page to increase the count: {this.props.count}&lt;/h2&gt;<br>      &lt;/div&gt;<br>    )<br>  }<br>}</pre><pre>export default IncreaseCount</pre><pre>// StaticCount.js<br>import React from &#39;react&#39;</pre><pre>function StaticCount() {<br>  return (<br>    &lt;div&gt;<br>      &lt;h1&gt;Static Count!&lt;/h1&gt;<br>      &lt;h2&gt;Count should not be increasing in the console whenever I click on the page.&lt;/h2&gt;<br>      &lt;button className=&quot;button&quot;&gt;Check the console log&lt;/button&gt;<br>    &lt;/div&gt;<br>  )<br>}</pre><pre>export default StaticCount</pre><p>The App component either renders the IncreaseCount component or the StaticCount component, depending if the checkbox is checked off or not. In the IncreaseCount component, if you look in the componentDidMount() method, I added two click event listeners.</p><p>Typically in React, you can use the onClick event listener in the tag that you want it to be associated with but for some reason, in the coding environment where I did my code challenge, the synthetic listeners didn’t seem to work or exist. To work around that, I used plain Javascript to include these event listeners. Soon, you will see how this will be the root cause of the bug.</p><h3>Video Demonstration of the Bug</h3><p>For the sake of time and clarity, please see the two videos below demonstrating the bug itself.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FoPyabNSaisE%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DoPyabNSaisE&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FoPyabNSaisE%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="640" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/27fdd005f3d657a47c0e34151d89386b/href">https://medium.com/media/27fdd005f3d657a47c0e34151d89386b/href</a></iframe><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FMXTS0VfClU8%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DMXTS0VfClU8&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FMXTS0VfClU8%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="640" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/fc125fe95ad093c931f88000820428d3/href">https://medium.com/media/fc125fe95ad093c931f88000820428d3/href</a></iframe><p>In the first video, I clicked on the page several times after the IncreaseCount component mounted. You can see in the developer console the console logs on the amount of times I clicked on the page. Next, I click on the check box to change from the IncreaseCount component to the StaticCount component. I clicked on the page several times and nothing is being console logged.</p><p>Looking good so far.</p><p>However, when I click on the check box to switch back to the IncreaseCount component, all of the clicks from the StaticCount component back loads into the IncreaseCount component, automatically updating the amount of counts. Admittedly, this was a cool side effect, but this is still a bug. I only want the count to increase when the IncreaseCount component is mounted.</p><p>In the second video, I clicked on the check box first to switch into the StaticCount . I clicked on the button and in the developer console, you can see it console logging “I’m in the Increase Count component”. As a quick reminder, this console log method is from the showLeakedMessage method in the IncreaseCount component. Yet… we’re in the StaticCount message. Also, as an added bonus for the bug, the amount of times clicked on the button is back loaded and console logged when you switch back over to the IncreaseCount component.</p><p>So… just what the heck is going on?</p><h3>Javascript versus React</h3><p>I followed the trail of logic of this bug which led me to the culprit:</p><pre>componentDidMount() {<br>    document.addEventListener(&#39;click&#39;, this.props.increaseCount)<br>    document.addEventListener(&#39;click&#39;, this.showLeakedMessage)<br>}</pre><p>For those not familiar with document.addEventListener() method, I highly recommend reading the documentation <a href="https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener">here</a>. document.addEventListener() is not a function created by React. This is a built in method within the Javascript language.</p><p>So… why does this matter?</p><p>Events handled by the browser are different than events handled by React. In React, events are wrapped with a SyntheticEvent wrapper. Straight from their <a href="https://reactjs.org/docs/events.html">documentation</a>,</p><blockquote>Your event handlers will be passed instances of SyntheticEvent, a cross-browser wrapper around the browser’s native event. It has the same interface as the browser’s native event, including stopPropagation() and preventDefault(), except the events work identically across all browsers.</blockquote><p>The implementation of a SyntheticEvent are slightly different than a native browser event. The SyntheticEvent , like onClick , is lexically scoped within the tag of where the event was declared. With a native browser event, you need to explicitly declare the target for your event listener. So in the case of document.addEventListener(‘click’, this.props.increaseCount) , the target is document , the native event is click , and the listener is this.props.increaseCount (the increaseCount method in the App component).</p><p>So, how does this tie back into the bug from those two videos?</p><p>When the IncreaseCount component is mounted, the native browser click event listener is added to the document . Because the target was document , the scope is the entire document, regardless of which component is mounted. This means even if you declared the event listener in a component, the event isn’t tied specifically to the component itself.</p><p>This is why the console logs and events are triggered in other components outside the component of where the event listener was declared.</p><p>Now that we understand the bug, how do we remedy this?</p><h3>Resolving the Bug</h3><p>There are three ways this bug can be resolved:</p><ol><li>Narrow or define the scope of target.</li><li>Narrow the scope within the event listener (e.g., the showLeakedMessage method).</li><li>Remove the event listener when the component unmounts from the page.</li></ol><p>For this scenario, I went with the third solution. Please note that the third solution is not a generic solution. In this example, it is the most convenient solution because with the target as document , this will primarily affect the mounted component, which is only either IncreaseCount or StaticCount . If you want the event listener to propagate to other components after the unmounting it from the page, then I would recommend either the first or second solution.</p><p>The lifestyle component to invoke whenever a component unmounts is componentWillUnmount() . According to the <a href="https://reactjs.org/docs/react-component.html#componentwillunmount">documentation</a>,</p><blockquote>“componentWillUnmount() is invoked immediately before a component is unmounted and destroyed. Perform any necessary cleanup in this method, such as invalidating timers, canceling network requests, or cleaning up any subscriptions that were created in componentDidMount().</blockquote><p>Since I only want my event listener (i.e, click) specifically for my IncreaseCount component, it makes logical sense to remove the event listener whenever this component unmounts (or not rendered). Another reason why this works is because I don’t need to use the same event listener on any other component outside of the IncreaseCount component. The same logic can be applied for the button shown in the second video.</p><p>In the IncreaseCount component, I invoke the componentWillUnmount() method and in the body of that method, I remove the event listeners. So now, the updated IncreaseCount component looks like the following:</p><pre>// IncreaseCount.js<br>import React from &#39;react&#39;</pre><pre>class IncreaseCount extends React.Component {</pre><pre>  componentDidMount() {<br>    document.addEventListener(&#39;click&#39;, this.props.increaseCount)<br>    document.addEventListener(&#39;click&#39;, this.showLeakedMessage)<br>  }</pre><pre>  // added this lifecycle method <br>  componentWillUnmount() {<br>    document.removeEventListener(&#39;click&#39;, this.props.increaseCount)<br>    document.removeEventListener(&#39;click&#39;, this.showLeakedMessage)<br>  }</pre><pre>  showLeakedMessage = (e) =&gt; {<br>    if (e.target.className === &quot;button&quot;) {<br>      console.log(&quot;I&#39;m in the Increase Count component&quot;)<br>    }<br>  }</pre><pre>  render() {<br>    console.log(&quot;I AM IN THE INCREASE COUNT COMPONENT. THE COUNT IS:&quot;, this.props.count)<br>    return (<br>      &lt;div&gt;<br>        &lt;h1&gt;Increase Count!&lt;/h1&gt;<br>        &lt;h2&gt;Click anywhere on this page to increase the count: {this.props.count}&lt;/h2&gt;<br>      &lt;/div&gt;<br>    )<br>  }<br>}</pre><pre>export default IncreaseCount</pre><p>And voila! We’ve cleared out this bug and now the event triggers are functioning as expected.</p><h3>Key Takeaway</h3><p>As usual, I learned a lesson while trying to debug my code. For this scenario, I had to use a different approach due to my coding environment. The beauty of coding is that there are many ways to achieve what your code needs to do. However, the catch is to understand the nuances of the different approaches and to not be caught off guard if the approach produces a slightly different result. I am not saying you must understand every explicit or implicit nuance but rather be cognizant of your chosen approach so if a bug, or in general, an issue, ever happens, you have a lead on how to approach the solution.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1cdabb4509a9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Deploying An Application to Netlify and Heroku With Proper Configurations]]></title>
            <link>https://medium.com/@guosamuel1114/deploying-an-application-to-netlify-and-heroku-with-proper-configurations-5c516d9e3f4c?source=rss-71ed97db9a59------2</link>
            <guid isPermaLink="false">https://medium.com/p/5c516d9e3f4c</guid>
            <category><![CDATA[netlify]]></category>
            <category><![CDATA[heroku]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[deployment]]></category>
            <dc:creator><![CDATA[Samuel Guo]]></dc:creator>
            <pubDate>Mon, 27 Jan 2020 04:40:26 GMT</pubDate>
            <atom:updated>2020-01-27T04:40:26.315Z</atom:updated>
            <content:encoded><![CDATA[<h3>Background</h3><p>One of the most satisfying, yet nerve wracking, experiences is deploying your application to production for the public to use. This satisfaction comes from the success that you completed your application and all your efforts produced a tangible, functioning result. The nervousness comes from the unknown future on the application itself (i.e., What future bugs will the users come across? Is it intuitive enough where the user knows where to go? Are the users going to read the ReadMe before getting stuck? etc.).</p><p>Unfortunately for me, its was mostly the nerve wracking part that came first before the satisfaction. And per usual, I learned from this lesson as well. In hindsight, the solution was pretty easy but at the time, it was a lot of Googling and researching.</p><h3>Netlify for Front End, Heroku for Back End</h3><p>I deployed my Progressing Forward application, my capstone project during my time at Flatiron School. For the front end, I deployed it through Netlify and for the back end, I deployed it through Heroku. You can deploy your front and back end however you want to, but through Googling and talking with others who have deployed applications before, this seemed to be the common route.</p><h3>Deploying to Netlify</h3><p>Deploying to Netlify was as smooth as it could go. I basically followed the deployment instructions from Netlify and connected the front end repository from Github to the Netlify server. There are options on how the repository is connected other than Github (i.e., Gitlab and Bitbucket) but overall, from my experience, whenever the repository you chose is updated, the Netlify server will reflect those changes.</p><p>Netlify also has a really cool feature where you can change the domain name (but still have the Netlify name in the URL). Here’s what I mean by that feature. When Netlify first deploys your application, it will provide a randomized name (i.e., “<a href="https://progressingforward.netlify.com/">https://dancing-giraffes.netlify.com/</a>”). The randomized name in the example is “dancing-giraffes”. However, in the dashboard for this application, you can change the given name to anything you want. In my scenario, I changed it to “progressingforward” so the full URL is “<a href="https://progressingforward.netlify.com/">https://progressingforward.netlify.com/</a>”. Notice how the “.netlify.com/” will always be appended to the given name. You can re-direct the URL to a domain that you own but you’re given a free domain, so I decided to stick with it.</p><p>So far so good! This was smooth sailing… until I deployed to Heroku.</p><h3>Deploying to Heroku</h3><p>Deploying to Heroku took a bit longer than deploying to Netlify. This is not meant to bash on Heroku but rather their tutorials are much more in depth than Netlify’s. I decided to go step-by-step, following Heroku’s example tutorial with their dummy setup and understanding each step before deploying my application’s back end. Following the tutorial wasn’t difficult at all. By following the same steps as the tutorial, I was able to deploy my application’s back-end to Heroku.</p><p>Hooray! Now I have a fully functioning application deployed to the internet! Let’s test it out and make sure it runs smoothly.</p><p>After attempting to log in with the dummy username and password, the nervousness started to kick in. The console in the Web Developers tool on Chrome said, in red, “Internal Server Error: Status 500”. Cue the sweat drops and internal screaming.</p><h3>Internal 500 Error</h3><p>The 500 error was due to my back-end. To confirm that it was, I attempted to log in as a different existing user on my application and was unsuccessful. I followed the logic of my code: typing in the username and password, fetching to the back end by following the proper routes, to the controller, and to the response given back to the front end. Everything looked normal to me.</p><p>Perhaps it had to do something with my routes?</p><p>Instead of logging in as an existing user, I decided to create a new user for testing purposes. Creating a different user would hit a different route in my back end. When I signed up as a new user, it was successful. Okay, so far so good. When I try to log in as that new user, it failed. The console in the Web Developers tool also gave the same internal 500 error message as before.</p><p>Hm… so now I have a control case where my application works and a case where it doesn’t work.</p><p>I pulled up the code for each case, side by side, slowly dissecting the code on where it might have went wrong and… I found the issue.</p><h3>Shhh… It’s a Secret!</h3><p>Below is the code where the issue occurred!</p><pre>class ApplicationController &lt; ActionController::API</pre><pre>  def encode_token(user_id)<br>    JWT.encode({user_id: user_id}, ENV[&#39;SECRET_TOKEN&#39;])<br>  end</pre><pre>  ...</pre><pre>end</pre><p>The error occurred because the deployed code did not have the .env file that was local to my computer, which means that ENV[&#39;SECRET_TOKEN&#39;] was undefined.</p><p>You might be thinking “Why would I not want to push a file to the repository for production?”.</p><p>Let’s take a look at the following code:</p><pre>JWT.encode({user_id: user_id}, ENV[&#39;SECRET_TOKEN&#39;])</pre><p>This is an over simplification but the code above encrypts the payload, {user_id: user_id} , based on a key that the ENV[&#39;SECRET_TOKEN&#39;] specifically is made for, and returns an encrypted string that contains the header, payload, and signature. Don’t worry about the details of it but I highly recommend reading how JSON web tokens (JWTs) work on their website linked <a href="https://jwt.io/introduction/">here</a>.</p><p>For all intents and purposes, the ENV[&#39;SECRET_TOKEN&#39;] is the key to encrypting and decrypting data. The .env file, where ENV[&#39;SECRET_TOKEN&#39;] is referencing, will look something like this:</p><p>SECRET_TOKEN=ThisIsJustAnExampleToSeeHowItWouldLookLike123456789</p><p>If a user has access to the key and the payload contained personal data, that is a huge data leak and no one would be happy with that! (Except for the hacker). It would also be worse if the hacker also hacked the database and was able to find all of the person’s information based on the decrypted payload (i.e., {user_id: user_id}).</p><p>This is where you would want to separate any keys from the repository where you don’t want users to have public access to.</p><p>So if I shouldn’t upload the file that will fix the error, what should be the next step?</p><h3>Configurations On Heroku</h3><p>After some more Googling and reading into Heroku’s documentation and tutorials, Heroku has taken this scenario into account.</p><p>On the dashboard of the website of where it was deployed, click on the “Settings” tab. A new screen should appear with the “Config Vars” row and a button that says “Reveal Config Vars”. When you click on that button, it reveals all of the configurations that Heroku used for your application. This is where you can put in your key that encrypts and decrypts your JWT.</p><p>Aaaaand viola! After putting in my key from my local file, the internal 500 error was resolved and the application is working exactly how it does on my local computer.</p><h3>Key Takeaways</h3><p>From this experience in deploying my application and extensive Googling, I came across two lessons:</p><ol><li><strong>Don’t post anything up to a public repository that is supposed to be hidden from the public (e.g., private keys).</strong></li></ol><p>I know this sounds obvious but it never hurts to state it. Even if you accidentally make this mistake, it is not the end of the world. You can always generate a new private key to replace the leaked one. From my research on private keys, you will still need to take additional steps after generating a private key to erase the history of the leaked key that is within your control.</p><p>2. <strong>You should have the proper configurations and separate codes for your development and production environment.</strong></p><p>I feel like this is also another obvious statement, especially for those in DevOps. This realization hit me first hand after I deployed my front end code and debugging my deployed back end code. When I was tinkering around with back end code on my local computer (so I didn’t accidentally destroy the deployed back end), I couldn’t use my front end code to help me debug. This was because my local front end code was already configured for the production environment (i.e., the fetch URLs was changed from my local computer URL to the deployed URL). Constantly switching between URLs on the deployed front end code to test if my back end code was working properly seemed unnecessarily redundant. If I already had separate code configured for the development environment, it would’ve made my life much easier.</p><p>Hopefully the next time you deploy code, you don’t run into as many headaches as I did!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5c516d9e3f4c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Knowing When To Componentize Your Code]]></title>
            <link>https://medium.com/@guosamuel1114/knowing-when-to-componentize-your-code-8b3901d19ab?source=rss-71ed97db9a59------2</link>
            <guid isPermaLink="false">https://medium.com/p/8b3901d19ab</guid>
            <category><![CDATA[redux]]></category>
            <category><![CDATA[components]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Samuel Guo]]></dc:creator>
            <pubDate>Mon, 20 Jan 2020 02:45:12 GMT</pubDate>
            <atom:updated>2020-01-20T02:45:12.731Z</atom:updated>
            <content:encoded><![CDATA[<h3>Background</h3><p>A fundamental concept of React is that you should always be componentizing. This means that the application should always be broken up into many smaller components rather than one giant component. This will help with maintainability and scaleability in the long run versus putting all your code on one file in the short run. Although it is easy on <em>how</em> to componentize your application, an issue I had was <em>when </em>I should be componentizing. This happened on my Group Randomizer project where I dumped the majority of my functions and states into my App.js file.</p><h3>Recreating The Issue</h3><p>Let’s re-create the baseline of this issue. Although I won’t be using the same code as my project, I will abstract the logic with pseudocode.</p><pre>//App.js</pre><pre>function App() {<br>  hook for stateOne<br>  hook for stateTwo<br>  hook for stateThree<br>  hook for stateFour<br>  hook for stateFive</pre><pre>  function alpha (stateOne) <br>  function bravo (stateOne, stateTwo)<br>  function charlie (stateThree)<br>  function delta (stateFour)<br>  function echo (stateThree, stateFive)</pre><pre>return (<br>    &lt;div&gt;<br>      renders something based on the output of function alpha<br>      renders something based on the output of function bravo<br>      renders something based on the output of function charlie<br>      renders something based on the output of function delta<br>      renders something based on the output of function echo<br>    &lt;/div&gt;<br>  )</pre><pre>}</pre><p>In the App.js file written in pseudo code, there are five hooks to maintain state, five functions that use one or two states as their parameters, and a return that renders something based on the output of their respective function.</p><h3>Always Be Componentizing</h3><p>In the return portion of App.js, there are five things that are rendering. Each of those renders can be broken up into a component, so there should be five new components. For the sake of demonstration purposes, I am going to pseudocode for two components as the process will be very similar, if not the same, for the rest of the components.</p><p>The psuedocode would look like the following below.</p><pre>//App.js</pre><pre>import ComponentOne from &#39;./ComponentOne&#39;</pre><pre>function App() {<br>  hook for stateTwo<br>  hook for stateThree<br>  hook for stateFour<br>  hook for stateFive</pre><pre>  function bravo (stateOne, stateTwo)<br>  function charlie (stateThree)<br>  function delta (stateFour)<br>  function echo (stateThree, stateFive)</pre><pre>return (<br>    &lt;div&gt;<br>      &lt;ComponentOne /&gt;<br>      renders something based on the output of function bravo<br>      renders something based on the output of function charlie<br>      renders something based on the output of function delta<br>      renders something based on the output of function echo<br>    &lt;/div&gt;<br>  )</pre><pre>}</pre><pre>//ComponentOne.js</pre><pre>export default function ComponentOne() {<br>  hook for stateOne</pre><pre>  function alpha (stateOne)</pre><pre>  return (<br>    &lt;div&gt;<br>      renders something based on the output of function alpha<br>    &lt;/div&gt;<br>  )</pre><pre>}</pre><p>Essentially, I moved the hook for stateOne and function alpha from App.js into ComponentOne.js because they directly affected the first component. So far this doesn’t seem so bad. Let’s move onto the second component.</p><pre>//ComponentTwo.js</pre><pre>export default function ComponentTwo() {<br>  hook for stateOne<br>  hook for stateTwo</pre><pre>  function bravo (stateOne, stateTwo)</pre><pre>  return (<br>    &lt;div&gt;<br>      renders something based on the output of function bravo<br>    &lt;/div&gt;<br>  )</pre><pre>}</pre><p>Well, we already hit our first snag. The stateOne hook is already defined in ComponentOne.js. Replicating the same hook in a different file would violate the single responsibility principle and potentially cause a ton of side effects/bugs in the future.</p><p>We would need to move stateOne back to the App component because it is used for both ComponentOne and ComponentTwo and pass it down to those two components as a prop. Assuming only ComponentOne is the only component that changes the state of stateOne , then a callback function will also need to be passed down to that component.</p><pre>//App.js</pre><pre>import ComponentOne from &#39;./ComponentOne&#39;</pre><pre>function App() {<br>  hook for stateOne<br>  hook for stateThree<br>  hook for stateFour<br>  hook for stateFive</pre><pre>  function charlie (stateThree)<br>  function delta (stateFour)<br>  function echo (stateThree, stateFive)</pre><pre>  function updateStateOneCallback()</pre><pre>  return (<br>    &lt;div&gt;<br>      &lt;ComponentOne stateOne={stateOne} updateStateOneCallback={updateStateOneCallback}/&gt;<br>      &lt;ComponentTwo stateOne={stateOne} /&gt;<br>      renders something based on the output of function charlie<br>      renders something based on the output of function delta<br>      renders something based on the output of function echo<br>    &lt;/div&gt;<br>  )</pre><pre>}</pre><pre>//ComponentOne.js</pre><pre>export default function ComponentOne(props) {</pre><pre>  function alpha (props.stateOne)</pre><pre>  return (<br>    &lt;div&gt;<br>      renders something based on the output of function alpha<br>      &lt;button onClick={props.updateStateOneCallback}&gt;Click Me&lt;/button&gt;<br>    &lt;/div&gt;<br>  )</pre><pre>}</pre><pre>//ComponentTwo.js</pre><pre>export default function ComponentTwo(props) {<br>  hook for stateTwo</pre><pre>  function bravo (props.stateOne, stateTwo)</pre><pre>  return (<br>    &lt;div&gt;<br>      renders something based on the output of function bravo<br>    &lt;/div&gt;<br>  )</pre><pre>}</pre><h3>Scaling the Issue</h3><p>Notice how many changes we needed to make it in order to accommodate componentizing ComponentTwo . Although it wasn’t difficult, it was a lot to keep track of. Missing one of those steps would cause bugs and potentially make debugging a nightmare. Imagine scaling that effort directly proportional to the number of components. At that point, it would be a tedious management task rather than coding new features.</p><p>Also, we were passing props and callback functions between App , ComponentOne , and ComponentTwo , where App is the parent component of ComponentOne and ComponentTwo . We had to do this because stateOne affected ComponentOne and ComponentTwo . But what if stateOne , or any other state, affected nested components, as in a component that is the great-great-children of App ? We would need to pass props and callback functions proportionate to how deeply nested the component is.</p><pre>App (where stateOne lives)<br>|<br>|- ComponentOne<br>|       |<br>|       |- ComponentOneChild<br>|                     |<br>|                     |- ComponentOneGrandChild<br>|                                     |<br>|                                     |- ComponentOneGreatGrandChild <br>|                                          (needs to use stateOne)<br>|- ComponentTwo                  <br>|<br>|- ComponentThree</pre><p>The diagram above is how a nested component may look like for stateOne .</p><p>In this scenario, we can easily see how it can get extremely messy and this can turn into more of a book keeping exercise rather than developing features or functionality of the application. Luckily, these are the type of scenarios where Redux is perfect to implement.</p><p>If we were to implement Redux, then we would need to create the reducers, actions, and dispatchers as necessary. Although this may seem slightly more work upfront in comparison to creating props and callback functions, this will save time in the long run because the structure of keeping track of various states in the Redux store will be established. From personal experience, debugging state in Redux is far easier than debugging state that was passed via props and callback functions.</p><h3>Back to the Original Issue</h3><p>So far, I’ve explained componentizing the application and the potential issues of what happens if you scale/develop your application before componentizing it. But I never answered the question: when do you start componentizing the application?</p><p>I believe you should start componentizing when:</p><ol><li>A new state is introduced that may affect multiple components</li><li>A portion of the code has one specific purpose (e.g., title, navigation bar, graphs, etc.)</li></ol><p>To circle back to the App example and to emphasize the second point, a portion of the code renders the result of function alpha . Since function alpha does not affect the rest of the code, it makes logical sense to componentize rendering the results of function alpha and the function itself, hence the creation of ComponentOne , and use Redux to keep track of stateOne because stateOne also affects function bravo , which lives in ComponentTwo .</p><p>If there was a case in which the results of a function, say function alpha, from one component affects the rendering or results of a different component, a solution to that could be storing the results of function alpha in the Redux store and access it when needed.</p><h3>Key Takeaways</h3><ol><li>Componentize as necessary as explained in the previous section.</li><li>Wire frame the application before starting to code.</li></ol><p>This is a common step during the development stages of any application. The wire frame lays out the format and the locations of each component, providing an idea on what components you will need and when to start componentizing. I know you may eager to dive straight into code and begin developing it but knowing where the components are will provide a development trajectory of the application.</p><p>3. Use Redux, or any state management tools, as soon as possible to assist you while componentizing.</p><p>Applications always scale. By putting the additional effort to set up the structure of your code earlier on, it will save you time and effort to debug or re-structuring in the future due to scaling reasons. This may not be helpful in the beginning of the application but after a certain point, the proper structuring will be more efficient than structuring the code as you go.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8b3901d19ab" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding What’s Happening “Under the Hood” with Source Codes and Existing Methods]]></title>
            <link>https://medium.com/swlh/understanding-whats-happening-under-the-hood-with-source-codes-and-existing-methods-3bca47cb5757?source=rss-71ed97db9a59------2</link>
            <guid isPermaLink="false">https://medium.com/p/3bca47cb5757</guid>
            <category><![CDATA[passwords]]></category>
            <category><![CDATA[bcrypt]]></category>
            <category><![CDATA[ruby-on-rails]]></category>
            <category><![CDATA[source-code]]></category>
            <dc:creator><![CDATA[Samuel Guo]]></dc:creator>
            <pubDate>Mon, 13 Jan 2020 04:20:35 GMT</pubDate>
            <atom:updated>2020-01-21T22:46:11.286Z</atom:updated>
            <content:encoded><![CDATA[<h3>Background</h3><p>Seed data is an essential part of the development process. Seed data can be dummy data that your code uses to confirm your code is doing exactly what it is supposed to do. This is slightly different from tests because the data can be used throughout your codebase where necessary. Seed data goes along the thought process of behavioral driven development, where depending on the output of your seed data, you may need to tweak your code accordingly.</p><p>Although it is very straight-forward to create seed data, you may run into issues creating the seed data itself. One instance where I ran into this was creating seed data where the user has a secured password via BCrypt. BCrypt is a gem in Rails where it salts and hashes your password, making it indecipherable to the human eye. An example is if my password is 123, then the salted and hashed password may look like <em>$2a$04$iOfhwahFymCs5weB3BNH/uXkTG65HR.qpW.bNhEjFP3ftli3o5DQC .</em></p><p>I wouldn’t worry about the concept of salting and hashing for the blog or the the BCrypt gem itself. You can think of salting and hashing as encryption for your password. Although I would be using these terms, the majority of the blog will be on password , password_digest , find_or_create_by, and has_secure_password .</p><h3>Setup For Usernames and Passwords</h3><p>To kick this off, below is the schema, User model, and seed data for this example.</p><pre>// Schema<br>create_table &quot;users&quot;, force: :cascade do |t|<br>  t.string &quot;username&quot;<br>  t.string &quot;password_digest&quot;<br>  t.datetime &quot;created_at&quot;, null: false<br>  t.datetime &quot;updated_at&quot;, null: false<br>end</pre><pre>// User model<br>class User &lt; ApplicationRecord<br>  has_secure_password<br>end</pre><pre>//Seed data<br>for x in 1..5<br>  User.find_or_create_by(username: &quot;Seed Data #{x}&quot;, password_digest: &quot;123#{x}&quot;)<br>end</pre><p>In the schema, I would ignore created_at and updated_at as those attributes are automatically provided whenever a new table is generated on the command line.</p><p>In the model, the only thing we need here is has_secure_password . Directly from the <a href="https://apidock.com/rails/v4.0.2/ActiveModel/SecurePassword/ClassMethods/has_secure_password">documentation</a> for has_secure_password , it</p><blockquote>Adds methods to set and authenticate against a BCrypt password. This mechanism requires you to have a password_digest attribute.</blockquote><p>In other words, has_secure_password encrypts the password the user inputs when it is created and an authentication method whenever the user inputs their decrypted password (i.e., the password they originally used). This is because the encrypted password, password_digest , is saved in the database.</p><p>In the seed data, we are creating five instances of a User by using a for loop and the method find_or_create_by . Personally, I like to use find_or_create_by because it will not create an instance of a model that has the same attributes. This will prevent any duplicated data within my seed data and also follows the notion that data should be not duplicated for users.</p><p>Now that we have everything set up, let’s start creating the seed data.</p><h3>Creating Seed Data</h3><p>Like any Rails application, we can run the seed file using rails db:seed in the command line. To double-check what we expected to get, let’s look at the seed in the console. This can be done by running rails c in the command line, and then typing User.all to get all of the instances of Users. This should all be our seed data. Below is what was outputted:</p><pre>2.6.1 :001 &gt; User.all</pre><pre><strong>User Load (2.5ms)</strong>  <strong>SELECT  &quot;users&quot;.* FROM &quot;users&quot; LIMIT ?</strong>  [[&quot;LIMIT&quot;, 11]]</pre><pre>=&gt; #&lt;ActiveRecord::Relation [#&lt;User id: 1, username: &quot;Seed Data 1&quot;, password_digest: &quot;1231&quot;, created_at: &quot;2020-01-13 01:38:04&quot;, updated_at: &quot;2020-01-13 01:38:04&quot;&gt;, #&lt;User id: 2, username: &quot;Seed Data 2&quot;, password_digest: &quot;1232&quot;, created_at: &quot;2020-01-13 01:38:04&quot;, updated_at: &quot;2020-01-13 01:38:04&quot;&gt;, #&lt;User id: 3, username: &quot;Seed Data 3&quot;, password_digest: &quot;1233&quot;, created_at: &quot;2020-01-13 01:38:04&quot;, updated_at: &quot;2020-01-13 01:38:04&quot;&gt;, #&lt;User id: 4, username: &quot;Seed Data 4&quot;, password_digest: &quot;1234&quot;, created_at: &quot;2020-01-13 01:38:04&quot;, updated_at: &quot;2020-01-13 01:38:04&quot;&gt;, #&lt;User id: 5, username: &quot;Seed Data 5&quot;, password_digest: &quot;1235&quot;, created_at: &quot;2020-01-13 01:38:04&quot;, updated_at: &quot;2020-01-13 01:38:04&quot;&gt;]&gt;</pre><pre>2.6.1 :002 &gt;</pre><p>Hm, that seems strange. Although the users were created, it seems that each password was not encrypted. The seed data does not accurately reflect an actual user which means the seed data creation code needs to be tweaked somewhere.</p><h3>Looking at the Source Code</h3><p>Unfortunately in the documentation, it doesn’t directly address what happens in the case when the password is not encrypted at the point of creation. Below is a snippet of code from the example in the documentation.</p><pre><em># Schema: User(name:string, password_digest:string)<br></em><strong>class </strong><a href="https://apidock.com/rails/User">User</a> <strong>&lt;</strong> <a href="https://apidock.com/rails/ActiveRecord">ActiveRecord</a><strong>::</strong>Base<br>  <a href="https://apidock.com/rails/ActiveModel/SecurePassword/ClassMethods/has_secure_password">has_secure_password</a><br><strong>end</strong><br><br>user <strong>=</strong> <a href="https://apidock.com/rails/User">User</a><strong>.</strong>new<strong>(</strong>name<strong>:</strong> <strong>&#39;</strong>david<strong>&#39;,</strong> password<strong>:</strong> <strong>&#39;&#39;,</strong> password_confirmation<strong>:</strong> <strong>&#39;</strong>nomatch<strong>&#39;)</strong></pre><p>It seems when creating a new user, the attribute is supposed to be password in lieu of password_digest . But in the comment on the first line, the schema also has an attribute of password_digest . There seems to be a weird disconnect. Typically, the attributes in the creation of an instance of a model is reflected in the schema as well, yet in this case, it’s not. The documentation doesn’t explain this disconnect. However, the documentation does provide the source code for has_secure_password , so let’s open that up.</p><p>I won’t copy and paste the entire source code, but below are the parts relevant to creating our seed data.</p><pre><em># File activemodel/lib/active_model/secure_password.rb, line 42</em><br>      <strong>def </strong>has_secure_password<strong>(</strong>options <strong>=</strong> <strong>{})</strong><br>        <em># Load bcrypt-ruby only when has_secure_password is used.</em><br>        <em># This is to avoid ActiveModel (and by extension the entire framework)</em><br>        <em># being dependent on a binary library.</em><br>        <strong>begin</strong><br>          gem <strong>&#39;</strong>bcrypt-ruby<strong>&#39;,</strong> <strong>&#39;</strong>~&gt; 3.1.2<strong>&#39;</strong><br>          require <strong>&#39;</strong>bcrypt<strong>&#39;</strong><br>        <strong>rescue</strong> LoadError<br>          $stderr<strong>.</strong>puts <strong>&quot;</strong>You don&#39;t have bcrypt-ruby installed in your application. Please add it to your Gemfile and run bundle install<strong>&quot;</strong><br>          <strong>raise</strong><br>        <strong>end</strong><br><br>        attr_reader :password<br><br>        include InstanceMethodsOnActivation<br><br>        ...</pre><pre>      <strong>end</strong><br>    <strong>end</strong><br><br>    <strong>module </strong>InstanceMethodsOnActivation</pre><pre>      ...</pre><pre>      <em># Encrypts the password into the +password_digest+ attribute, only if the</em><br>      <em># new password is not blank.</em><br>      <em>#</em><br>      <em>#   class User &lt; ActiveRecord::Base</em><br>      <em>#     has_secure_password validations: false</em><br>      <em>#   end</em><br>      <em>#</em><br>      <em>#   user = User.new</em><br>      <em>#   user.password = nil</em><br>      <em>#   user.password_digest # =&gt; nil</em><br>      <em>#   user.password = &#39;mUc3m00RsqyRe&#39;</em><br>      <em>#   user.password_digest # =&gt; &quot;$2a$10$4LEA7r4YmNHtvlAvHhsYAeZmk/xeUVtMTYqwIvYY76EW5GUqDiP4.&quot;</em><br>      <strong>def </strong>password=<strong>(</strong>unencrypted_password<strong>)</strong><br>        <strong>unless</strong> unencrypted_password<strong>.</strong>blank?<br>          @password <strong>=</strong> unencrypted_password<br>          cost <strong>=</strong> ActiveModel<strong>::</strong>SecurePassword<strong>.</strong>min_cost <strong>?</strong> BCrypt<strong>::</strong>Engine<strong>::</strong>MIN_COST <strong>:</strong> BCrypt<strong>::</strong>Engine<strong>.</strong>cost<br>          self<strong>.</strong>password_digest <strong>=</strong> BCrypt<strong>::</strong>Password<strong>.</strong>create<strong>(</strong>unencrypted_password<strong>,</strong> cost<strong>:</strong> cost<strong>)</strong><br>        <strong>end</strong><br>      <strong>end</strong><br><br>      ...</pre><pre>    <strong>end</strong><br>  <strong>end</strong></pre><p>This may be a lot to take in at first but its actually not all that bad. If you understand Ruby methods and rescues, everything else is straightforward.</p><p>In the has_secure_password method, it starts with a rescue. This is to confirm that you have the gem bcrypt in your bundle and installed prior to moving forward. Next, it has a reader method to read the password attribute and uses the module InstanceMethodsOnActivation . This is where clarity on the disconnect comes in.</p><p>The password method has an equal sign after the method name, which I am unfamiliar with. After a quick Google search, the link below can explain this much better in a way that I can rephrase it.</p><p><a href="https://stackoverflow.com/questions/5398919/what-does-the-equal-symbol-do-when-put-after-the-method-name-in-a-method-d">What does the equal (&#39;=&#39;) symbol do when put after the method name in a method definition?</a></p><p>When the password is being assigned (i.e., user.password = ), the password method is invoked. Although I do not know what is happening with the line cost <strong>=</strong> ActiveModel<strong>::</strong>SecurePassword<strong>.</strong>min_cost <strong>?</strong> BCrypt<strong>::</strong>Engine<strong>::</strong>MIN_COST <strong>:</strong> BC , rest assure that this is not relevant to the topic of this blog. This involves the use of the BCrypt library which encrypts the password.</p><p>However, we are interested in the last line of the password method: self<strong>.</strong>password_digest <strong>=</strong> BCrypt<strong>::</strong>Password<strong>.</strong>create<strong>(</strong>unencrypted_password<strong>,</strong> cost<strong>:</strong> cost<strong>) . </strong>Like every Ruby method, the last line of the method is what is returned. In this case, the self , which would be an instance of the user, is assigning the attribute, password_digest , with the encrypted password, which is created by the BCrypt library.</p><p>So, in a nutshell, the has_secure_password contains the InstancesMethodsOnActivation , which “converts” the password attribute from the seed data to password_digest as reflected in the schema.</p><p>With this new discovery, let’s change the seed data attribute from password_digest to password .</p><pre>//Revised Seed data<br>for x in 1..5<br>  User.find_or_create_by(username: &quot;Seed Data #{x}&quot;, password: &quot;123#{x}&quot;)<br>end</pre><p>Let’s run this seed data! And… this is what appears:</p><pre>rails aborted!</pre><pre>ActiveRecord::StatementInvalid: SQLite3::SQLException: no such column: users.password: SELECT  &quot;users&quot;.* FROM &quot;users&quot; WHERE &quot;users&quot;.&quot;username&quot; = ? AND &quot;users&quot;.&quot;password&quot; = ? LIMIT ?</pre><p>The error above appeared!</p><h3>Order of Operations With find_or_create_by</h3><p>According to the <a href="https://apidock.com/rails/v4.0.2/ActiveRecord/Relation/find_or_create_by">documentation</a> for find_or_create_by :</p><blockquote>Finds the first record with the given attributes, or creates a record with the attributes if one is not found:</blockquote><p>Finding the first record with the given attributes also coincides with the error that we received. In the error, the SQL statement is selecting all rows where the user.username and user.password matches with our input, except there is no column with the name password because our schema contains password_digest and username .</p><p>Since the SQL statement fails at the find part, it will never reach the create part of the find_or_create_by method. However, as mentioned earlier in this blog, we needed to change the attribute of the seed data from password_digest to password because of the has_secure_password method.</p><p>To circumvent the error, I would need to change the find_or_create_by method to create . Originally, I wanted to use the find_or_create_by method to avoid duplicates. Given the encryption methods from the BCrypt library, there should never be a case where the encrypted passwords are exactly the same, hence there should never be duplicates with the exact same attributes.</p><p>The new revised code for the seed data now looks like the following:</p><pre>//Revised Seed data (again)<br>for x in 1..5<br>  User.create(username: &quot;Seed Data #{x}&quot;, password: &quot;123#{x}&quot;)<br>end</pre><p>Let’s run this and see what happens!</p><p>Looks like the code completed running via rails db:seed but let’s double check. We can enter the rails console via rails c and typing in User.all .</p><pre>// ♥ rails c</pre><pre>Running via Spring preloader in process 24545</pre><pre>Loading development environment (Rails 5.2.4.1)</pre><pre>2.6.1 :001 &gt; User.all</pre><pre><strong>User Load (4.5ms)</strong>  <strong>SELECT  &quot;users&quot;.* FROM &quot;users&quot; LIMIT ?</strong>  [[&quot;LIMIT&quot;, 11]]</pre><pre>=&gt; #&lt;ActiveRecord::Relation [#&lt;User id: 1, username: &quot;Seed Data 1&quot;, password_digest: &quot;$2a$12$Gk1Hruq4rpHshJ.dJNxo/u0BKJce32ytHwoBIOFAUP1...&quot;, created_at: &quot;2020-01-13 03:48:32&quot;, updated_at: &quot;2020-01-13 03:48:32&quot;&gt;, #&lt;User id: 2, username: &quot;Seed Data 2&quot;, password_digest: &quot;$2a$12$jUBRmNiFp4NxK.nPWdB45ulg8LzB3Vk1Kg5d9PKg0bv...&quot;, created_at: &quot;2020-01-13 03:48:32&quot;, updated_at: &quot;2020-01-13 03:48:32&quot;&gt;, #&lt;User id: 3, username: &quot;Seed Data 3&quot;, password_digest: &quot;$2a$12$PjTfpqjndExTDWDBsmDpne4T0trwnPrKcxM16FAq4xG...&quot;, created_at: &quot;2020-01-13 03:48:32&quot;, updated_at: &quot;2020-01-13 03:48:32&quot;&gt;, #&lt;User id: 4, username: &quot;Seed Data 4&quot;, password_digest: &quot;$2a$12$Vr6IFEBoSEM4slCnlUM5kOZNIyeUXKojOoB04QH0maq...&quot;, created_at: &quot;2020-01-13 03:48:33&quot;, updated_at: &quot;2020-01-13 03:48:33&quot;&gt;, #&lt;User id: 5, username: &quot;Seed Data 5&quot;, password_digest: &quot;$2a$12$RiklTVCJDw4E9CV14E6eUeyXWFn/UbEciDa0HKwceQk...&quot;, created_at: &quot;2020-01-13 03:48:33&quot;, updated_at: &quot;2020-01-13 03:48:33&quot;&gt;]&gt;</pre><p>Success! We were able to create seed data with encrypted passwords!</p><h3>Key Takeaway</h3><p>Understand the portions of the source code of third party libraries or existing methods you are using that are relevant to your code (i.e., know what’s happening “under the hood”). Although it’s impossible to understand every single line of code, understanding the relevant parts will immensely help you debug after you’ve exhausted all other options.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3bca47cb5757" width="1" height="1" alt=""><hr><p><a href="https://medium.com/swlh/understanding-whats-happening-under-the-hood-with-source-codes-and-existing-methods-3bca47cb5757">Understanding What’s Happening “Under the Hood” with Source Codes and Existing Methods</a> was originally published in <a href="https://medium.com/swlh">The Startup</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>