<?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 Tina Luk on Medium]]></title>
        <description><![CDATA[Stories by Tina Luk on Medium]]></description>
        <link>https://medium.com/@tina-luk-tina?source=rss-49d75f61c6ac------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*ze4uv2D33ovlhRRp</url>
            <title>Stories by Tina Luk on Medium</title>
            <link>https://medium.com/@tina-luk-tina?source=rss-49d75f61c6ac------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 23 Nov 2026 00:35:19 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@tina-luk-tina/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[JavaScript: Fun Intersection of 2 Linked Lists]]></title>
            <link>https://blog.devgenius.io/javascript-fun-intersection-of-2-linked-lists-ae6949594aa9?source=rss-49d75f61c6ac------2</link>
            <guid isPermaLink="false">https://medium.com/p/ae6949594aa9</guid>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[data-structures]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[leetcode]]></category>
            <category><![CDATA[algorithms]]></category>
            <dc:creator><![CDATA[Tina Luk]]></dc:creator>
            <pubDate>Mon, 20 Sep 2021 20:10:16 GMT</pubDate>
            <atom:updated>2021-09-21T00:02:16.865Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/742/1*BxgUmdeRTaUeBl_BoE4T-A.png" /><figcaption>Find Intersection of Two Singly Linked Lists</figcaption></figure><p>This is an interesting problem — find the node of intersection for two singly Linked Lists. For the example above, node C1 is the intersection node.</p><h3>Naïve Solution</h3><p>A naïve approach would be to iterate over each node Linked List A and cross check if that same pointer exists in Linked List A.</p><p>Assuming Linked List A is length <strong><em>M</em></strong> and Linked List B is length <strong><em>N.</em></strong></p><p>Time complexity is O(M * N).</p><p>We can do better. Let’s improve the solution.</p><h3>Two Pointers Solution</h3><p>Let’s use the following as problem:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/742/1*EdUtJb21JAWkAmN5NdCEWQ.png" /></figure><p>The two pointers solution is so clever and simple!</p><p>Pretty much we need to concatenate the two linked lists in opposite order, <strong>A + B</strong> and <strong>B + A</strong>. This will help us line up the ends of the two lists.</p><p>Let’s redirect the tail’s next to the head of the other linked list. A’s tail next goes to the B’s head. B’s tail next goes to A’s head. As shown below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OnpSd3qGofjCSHLuUXnnPg.png" /></figure><p>Now the two lists are essentially the same length!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/718/1*c0BcIGenO9ku7KZ29fnc1w.png" /></figure><p>Now we can just check if at some point the two lists merge or intersect at the same node. And if they don’t intersect, we will exit at null when the list ends.</p><p><strong>JavaScript Solution:</strong></p><pre>var getIntersectionNode = function(headA, headB) {<br>    let a = headA;<br>    let b = headB;<br>    <br>    while (a != b) {<br>        a = !a ? headB : a.next;<br>        b = !b ? headA : b.next;<br>    }<br>    <br>    return a;<br>};</pre><p>In summary, we keep traveling down list A and list B if the node exists. If we come to a point where the node does not exist. If we are at the end of list A we then send our current pointer to the head of B and vice versa. Eventually, our A and B pointers will now cross at the intersection node at the same time as we are travelling, which we will then exit our loop and return that node.</p><p>Also the time complexity is O(M+N)!</p><p>This is a fun, clever problem and solution, wanted to share!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ae6949594aa9" width="1" height="1" alt=""><hr><p><a href="https://blog.devgenius.io/javascript-fun-intersection-of-2-linked-lists-ae6949594aa9">JavaScript: Fun Intersection of 2 Linked Lists</a> was originally published in <a href="https://blog.devgenius.io/">Dev Genius</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Mom in Tech: I made it!]]></title>
            <link>https://blog.devgenius.io/mom-in-tech-i-made-it-cada3fd555af?source=rss-49d75f61c6ac------2</link>
            <guid isPermaLink="false">https://medium.com/p/cada3fd555af</guid>
            <category><![CDATA[motherhood]]></category>
            <category><![CDATA[women]]></category>
            <category><![CDATA[job-hunting]]></category>
            <category><![CDATA[inspiration]]></category>
            <category><![CDATA[women-in-tech]]></category>
            <dc:creator><![CDATA[Tina Luk]]></dc:creator>
            <pubDate>Sun, 05 Sep 2021 07:21:35 GMT</pubDate>
            <atom:updated>2021-09-06T07:17:31.413Z</atom:updated>
            <content:encoded><![CDATA[<p>A toddler, a 2 month old, breastfeeding, boot camp and finally transitioned out of my old career into a new tech job. I made it! It paid off, I landed a frikin job and one that I’m actually really excited about within a month!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*uOpEQ-vowrFgSsq3" /><figcaption>Photo by <a href="https://unsplash.com/@julianhochgesang?utm_source=medium&amp;utm_medium=referral">Julian Hochgesang</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3><strong>Background: Where I was a month ago</strong></h3><p>Let’s just say it felt like I couldn’t get a break. My kids were constantly getting sick. My little man had cradle cap all over him including his precious face. I had postpartum side effects like anxiety, depression and body dysmorphia. I had terrible mom guilt too. Plus, above all this I hadn’t coded since I gave birth. My anxiety and imposter syndrome was high, and I thought — I really have to fake it to make it now.</p><h3>My secret recipe to making it</h3><p>With time restrictions in my life, these were the ingredients for me to success.</p><ol><li>5 quality applications 5 days a week</li><li>2 to 5 LeetCode Problems 5 days a week</li><li>Developing mini full stack apps, if time permitted</li><li>Support system whom I constantly Face Timed (this was my KEY to making it)</li><li>An amazing little baby that rarely cried during the day (good time management)</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*5vQkI487ltsHoKXC" /><figcaption>Photo by <a href="https://unsplash.com/@tamanna_rumee?utm_source=medium&amp;utm_medium=referral">Tamanna Rumee</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>Let’s start —</h3><h3><strong>5 quality applications 5 days a week</strong></h3><p>I had a pretty solid resume and cover letter in place already before the baby came. I just had to get myself out there in the job market.</p><p>Tools that I definitely recommend:</p><ul><li><a href="https://huntr.co/">Huntr</a> — Organize your job search. I applied a lot and got rejected ALOT!</li><li><a href="https://www.hiretechladies.com/">HireTechLadies</a> — An amazing job board for all you women out there. Most of my interviews and traction was because of this job board.</li><li><a href="https://cultivatedculture.com/resume-scanner/">Scan Your Resume</a> — Scan your resume to the job posting. The link here is a free resume scanner. Try to at least hit 70% match. Also, I only applied this technique to jobs I really wanted or jobs for larger companies.</li></ul><p>I spent about 2–3 hours a day on this area.</p><h3>LeetCode Problems 5 days a week</h3><p>My relationship with LeetCode is definitely a love-hate. I love solving the problem but hate when I can’t and I need more time to focus! Good thing is that you can actually just checkout the solution or discussion page for that problem and reverse engineer from the solution.</p><p>Some tips and tools:</p><ul><li>Complete at least 2 to 5 problems a day (ramp up to Medium difficulty)</li><li><a href="https://seanprashad.com/leetcode-patterns/">Leetcode Patterns</a> — Use this resource for which problems to start on or target.</li><li><a href="https://chrome.google.com/webstore/detail/leethub/aciombdipochlnkbpcbgdpjffcfdbggi?hl=en">LeetHub</a> — An amazing extension. This extension automatically creates a repo for you and whenever you complete a LeetCode problem, it pushes to your GitHub, keeping it active! How convenient is that?!</li><li>If you’re stuck, don’t spend too much time. Look at the solution, reverse engineer, understand the concept, practice and reinforce again on a similar problem.</li></ul><p>I spent about 2–3 hours a day on this area.</p><h3>Develop mini full stack apps</h3><p>Programming is a muscle. I hadn’t used this muscle for over month since the new baby and my programming muscle was lacking. I needed to work this muscle again and the best way was building a full stack app, refamiliarizing myself with various tech stacks and getting rid of this imposter syndrome I was facing!</p><p>For me, this was the last item on my list for the day. Some days I wasn’t able to contribute to this area. However, I always made sure I submitted 5 applications and did LeetCode.</p><p>This is definitely a creative, fun area to develop an app of your interest, troubleshoot and optimize!</p><h3>My Support System</h3><p>My support system was key and motivation I needed to stay the course. They helped me prepare and reflect on interviews, talk about my concerns, uplifted and encouraged me when I had major imposter syndrome going on. Here’s a list of my people:</p><ul><li>My brother and sister</li><li>My baby daddy</li><li>Career services manager from boot camp</li><li>My cohort mates</li></ul><p>Here’s how often I reached out:</p><ul><li>Before I even had any interviews</li><li>Before and after every single interview</li><li>After I received an offer</li><li>In summary, at least once a day (usually multiple times a day)</li></ul><p>They honestly made such a big impact in my success.</p><h3>Time Management</h3><p>Thankfully, I was able to send my toddler to daycare because when she is home, it’s extremely difficult to have time to grind and focus. This area is a big challenge for new moms when you are trying to schedule your day around an unpredictable little human.</p><p>My advice here:</p><ul><li>Do feedings before interview</li><li>Try to have someone watch your baby during scheduled interviews. If not, 30 minutes before interview, feed, burp, put baby in swinger, and give yourself 10 minutes to prep and refresh on the company, position and your resume.</li><li>Schedule interviews around time blocks baby is usually napping. This may not be predictable but try your best.</li><li>Don’t forget to give your baby(s) some love! I like to dance with my boy during the day and give baby massages. When my girl is home from daycare, I make sure she has my attention.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*wPYJh_aglTlAEP-z" /><figcaption>Photo by <a href="https://unsplash.com/@hillshirefarm?utm_source=medium&amp;utm_medium=referral">Hillshire Farm</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>That’s a wrap!</h3><p>Moms can have it all. They can program, have babies, raise kids, learn and land a job! I still have imposter syndrome till this day but at least I know I made it. I can change careers, be a mom, clean up poop and the house and learn to code. I hope I can inspire some other women and mommies out there in the world. :)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cada3fd555af" width="1" height="1" alt=""><hr><p><a href="https://blog.devgenius.io/mom-in-tech-i-made-it-cada3fd555af">Mom in Tech: I made it!</a> was originally published in <a href="https://blog.devgenius.io/">Dev Genius</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[JavaScript: Merge Sort Algorithm]]></title>
            <link>https://blog.devgenius.io/javascript-merge-sort-algorithm-bf46d42f175?source=rss-49d75f61c6ac------2</link>
            <guid isPermaLink="false">https://medium.com/p/bf46d42f175</guid>
            <category><![CDATA[recursion]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[computer-science]]></category>
            <category><![CDATA[problem-solving]]></category>
            <category><![CDATA[algorithms]]></category>
            <dc:creator><![CDATA[Tina Luk]]></dc:creator>
            <pubDate>Mon, 02 Nov 2020 22:08:55 GMT</pubDate>
            <atom:updated>2020-11-03T08:35:15.016Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2Xl0wf6WZnVfinVPUn81bw.png" /><figcaption><a href="https://www.programiz.com/dsa/merge-sort">https://www.programiz.com/dsa/merge-sort</a></figcaption></figure><h3>What is sorting?</h3><p>Sorting is rearranging a set of data into a specific order such as ascending to descending for numbers, or vice versa. A sorting algorithm takes in a given array or list and outputs a sorted array or list.</p><p>Sorting is applied everywhere. When we are on a website and sorting listings by lowest price to highest, ratings, etc. or searching for a book at the library. The concept of sorting makes it easier to arrange sets of data, therefore making it easier to search.</p><h3>Types of Sorting Algorithms</h3><p>There are many types of sorting algorithms. Sorting techniques are mainly differentiated by <a href="https://www.hackerearth.com/practice/basic-programming/complexity-analysis/time-and-space-complexity/tutorial/#:~:text=Time%20complexity%20of%20an%20algorithm,the%20length%20of%20the%20input.">time complexity and space complexity.</a> As the name implies, time complexity is the amount of time an algorithm takes to run as a function of the input length and space complexity is the amount of space or memory required as a function of input length. Below lists a a few different types of sorting algorithms:</p><ul><li>Quick sort</li><li>Bubble sort</li><li><strong>Merge sort</strong></li><li>Insertion sort</li><li>Heap sort</li></ul><p><a href="https://www.interviewbit.com/tutorial/sorting-algorithms/">Sorting Algorithms - InterviewBit</a></p><h3>What is merge sort?</h3><p>This article covers merge sort. Merge sort is a sorting technique that is based on divide and conquer. The worst case time complexity is O(n log(n)) and space complexity is O(n).</p><p>Merge sort is a very popular sorting algorithm and uses a recursive approach.</p><h3><strong>How does merge sort work?</strong></h3><p>The following recursive steps take place for merge sort to work:</p><ol><li>Divide given array of values in half</li><li>Continue to divide until reached base case of a single value</li><li>Merge the two halves in a sorted manner by comparing the values.</li><li>Pop off the call stack with the sorted half and continue to divide, merge and sort.</li></ol><p>Below shows a diagram and steps of an example input using merge sort.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XB4P42h0PS1vF0NkO_oJbw.png" /><figcaption><a href="https://www.programiz.com/dsa/merge-sort">https://www.programiz.com/dsa/merge-sort</a></figcaption></figure><p>Steps 1, 2, 3 we are dividing the array until we hit the base case. The base case is when we reach a point we can no longer divide the values of the array. There is only a single value in the array. Same with steps 5, 6, 7 we are recursively dividing the array until we hit our base case and pop off the call stack. Step 8 merges the left and right halves are merged in a sorted manner, once merged we pop this returned value off the call stack and this is our right half for step 9. Step 9 does the same merge the left and right halves in a sorted manner. Step 10 now repeats the same recursive process again.</p><h3>What does this algorithm look like?</h3><pre>const mergeSort = function (array) {<br>  if (array.length &lt;= 1) {<br>    return array;<br>  }<br>  let mid = Math.floor(array.length / 2);<br>  let left = mergeSort(array.slice(0, mid));<br>  let right = mergeSort(array.slice(mid));<br>  return merge(left, right);<br>};</pre><p>The merge sort function accepts an array of values. This array is divided recursively until it hits the base case of length of 1. Once these sub arrays are returned and popped off the call stack the function continues and merges the right and left sub array. Inside the merge function it will return an a merge sorted array. Every time the merge function is used, the left and right sub arrays are already sorted. Therefore we are merging sorted arrays.</p><p>Below if the merge function.</p><pre>const merge = function (left, right) {<br>  let sorted = [];</pre><pre>  while (left.length &gt; 0 &amp;&amp; right.length &gt; 0) {<br>    if (left[0] &lt; right[0]) {<br>      sorted.push(left.shift());<br>    } else {<br>    sorted.push(right.shift());<br>    }<br>  }</pre><pre>  if (left.length &gt; 0) {<br>    sorted = sorted.concat(left);<br>  }<br>  if (right.length &gt; 0) {<br>    sorted = sorted.concat(right);<br>  }<br>  return sorted;<br>};</pre><p>The merge function accepts 2 sorted arrays. The function will merge these sorted arrays with a simple while loop comparing the first values in each array and popping them off and adding it into the new sorted array.</p><p>Hope this helps you understand merge sort better. Check out all the other sorting techniques, I know I need to.</p><p>I just finished my Junior phase of Hack Reactor bootcamp now. Took a 6 hour long technical assessment this past weekend. Excited to enter my senior phase and start actually building some pretty cool projects!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bf46d42f175" width="1" height="1" alt=""><hr><p><a href="https://blog.devgenius.io/javascript-merge-sort-algorithm-bf46d42f175">JavaScript: Merge Sort Algorithm</a> was originally published in <a href="https://blog.devgenius.io/">Dev Genius</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[DFS (Depth First Search) Traversal Techniques — Short and Sweet]]></title>
            <link>https://blog.devgenius.io/dfs-depth-first-search-traversal-techniques-short-and-sweet-1e4c134babcf?source=rss-49d75f61c6ac------2</link>
            <guid isPermaLink="false">https://medium.com/p/1e4c134babcf</guid>
            <category><![CDATA[algorithms]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Tina Luk]]></dc:creator>
            <pubDate>Tue, 06 Oct 2020 00:03:49 GMT</pubDate>
            <atom:updated>2020-10-06T07:47:24.457Z</atom:updated>
            <content:encoded><![CDATA[<h3>DFS (Depth First Search) Traversal Techniques — Short and Sweet</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/502/1*eyqACQAziXkSuMNmMeTa6A.png" /><figcaption><a href="https://thenafi36.wordpress.com/2014/09/26/uva-536-tree-recover/">https://thenafi36.wordpress.com/2014/09/26/uva-536-tree-recover/</a></figcaption></figure><h3>What is a binary tree?</h3><p>A binary tree is a tree data structure which each node has at most two children. The children are referred to as the left child and the right child. The top most node in the tree is referred to as the root node.</p><p>A tree is a collections of node(s). Nodes are connected by edges. Each node contains a value and it may or may not have a child node.</p><h3><strong>What is traversing a tree?</strong></h3><p>Traversing a tree is the process of visiting each node in the tree exactly once. There are 2 widely known techniques for traversing trees are:</p><ul><li>DFS or Depth First Search</li><li>BFS or Breadth First Search — Level Order Traversal</li></ul><p>We will focus on DFS (Depth First search) techniques. These algorithms can be generalized and applied to other types of trees beyond binary trees.</p><h3>3 DFS Traversal Techniques</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/514/1*c7nIgmTkEyR6A0Ql-ezUlA.png" /><figcaption><a href="https://www.journaldev.com/44201/breadth-first-search-depth-first-search-bfs-dfs">https://www.journaldev.com/44201/breadth-first-search-depth-first-search-bfs-dfs</a></figcaption></figure><ol><li>Inorder traversal — left, root, right 3 1 4 0 2</li><li>Preorder traversal — root, left, right 0 1 3 4 2</li><li>Postorder traversal — left, right, root 3 4 1 2 0</li></ol><p>Let’s first set up our binary tree data structure:</p><pre>function TreeNode(val, left, right) {<br>  this.val = (val===undefined ? 0 : val)<br>  this.left = (left===undefined ? null : left)<br>  this.right = (right===undefined ? null : right)<br>}</pre><h3><strong>Inorder traversal</strong></h3><p>Inorder traversal initially recurses on the left child node continuously until there is no left child for that root.</p><ol><li>Recurse on the left child node</li><li>Traverse the current root node</li><li>Recurse on the right child node</li></ol><p>As we pop off the call stack (exit each recursive function), we will continue pushing the value and recursing on the right node if it exists.</p><pre>var inorderTraversal = function(root) {<br>    let result = [];<br>    let helper = function(node) {<br>        if (node) {<br>            helper(node.left);<br>            result.push(node.val);<br>            helper(node.right);<br>        }<br>    }<br>    helper(root);<br>    return result;<br>};</pre><h3>Preorder traversal</h3><p>Similar to inorder however the steps are in a different order.</p><ol><li>Traverse the current root node</li><li>Recurse on the left child node</li><li>Recurse on the right child node</li></ol><pre>var preorderTraversal = function(root) {<br>    let result = [];<br>    let helper = function(node) {<br>        if (node) {<br>            result.push(node.val);<br>            helper(node.left);<br>            helper(node.right);<br>        }<br>    }<br>    helper(root);<br>    return result;<br>};</pre><h3>Postorder traversal</h3><p>Similar to inorder however the steps are in a different order.</p><ol><li>Recurse on the left child node</li><li>Recurse on the right child node</li><li>Traverse the current root node</li></ol><pre>var preorderTraversal = function(root) {<br>    let result = [];<br>    let helper = function(node) {<br>        if (node) {<br>            helper(node.left);<br>            helper(node.right);<br>            result.push(node.val);<br>        }<br>    }<br>    helper(root);<br>    return result;<br>};</pre><h3>Next challenge — How can we implement this iteratively?</h3><p>The same concept applies when implementing this algorithm iteratively. We can visualize the call stack as an array and continue to get add (push) sub trees onto the call stack until it’s time for it get popped off.</p><p>An example iterative algorithm for inorderTraversal of a binary tree.</p><pre>var inorderTraversal = function(root) {<br>    let result = [];<br>    let stack = [];<br>    while (root || stack.length &gt; 0) {<br>        if (root) {<br>            stack.push(root);<br>            root = root.left<br>        } else {<br>            let save = stack.pop();<br>            result.push(save.val);<br>            root = save.right;            <br>        }        <br>    }<br>    return result;<br>};</pre><p>Try to see how we can reorder the algorithm for the other 2 variants of DFS. What would the sequence of the call stack look like here?</p><p>I am on week 13 of Hack Reactor. We are now on our own building mini-apps! So far it’s been a great learning experience and who doesn’t love building things.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1e4c134babcf" width="1" height="1" alt=""><hr><p><a href="https://blog.devgenius.io/dfs-depth-first-search-traversal-techniques-short-and-sweet-1e4c134babcf">DFS (Depth First Search) Traversal Techniques — Short and Sweet</a> was originally published in <a href="https://blog.devgenius.io/">Dev Genius</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Power Set Algorithm with Recursion or Bits]]></title>
            <link>https://blog.devgenius.io/power-set-algorithm-with-recursion-or-bits-cc3ffcfc0daa?source=rss-49d75f61c6ac------2</link>
            <guid isPermaLink="false">https://medium.com/p/cc3ffcfc0daa</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[algorithms]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[problem-solving]]></category>
            <category><![CDATA[coding]]></category>
            <dc:creator><![CDATA[Tina Luk]]></dc:creator>
            <pubDate>Thu, 24 Sep 2020 17:57:37 GMT</pubDate>
            <atom:updated>2020-09-24T19:07:43.143Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/512/1*0nYzSI66v0Cng7BreoOJgA.jpeg" /><figcaption><a href="http://clipart-library.com/clipart/182935.htm">http://clipart-library.com/clipart/182935.htm</a></figcaption></figure><h3>What is a Power Set?</h3><p>A<a href="https://www.mathsisfun.com/sets/power-set.html"> Power Set</a> is a set of all the subsets of a set, including the empty set and the set itself. A <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set">Set</a> in JavaScript is a collection of values. A value in the Set may only occur once (no value is repeated); it is unique in the Set’s collection. With a given set, a power set are all the different ways we can select the values, including selecting none or all. The Power Set solution must not contain duplicate subsets.</p><p>For a set {a, b, c}, the following lists the power set of this set.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/253/1*vPO0MqYip6RAstQ9nCi-8A.png" /><figcaption><a href="https://www.mathsisfun.com/sets/power-set.html">https://www.mathsisfun.com/sets/power-set.html</a></figcaption></figure><h3>How many Subsets in a Power Set?</h3><p>A set with n elements has 2^n subsets. With our example, Set {a, b, c} has 3 elements therefore this set should have 2³ = 8 subsets.</p><p>Let’s consider a set with n elements {__, __, __, __ … __}. To create each subset, which may be empty, we go through each value in the set and select each as either absent or present. Therefore, each element has 2 options, being put in or not. The total number of subsets possible is:</p><p>2 * 2 * … * 2 = 2 ^ n.</p><p>Since each value in the set can either exist in the subset or not, you can use binary numbers (bits! because it can either be absent<strong> 0</strong> or present <strong>1 </strong>— I like to think of it as turning a light switch on or off, either that value is turned on or off). We will get into this later. Let’s start with another intuitive solution.</p><h3>Recursion</h3><p>The idea is the same that if there are n elements in the set, each element has 2 choices to either be included or not in the subset. With this idea we can form a recursive solution.</p><p>This a backtracking approach. The recursive function has 2 parameters a subset string and the current index. There is an outer results array that stores each subset created. The input string is looped through and one by one fix characters are added to each subset and recursed on. This generates all subsets starting from the previous subset. If the current index equals the length or size of the input, no iteration is needed and recursion ends. The results array continues to get updated as every subset is created.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*stMWsSt0Es4ciJ-GmPc_Dg.png" /></figure><pre>var powerSet = function (str) {<br>  let results = [];</pre><pre>  let findSubSets = (string, index) =&gt; {<br>    results.push(string);<br>    for (let i = index; i &lt; str.length; i++) {<br>      helper(string + str[i], i + 1);<br>    }<br>  };</pre><pre>  findSubSets(&quot;&quot;, 0);<br>  return results;<br>};</pre><pre>powerSet(&#39;abc&#39;); // [&#39;&#39;, &#39;a&#39;,  &#39;ab&#39;, &#39;abc&#39;, &#39;ac&#39;, &#39;b&#39;, &#39;bc&#39;, &#39;c&#39;]</pre><p>The time complexity for this solution is O(2^n).</p><h3>Mapping with Binary Bitmasks</h3><p>The power set can be found by generating binary numbers between 0 to 2^n-1, where n is the size of the given set. Where there is a “1” in the sequence, this means putting a corresponding value into that subset.</p><pre>a b c<br>1 1 1  // &#39;abc&#39;</pre><pre>a b c<br>1 0 1 // &#39;ac&#39;</pre><p>See example below, if there is “110” this is replaced by 1 <strong>a</strong>, 1 <strong>b</strong> and 0 <strong>c</strong> to result in a subset {a, b}. For all zeros, this corresponds to an empty subset and all ones corresponds to the entire input set.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9AQE11XRbb3J3KrIq5URjA.png" /><figcaption><a href="https://www.mathsisfun.com/sets/power-set.html">https://www.mathsisfun.com/sets/power-set.html</a></figcaption></figure><p>With bit-wise operators, we can operate on the binary level. Using the &lt;&lt; zero fill left shift operator, this operator will push in one or more zeros from the right and the left most bits fall off. The following fun with bits will get us the power set size. The power set can be though of counting from 0 unit 2^n-1.</p><pre>1 &lt;&lt; str.length // is equivalent to 2^n</pre><pre>ex. str = &#39;abc&#39;<br>1 &lt;&lt; str.length<br>1 &lt;&lt; 3 = 8 // 8 in binary is 1000 (3 zeros pushed in from right)<br>2^n = 2^3 = 8 // Power Set size</pre><p>With the power set size known, we can use the Bitwise AND (<strong>&amp;)</strong> operator. The Bitwise AND returns 1 only if both bits are 1.</p><p>0 &amp; 0 = 0</p><p>0 &amp; 1 = 0</p><p>1 &amp; 0 = 0</p><p>1 &amp; 1 = 1</p><p>The Bitwise AND let’s us map all the subsets and returns the power set.</p><p>The table below shows the mapping from 0 to 2^n-1 (i = outer loop). Each binary set has the bitwise AND performed on it against the index position of the string 0 to n (our inner loop). The inner loop is necessary to find out each binary digit within the current iteration count. If there is a ‘1’ in the result of this AND operation, the corresponding letter will be put in it’s place and added as a subset.</p><p>The table below shows <strong>(i — power set size) </strong>outer loop and our inner loop <strong>(j— input size) </strong>and how the corresponding bit operations are being calculated to determine whether to add a corresponding letter into the next subset.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*owTaEcENGvUV6i0IMO6v7w.png" /></figure><pre>var powerSet = function (str) {<br>  const results = [];</pre><pre>  for (let i = 0; i &lt; 1 &lt;&lt; str.length; i++) {<br>    let subset = &quot;&quot;;<br>    for (let j = 0; j &lt; str.length; j++) {<br>      if (i &amp; (1 &lt;&lt; j)) {<br>        subset += str[j];<br>      }<br>    }<br>    results.push(subset);<br>  }<br>  return results;<br>};</pre><p>The time complexity is O(n * 2^n). This is a nice solution as it simplifies the idea and verifies no solution is missing, but the time complexity is slower compared to the earlier recursive solution.</p><p>Hope this helps understand how to solve Power Set algorithm with two different approaches!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cc3ffcfc0daa" width="1" height="1" alt=""><hr><p><a href="https://blog.devgenius.io/power-set-algorithm-with-recursion-or-bits-cc3ffcfc0daa">Power Set Algorithm with Recursion or Bits</a> was originally published in <a href="https://blog.devgenius.io/">Dev Genius</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[JavaScript Asynchronous Operation — Read File Directory with Callback or Promises]]></title>
            <link>https://blog.devgenius.io/javascript-asynchronous-operation-read-file-directory-with-callback-or-promises-9d74a236a928?source=rss-49d75f61c6ac------2</link>
            <guid isPermaLink="false">https://medium.com/p/9d74a236a928</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[asynchronous]]></category>
            <category><![CDATA[promises]]></category>
            <category><![CDATA[coding]]></category>
            <dc:creator><![CDATA[Tina Luk]]></dc:creator>
            <pubDate>Mon, 14 Sep 2020 02:29:03 GMT</pubDate>
            <atom:updated>2020-09-14T07:16:31.744Z</atom:updated>
            <content:encoded><![CDATA[<h3>JavaScript Asynchronous Operation — Read File Directory with Callback or Promises</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*TRWc0saJY2LMbjwi" /><figcaption>Photo by <a href="https://unsplash.com/@qwitka?utm_source=medium&amp;utm_medium=referral">Maksym Kaharlytskyi</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3><strong>Asynchronous Operation — Why do we care?</strong></h3><p>JavaScript is a synchronous, blocking, single threaded language. Synchronous single threaded means JavaScript waits for the task to be completed before being able to move on to the next task. However, Asynchronous JavaScript makes it so much faster if each task takes a really long time! Instead of waiting for the task beforehand to move on, there can be independent threads to start the tasks simultaneously.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/779/1*6YjH0YEvGBxhdOHb3FRfqQ.png" /><figcaption><a href="http://www.phpmind.com/blog/2017/05/synchronous-and-asynchronous/">http://www.phpmind.com/blog/2017/05/synchronous-and-asynchronous/</a></figcaption></figure><p>In the computer programming world, synchronous and asynchronous may still be considered “fast” in human time. But let’s imagine a scenario if a request was sent to read an entire database of files and there are files in there are REALLY huge therefore take a long time to read. Instead of waiting, what if we can start reading the other files in the directory at the same time. This is Asynchronous JavaScript.</p><h3>Asynchronous Operation — Code Styles</h3><p>In JavaScript, functions are first class citizens. This means functions can be treated like values of other types. Functions can be passed to other functions as arguments, returned from other functions as values, and stored in variables.</p><p>Async operations are put into an event queue which runs after the main thread has finished processing so that they do not stop subsequent JavaScript from running.</p><p>There are 2 main asynchronous concepts that JavaScript uses which leverage functions first class citizenship:</p><ol><li>Async Callbacks</li><li>Promises</li></ol><p>For other examples, to help you further solidify your understanding of these 2 concepts.</p><ul><li><a href="https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Asynchronous/Introducing">Introducing asynchronous JavaScript - Learn web development | MDN</a></li><li><a href="https://scotch.io/courses/10-need-to-know-javascript-concepts/callbacks-promises-and-async">Callbacks, Promises, and Async</a></li></ul><p>Let’s consider an AJAX (Asynchronous JavaScript and XML) request to the server.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/693/1*i64GjRzGshRhSMUynG56EQ.png" /><figcaption><a href="http://www.phpmind.com/blog/2017/05/synchronous-and-asynchronous/">http://www.phpmind.com/blog/2017/05/synchronous-and-asynchronous/</a></figcaption></figure><p>The user clicks on the browser which results in sending an HTTP request to the server to read an entire directory, which could take some time. Instead of having the browser stop running any other functions and wait for the response, another function is set up to wait for this response and react when the response is received.</p><p>Let’s see how we can write these Asynchronous Operations.</p><h3><strong>Async Callbacks</strong></h3><p>Not all callbacks are asynchronous. A callback using .map() in this context isn’t being delayed.</p><pre>[1,2,3].map((i) =&gt; i + 5)</pre><p>On the other hand, waiting for the user to click to invoke a function. Waiting for a callback to execute during a particular time. This callback (the second parameter) is an async callback. Once the event listener (‘click’) is heard, the callback will execute.</p><pre>$(&#39;#btn&#39;).on(&#39;click&#39;, () =&gt;<br>  console.log(&#39;Callbacks are everywhere&#39;)<br>)</pre><p>A GET request has been sent to read the whole directory. Let’s read all files. For now we will just read the file name (not the file content because of the extra complexity) and return that data. The callbacks are using a pattern called <a href="https://medium.com/@b.essiambre/continuation-passing-style-patterns-for-javascript-5528449d3070#:~:text=Continuation%20Passing%20Style%20basically%20means,the%20last%20parameter%20of%20functions.">continuation passing style</a>. Notice also we are following the <a href="https://hashnode.com/post/whats-an-error-first-callback-in-nodejs-ciibz8ehi00lwj3xt257d72rt">error first callback</a> pattern that adopted by the nodejs community.</p><pre>const fs = require(&#39;fs&#39;);<br>const path = require(&#39;path&#39;);</pre><pre>exports.readAll = (callback) =&gt; {<br>  var data = [];<br>  fs.readdir(`${exports.dataDir}`, (err, files) =&gt; {<br>    if (err) {<br>      throw &#39;error reading dir&#39;;<br>    } else {<br>      files.forEach((file) =&gt; {<br>        id = file.slice(0, 5);<br>        data.push({ id: id, text: id });<br>      });<br>      callback(null, data);<br>    }<br>  });<br>};</pre><pre>exports.readOne = (id, callback) =&gt; { <br>  fs.readFile(`${exports.dataDir}/${id}.txt`, &#39;utf8&#39;, <br>  (err, text) =&gt; {<br>    if (err) {<br>      callback(new Error(`No item with id: ${id}`));<br>    } else {<br>      callback(null, { id, text });<br>    }<br>  });<br>};</pre><p>Unfortunately, if we add more layers of callbacks, which results in nested callbacks within nested callbacks, we enter the world of “Callback Hell”.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*W9g_kSHGR6SJ2E3g5OS10Q.png" /><figcaption><a href="https://medium.com/@js_tut/the-great-escape-from-callback-hell-3006fa2c82e">https://medium.com/@js_tut/the-great-escape-from-callback-hell-3006fa2c82e</a></figcaption></figure><p>A common approach to help us with “Callback hell” is to modularize our code well. This helps with the readability of “callback hell” however it may still be extremely hard to sequentially track what is happening.</p><h3><strong>Promises</strong></h3><p>Promises are the newer style of asynchronous code and specifically made for handling async operations. A promises will execute your request if the response is true. If not, a promise won’t. Promises have 3 states:</p><ul><li><strong>Pending </strong>— the initial state of the Promise before operation (request) begins</li><li><strong>Fulfilled </strong>— the operation (request) was completed</li><li><strong>Rejected </strong>— the operation (request) did not complete, there was an error</li></ul><p>Constructing a Promise uses the new keyword, creating a new instance of a Promise . The Promise constructor takes a single argument a (callback) function that has resolve and reject as it’s arguments.</p><pre>const promise = new Promise(function(resolve, reject) {<br>  // promise description<br>})</pre><p>resolve allows us to update the state of the promise to fulfilled.</p><p>reject allow us to update the state of the promise to rejected.</p><p>A promise is a plain JavaScript object and has the .then and .catch method which can be invoked. If the promise is fulfilled, the function passed into .then will be invoked. Otherwise if the promise is rejected (the async request fails), the function passed into .catch will be invoked.</p><h3>Chaining Promises</h3><p>The .then and .catch will return a new promise which allows us to chain promises. This is an improvement to our “callback hell” scenario. We can think more sequentially.</p><pre>function getPromise () {<br>  return new Promise((resolve) =&gt; {<br>    setTimeout(resolve, 2000)<br>  })<br>}<br><br>function logA () {<br>  console.log(&#39;A&#39;)<br>}<br><br>function logB () {<br>  console.log(&#39;B&#39;)<br>}<br><br>function logCAndThrow () {<br>  console.log(&#39;C&#39;)<br><br>  throw new Error()<br>}<br><br>function catchError () {<br>  console.log(&#39;Error!&#39;)<br>}<br><br>getPromise()<br>  .then(logA) // A<br>  .then(logB) // B<br>  .then(logCAndThrow) // C<br>  .catch(catchError) // Error!</pre><h3>Promisification and Promise.all</h3><p>Promisification is a simple transformation. Essentially it is the conversion of a function that is has an error first callback style and returns that as a promise. Function and libraries that are callback-based with the correct formatting can be ‘promisified’. See example of the asynchronous readFile in node’s fs-module.</p><pre>var readFile = Promise.promisify(require(&quot;fs&quot;).readFile);<br><br>readFile(&quot;myfile.js&quot;, &quot;utf8&quot;).then(function(contents) {<br>    return eval(contents);<br>}).then(function(result) {<br>    console.log(&quot;The result of evaluating myfile.js&quot;, result);<br>}).catch(function(e) {<br>    console.log(&quot;Error reading file&quot;, e);<br>});</pre><p>Transform the entire object with .promisifyAll will promisifisy the entire object going through the object’s properties and create an async equivalent of each function on the object and its prototype chain. The original methods are not overwritten but new promisified methods will have and Async-suffix.</p><pre>var fs = Promise.promisifyAll(require(&quot;fs&quot;));<br><br>fs.readFileAsync(&quot;myfile.js&quot;, &quot;utf8&quot;).then(function(contents) {<br>    console.log(contents);<br>}).catch(function(e) {<br>    console.log(&quot;Error reading file&quot;, e);<br>});</pre><p>With Promise.all() we can aggregate a group of promises in an array (an iterable) as an input and return a single Promise that resolves to an array of results.</p><ul><li>Resolves when every input Promise has resolved</li><li>Rejects when any of the input Promise has rejected</li></ul><p>This method is useful for aggregating results of multiple promises and used when multiple asynchronous tasks are dependent on another to complete successfully.</p><p>With all that we now know about promises let’s read our directory with the Promise Async operation.</p><pre>const fs = require(&#39;fs&#39;);<br>const path = require(&#39;path&#39;);<br>const Promise = require(&#39;bluebird&#39;);<br>const fsAsync = Promise.promisifyAll(fs);</pre><pre>exports.readOne = (id, callback) =&gt; {<br>  return fsAsync<br>    .readFileAsync(`${exports.dataDir}/${id}.txt`, &#39;utf8&#39;)<br>    .then((text) =&gt; callback(null, { id, text }))<br>    .catch((err) =&gt; callback(new Error(`No item with id: ${id}`)))<br>};</pre><pre>exports.readAll = (callback) =&gt; {<br>  var readFileAsync = Promise.promisify(exports.readOne);<br>  var promises = [];<br>  return fsAsync<br>    .readdirAsync(`${exports.dataDir}`).then((files) =&gt; {<br>      _.each(files, (file) =&gt; {<br>        var id = file.slice(0, 5);<br>        promises.push(readFileAsync(id));<br>      });<br>      Promise.all(promises)<br>        .then((promise) =&gt; callback(null, promise))<br>        .catch((err) =&gt; callback(<br>          new Error(&#39;error reading directory&#39;))<br>        );<br>  });<br>};</pre><p>With promises, we can now read the contents of each file in the directory asynchronously using Promise.all() . As we are reading the firection, each file is now being read as a promise and pushed into the promise array. If the all the files are read successfully, the callback in the RESTful route (Read all route) in the server will run.</p><p>Asynchronous operation is very powerful. It will be up to us to determine whether we want to run code synchronous or asynchronous depending on the task at hand. If an operation take time like navigating a database, it may be better to have another thread complete this task asynchronously.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9d74a236a928" width="1" height="1" alt=""><hr><p><a href="https://blog.devgenius.io/javascript-asynchronous-operation-read-file-directory-with-callback-or-promises-9d74a236a928">JavaScript Asynchronous Operation — Read File Directory with Callback or Promises</a> was originally published in <a href="https://blog.devgenius.io/">Dev Genius</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Linked List Algorithm: Is it a palindrome for singly-linked list?]]></title>
            <link>https://blog.devgenius.io/linked-list-algorithm-is-it-a-palindrome-for-singly-linked-list-3137291f76c9?source=rss-49d75f61c6ac------2</link>
            <guid isPermaLink="false">https://medium.com/p/3137291f76c9</guid>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[data-structures]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[algorithms]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Tina Luk]]></dc:creator>
            <pubDate>Mon, 31 Aug 2020 01:56:21 GMT</pubDate>
            <atom:updated>2020-08-31T07:51:44.754Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*v6S7BQibuojA8loZUu8wNw.png" /><figcaption><a href="https://www.educative.io/edpresso/what-is-a-linked-list">https://www.educative.io/edpresso/what-is-a-linked-list</a></figcaption></figure><h3>What is a Linked List?</h3><p>A linked list is a data structure made up of a chain of nodes connected by links. Each node contains a value and has a next pointer to the next node in the chain. The head pointer points to the first node and the last element points to null.</p><p>There are different types of linked lists:</p><ul><li>Singly Linked List (uni-directional)</li><li>Doubly Linked List (bi-directional)</li><li>Circular Linked List</li></ul><p>Linked lists have simple basic operations such as insertion, deletion, search. Unlike arrays, the pointers in the elements can be changed easily to insert or delete an element.</p><h3>What is a palindrome?</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yKs3dOTwWNI8Zmn0nlquJg.png" /></figure><p>A palindrome is a word, phrase, or sequence that reads the same backward as forward.</p><h3>Is a Linked List a palindrome?</h3><p>Now we know what a linked list and a palindrome is, how can we determine whether the given linked list is a palindrome.</p><p>With an array or a string, to determine whether these data sets is a palindrome there can be different simple solutions. A possible solution is to make a reverse copy and compare it to the original to see if the reverse copy is equal to the original. Another potential solution is to iterate through the array or string and compare the first element to the last element and continue to do this for each element heading towards the center.</p><p>As for a singly linked list, it is not as straight forward as a string or an array. This is because without a previous pointer or a tail pointer, we do not know the last node in the list or the previous node or can quickly determine the length of the list.</p><p>There are solutions that take up extra memory space. For example, store all values of the linked list into an array and determine whether that array is a palindrome. Or make a copy of the linked list, reverse the copy of the linked list and compare each value to the original.</p><p>Let’s think of solution that doesn’t take up extra memory by following these steps:</p><ol><li>Determine the mid point of the given linked list (by using 2 pointers)</li><li>Reverse the second half of the linked list</li><li>Compare the linked list values</li></ol><p>Let use this drawing as an example:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xBYG3YOWpojZg2T_wKQo-w.png" /><figcaption>Example. Is this Singly Linked List a palindrome?</figcaption></figure><h3>Determine the midpoint by using 2 pointers.</h3><ul><li>Fast pointer — Initially set to the same as head pointer, will move 2x faster than the slow pointer until it reaches the end</li><li>Slow pointer — Initially set to the same as head pointer, will move 1 node at a time along with the fast pointer.</li></ul><p>See how the slow and fast pointer travel through the linked list.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7xyBItdtDbZsQF1H9AXa1A.png" /></figure><pre>let slow = head;<br>let fast = head;<br>while (fast &amp;&amp; fast.next) {<br>  slow = slow.next<br>  fast = fast.next.next;<br>}</pre><h3><strong>Reverse 2nd half of Linked List</strong></h3><p>How can we reverse a linked list in general?</p><p>As we go through the linked list, we want our first node to be the last therefore it’s next pointer should point to null. With a prev, head and temp pointer we can have the head’s next point to the prev node and continue to do this as we move through the list. We need to have a temp pointer so the head knows which node to go to next.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Axy5tcWlruhunbenXQ6fgg.png" /></figure><pre>var reverse = function(head) {<br>  let prev = null;<br>  while (head) {<br>    let temp = head.next;<br>    head.next = prev;<br>    prev = head;<br>    head = temp;<br>  }<br>  return prev;<br>}</pre><p>Let’s go back to our example and take a look at what the 2nd half (with the slow pointer) being reverse would look like.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-VyVdTInJzUMtXkubB5ZLA.png" /></figure><p>With our head pointer and slow pointer and all the next pointers going towards the end or null. We can now …</p><h3><strong>Compare linked list values</strong></h3><p>As we traverse with either head or slow not equal to null, we can compare head’s value to slow’s value as we move towards the end (or null).</p><pre>while (slow) {<br>  if (head.val !== slow.val) {<br>    return false;<br>  }<br>    head = head.next;<br>    slow = slow.next<br>}</pre><p>Let’s put all the pieces together for our final solution.</p><pre>var isPalindrome = function(head) {<br>    let slow = head;<br>    let fast = head;<br>    while (fast &amp;&amp; fast.next) {<br>        slow = slow.next<br>        fast = fast.next.next;<br>    }<br>    slow = reverse(slow);<br>    while (slow) {<br>        if (head.val !== slow.val) {<br>            return false;<br>        }<br>        head = head.next;<br>        slow = slow.next<br>    }<br>    return true;<br>};</pre><pre>var reverse = function(head) {<br>    let prev = null;<br>    while (head) {<br>        let temp = head.next;<br>        head.next = prev;<br>        prev = head;<br>        head = temp;<br>    }<br>    return prev;<br>}</pre><p>There you go, not so bad when the steps are broken out and put together!</p><p>I wanted to keep this weeks article short and sweet with a simple data structure algorithm. In Hack Reactor this week, we did a react redux and thunk sprint which is a state management tool. I think it makes sense conceptually and going over the workings of the code it makes sense as well (sometimes, I have to think it through). I look forward to learning more about React hooks because it’s React’s own state management system. More to write about in the following weeks to come!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3137291f76c9" width="1" height="1" alt=""><hr><p><a href="https://blog.devgenius.io/linked-list-algorithm-is-it-a-palindrome-for-singly-linked-list-3137291f76c9">Linked List Algorithm: Is it a palindrome for singly-linked list?</a> was originally published in <a href="https://blog.devgenius.io/">Dev Genius</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Java Script: Let’s Talk React Basics]]></title>
            <link>https://blog.devgenius.io/java-script-lets-talk-react-basics-322629bb6e62?source=rss-49d75f61c6ac------2</link>
            <guid isPermaLink="false">https://medium.com/p/322629bb6e62</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[apps]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[reactjs]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Tina Luk]]></dc:creator>
            <pubDate>Mon, 24 Aug 2020 04:57:40 GMT</pubDate>
            <atom:updated>2020-08-24T07:24:39.171Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FGFRP0QNXfTCOfGl3cRTDg.png" /><figcaption><a href="https://abcntechnologies.com/wp-content/uploads/2019/12/reactjs.png">https://abcntechnologies.com/wp-content/uploads/2019/12/reactjs.png</a></figcaption></figure><h3>What is React?</h3><p><a href="https://reactjs.org/">React</a> is a JavaScript library for building user interfaces. React was developed by Facebook and Instagram. React deals with View in <a href="https://en.wikipedia.org/wiki/Model%E2%80%93view%E2%80%93controller">MVC </a>(Model — View — Controller). React is declarative, rather than imperative. <a href="https://codeburst.io/declarative-vs-imperative-programming-a8a7c93d9ad2">Declarative </a>code (such as HTML) is a programming paradigm that expresses <strong><em>what to do</em></strong> without describing the <strong><em>how to</em></strong>.</p><h3><strong>Why React?</strong></h3><p>React give you tools for interacting with the DOM that are much cleaner and effective than with raw JavaScript or jQuery. The HTML, CSS, JavaScript can be held in one component, they are like “super powered” HTML tags. It is fast and supports code modularity and reuse.</p><h3><strong>React Concepts</strong></h3><p>There are many <a href="https://reactjs.org/docs/introducing-jsx.html">react concepts</a> that all serve importance. To keep this post, concise and sweet we will discuss the basic foundational ones listed.</p><ol><li>Components</li><li>JSX</li><li>Rendering Elements</li><li>Function vs Class Components and Props</li><li>State and Handling Events</li></ol><p>There are many more main concepts with additional depth. This post attempts to summarize some main concepts at a high level.</p><h3><strong>React is Component-Based</strong></h3><p>Components are the building blocks to React written application. Imagine your UI (a web page application), this can be split into independent, reusable pieces. Consider each piece in isolation. Each piece is a <a href="https://www.w3schools.com/react/react_components.asp"><strong>component</strong></a><strong> </strong>as shown below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*Hr4F71bW9V5M60oe2RKkqA.png" /><figcaption><a href="https://cdn-media-1.freecodecamp.org/images/1*bvQNHjZOXcl-ds9A4AWYVg.png">https://cdn-media-1.freecodecamp.org/images/1*bvQNHjZOXcl-ds9A4AWYVg.png</a></figcaption></figure><p>Each component is a JavaScript function that returns (renders) React elements to the screen (DOM).</p><h3><strong>Does React need JSX ?</strong></h3><p><a href="https://reactjs.org/docs/jsx-in-depth.html">JSX</a> is a syntax extension to JavaScript. React uses this language to describe what the UI should look like. It looks like HTML but with the full power of JavaScript. See the example syntax.</p><pre>const element = &lt;h1&gt;Hello, world!&lt;/h1&gt;;</pre><p>JSX is not required for using React. However, JSX makes it very convenient. See the difference.</p><p>Code that does NOT use JSX:</p><pre>class Hello extends React.Component {<br>  render() {<br>    return React.createElement(&#39;div&#39;, null, `Hello ${this.props.toWhat}`);<br>  }<br>}<br><br>ReactDOM.render(<br>  React.createElement(Hello, {toWhat: &#39;World&#39;}, null),<br>  document.getElementById(&#39;root&#39;)<br>);</pre><p>Code written with JSX:</p><pre>class Hello extends React.Component {<br>  render() {<br>    return &lt;div&gt;Hello {this.props.toWhat}&lt;/div&gt;;<br>  }<br>}<br><br>ReactDOM.render(<br>  &lt;Hello toWhat=&quot;World&quot; /&gt;,<br>  document.getElementById(&#39;root&#39;)<br>);</pre><p>Try more snippets in <a href="https://babeljs.io/repl/#?presets=react&amp;code_lz=GYVwdgxgLglg9mABACwKYBt1wBQEpEDeAUIogE6pQhlIA8AJjAG4B8AEhlogO5xnr0AhLQD0jVgG4iAXyJA">Babel’s</a> online tool to appreciate JSX ES6 syntax.</p><p>Any valid JavaScript expression are placed inside curly braces in JSX. By default, React DOM escapes any values embedded in JSX before rendering. This prevents XSS attacks.</p><h3><strong>Rendering Elements</strong></h3><p>An element describes what is seen on the screen. React elements are plain objects where the <a href="https://reactjs.org/docs/react-dom.html#render">React DOM</a> uses to update the actual DOM. Elements are what components are made of.</p><p>In the HTML file, identify where you want to place the react element or component. For example, in the HTML file there is:</p><pre>&lt;div id=&quot;app&quot;&gt;&lt;/div&gt;</pre><p>Everything inside this &lt;div&gt; will be managed by the React DOM. An application built with just React have a single root DOM node. If React is integrated into an existing app, there may be varying root DOM nodes.</p><p>To render a React element or component, use <a href="https://reactjs.org/docs/react-dom.html#render">ReactDOM.render()</a>:</p><pre>ReactDOM.render(element, placeWeWantToPutElementOrComponent)</pre><pre>// example<br>const element = &lt;h1&gt;Hello, world&lt;/h1&gt;;<br>ReactDOM.render(element, document.getElementById(&#39;app&#39;));</pre><p>React only updates what is necessary. The React DOM compares the element and its children to the previous, and only applies the necessary DOM updates.</p><h3><strong>Functional vs Class Components and Props</strong></h3><p>We will discuss state in the following section. The main difference between functional and class components are:</p><ul><li>Functional Components are Stateless (simply accepts data and display them to UI)</li><li>Class Components are Stateful (more complex by implementing logic and state)</li></ul><p>Let’s write our first component as functional. Below is a simple functional component in ES6 syntax showing how we can put React components within another.</p><p><strong>Note: Always start component names with a capital letter. </strong>React treats components with lowercase letters as DOM tags &lt;div /&gt; and &lt;Container /&gt; represent a component.</p><p>Components can accept arbitrary inputs (called “props”, which stands for properties) and returns a React element. This is a way to pass data into components, making them more dynamic and reusable. Props are immutable and cannot be changed once passed in from a parent.</p><pre>const Component = () =&gt; (     <br>  &lt;h1&gt;I am a child component!&lt;/h1&gt; <br>);</pre><pre>const Container = (props) =&gt; (<br>&lt;div&gt;<br>  &lt;h1&gt;I am parent {props.name} component!&lt;/h1&gt;<br>  &lt;Component /&gt;<br>&lt;/div&gt;<br>);</pre><pre>ReactDOM.render(&lt;Container name=&quot;Container&quot; /&gt;, document.getElementById(&#39;app&#39;));</pre><p>We can re-write the Container component into a class component with Java Script&#39;s ES6 classes to make things more dynamic.</p><pre>class Container extends React.Component {<br>  render() {<br>    return (      <br>      &lt;div&gt;<br>        &lt;h1&gt;<br>           I am the parent {this.props.name} component!<br>        &lt;/h1&gt;<br>       &lt;Component /&gt; <br>     &lt;/div&gt;    <br>    );  <br>  }<br>}</pre><pre>const Component = () =&gt; (     <br>  &lt;h1&gt;I am a child component!&lt;/h1&gt; <br>);</pre><pre>ReactDOM.render(&lt;Container name=&quot;Container&quot; /&gt;, document.getElementById(&#39;app&#39;));</pre><p>The example above:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_2i7MiXejYuNLF5e5fmNvQ.png" /><figcaption>HTML Render from example above</figcaption></figure><ol><li>ReactDOM.render() renders the &lt;Container name=&quot;Container&quot; /&gt; to the DOM. The container component has {name=&quot;Container&quot;} as it’s props.</li><li>The &lt;Container /&gt; component returns a &lt;div &gt; with the &lt;h1 &gt; and the inner &lt;Component /&gt;</li><li>React DOM updates the DOM to match this</li></ol><p>Class components must have a function called render() . Both &lt;Container /&gt; components (functional and class) above are equivalent from React’s point of view. You should use functional components over class components unless you need component “<a href="https://reactjs.org/docs/state-and-lifecycle.html">state</a>” discussed in a later section. State lets React components change their output in response to user actions, network responses, and anything else.</p><h3><strong>State</strong></h3><p>To make applications interactive, our components need to do more than receive props. Class components can have information about their current situation which is called <strong>state </strong>stored in a Java Script object. State can be used to update and re-render data changes. State is only available on class components. The key word this inside the component refers to the component it’s within.</p><p>The simple example below has a ToDoList component with it’s current state as NOT being done (set to false).</p><pre>class ToDoList extends React.Component {<br>  constructor(props) {<br>    super(props);<br>    this.state = {<br>      done: false,<br>    };<br>  }</pre><pre>  render() {<br>    const status = this.state.done ? &#39;Good Work&#39; : &#39;YOU HAVE WORK&#39;;<br>    return (      <br>      &lt;div&gt;<br>        &lt;h1&gt;<br>           {status}<br>        &lt;/h1&gt;<br>     &lt;/div&gt;    <br>    );  <br>  }<br>}</pre><pre>ReactDOM.render(&lt;Container name=&quot;Container&quot; /&gt;, document.getElementById(&#39;app&#39;));</pre><p>Once state is initialized, the way to update state is with setSate(). Do not modify state directly. The only place to assign this.state is the constructor.</p><p>Let’s interact with our component to let it know we have completed our ToDoList and display the correct status. Let’s say there is a button we can click to inform this change.</p><h3>Event Handling</h3><p>Handing <a href="https://reactjs.org/docs/handling-events.html">events </a>with React elements is similar to handling events on DOM elements. There are some differences.</p><ul><li>React events use camelCase, not lowercase</li><li>Pass a function within curly braces in JSX as the event handler, not a string</li><li>Cannot return false to prevent default behavior, must preventDefault() explicitly</li><li>Reference <a href="https://reactjs.org/docs/events.html#clipboard-events">SyntheticEvent</a>s reference defined by React</li><li>Be careful with this in JSX callback. Class methods are not bound by default. Remember to bind this.eventHandleMethod.bind(this) or with ES6 arrow function before passing into onClick .</li></ul><p>Let’s add a way the user can interact with the component by clicking a button. When they click the button, let’s update the state done to be true with setSate() , which therefore updates the status.</p><pre>class ToDoList extends React.Component {<br>  constructor(props) {<br>    super(props);<br>    this.state = {<br>      done: false,<br>    };<br>  }</pre><pre>  handleClick(event) {<br>    if (!this.state.done) {<br>      this.setState({ done: true });<br>    } else {<br>      this.setState({ done: false });<br>    } <br>  };</pre><pre>  render() {<br>    const status = this.state.done ? &#39;Good Work&#39; : &#39;YOU HAVE WORK&#39;;<br>    return (      <br>      &lt;div&gt;<br>        &lt;h1&gt;<br>           {status}<br>        &lt;/h1&gt;<br>        &lt;button onClick={this.handleClick.bind(this)}&gt;<br>           Done<br>        &lt;/button&gt;<br>      &lt;/div&gt;    <br>    );  <br>  }<br>}</pre><pre>ReactDOM.render(&lt;Container name=&quot;Container&quot; /&gt;, document.getElementById(&#39;app&#39;));</pre><p>Now when the user clicks this Done button, the ToDoList component updates the new state, which therefore renders a new status to display.</p><p>There is so much more we can do with nested components talking between each other using their props and their events. Props don’t have to be just information, they can be functions as well. We can also pass arguments to event handlers. There are other resources out there that will show these simple <a href="https://reactjs.org/docs/handling-events.html">examples</a>.</p><p>I hope this provides a simple overview of some basic concepts in React. These concepts have more depth and there are other powerful concepts I have not discussed. React’s website was my resource and has amazing tutorial’s and guides to further discover.</p><p><a href="https://reactjs.org/docs/getting-started.html">Getting Started - React</a></p><p>I have completed my 6th week of Hack Reactor and we built a YouTube video player with React. Using interactions with YouTube’s data API. We are onto Redux/React next. Hope this guide is useful for someone out there!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=322629bb6e62" width="1" height="1" alt=""><hr><p><a href="https://blog.devgenius.io/java-script-lets-talk-react-basics-322629bb6e62">Java Script: Let’s Talk React Basics</a> was originally published in <a href="https://blog.devgenius.io/">Dev Genius</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Let’s rotate a matrix clockwise! JavaScript Beginners]]></title>
            <link>https://blog.devgenius.io/lets-rotate-a-matrix-clockwise-javascript-beginners-65a9c34aa0a6?source=rss-49d75f61c6ac------2</link>
            <guid isPermaLink="false">https://medium.com/p/65a9c34aa0a6</guid>
            <category><![CDATA[problem-solving]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[bootcamp]]></category>
            <category><![CDATA[algorithms]]></category>
            <dc:creator><![CDATA[Tina Luk]]></dc:creator>
            <pubDate>Sun, 16 Aug 2020 02:32:19 GMT</pubDate>
            <atom:updated>2020-08-16T09:33:10.514Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*vpxgvlPiIYJJrjsv" /><figcaption>Photo by <a href="https://unsplash.com/@honeyyanibel?utm_source=medium&amp;utm_medium=referral">Honey Yanibel Minaya Cruz</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Given an n x n matrix, how can we rotate it by 90 degrees clockwise? This is a standard algorithm problem, let’s look at a straightforward solution with visuals before we refactor and optimize our code.</p><p>Our goal is to write a function that accepts an input matrix of any n x n size and returns an output of a rotated matrix. See the example of a 3 x 3 matrix below, an array of arrays representation for our input and output.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1eae72cd6f140118b2c8616fae7ad00f/href">https://medium.com/media/1eae72cd6f140118b2c8616fae7ad00f/href</a></iframe><p>This blog will cover the following and use a 3 x 3 matrix example:</p><ol><li>Visuals for each step of the matrix rotation process</li><li>How to flip matrix on major and minor diagonal</li><li>Other solutions using JavaScript’s built-in methods</li></ol><h3>Let’s rotate this matrix…</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wzh-y6cNX_jNDbvbpiwpJw.png" /><figcaption>3 x 3 matrix rotate by 90 degrees</figcaption></figure><p>Comparing the input matrix and the output, the columns are now rows, but reversed. For example, the first column in the input has now become the first row in the output but reversed.</p><h3>What are the steps to rotate the matrix?</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jrXH7DzxfjRjITJS8gxjng.png" /><figcaption>Steps to rotate matrix</figcaption></figure><p>To access each value in the matrix, a simple nested loop can be used.</p><ol><li>The matrix is flipped along the major diagonal (top left to bottom right). This will transpose the columns to be rows. This is done by swapping the values on the upper half of the diagonal with the lower half. For example, the value at [row: index 0][column: index 1] is 2 to be replaced by the value at [row: index 1][column: index 0] which is 4 and vice versa. Remember to ensure the swap only takes place one time, the inner nested loop (column index) must be initialized correctly.</li><li>Reverse each row in the matrix. This can be executed with JavaScript’s built-in reverse method or with a for loop swapping values at each end until the center is reached.</li></ol><p>Now we know how to flip along the major diagonal and rotate the matrix. Let’s take it a step further.</p><h3>How to flip matrix along the minor diagonal?</h3><p>The minor diagonal the from the top right to the bottom left.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gImwf4aJ4I4iNyT4NiroUw.png" /><figcaption>Steps to flip along the minor diagonal</figcaption></figure><p>This problem without the rotated matrix, may be cumbersome to solve with swapping index values. Swapping the index value along the minor diagonal is not as simple as the major diagonal.</p><p>However, with the rotated matrix in play, we can visually see the solution is simple. Just reverse (upside down) the rotated matrix! The steps are:</p><ol><li>Rotate matrix by 90 degrees</li><li>Reverse order of entire matrix, flip upside down. Bottom row is now on top and so on.</li></ol><p>Let’s look at the code. The function expressions have been isolated by different ways to manipulate the matrix.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/455b78cd43cdbbf3284826e2d50fe463/href">https://medium.com/media/455b78cd43cdbbf3284826e2d50fe463/href</a></iframe><p>Summary of the different functions expressions:</p><ul><li>Rotate matrix: flip along major diagonal then reverse each row</li><li>Flip major diagonal: will swap each value on upper half of diagonal with lower half. To ensure the swap does not occur twice, initialize the inner loop (column index) to start at the outer loop (row index).</li><li>Flip minor diagonal: rotate matrix then reverse entire matrix</li></ul><h3>Other Solution to rotate with JavaScript’s built-in Map method</h3><p>Leveraging JavaScript’s map method, we can compress our code to rotate the matrix even further as shown below.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c8acb0d9a20be5e9213bf25be21d31cd/href">https://medium.com/media/c8acb0d9a20be5e9213bf25be21d31cd/href</a></iframe><p>For a deeper dive, on this solution the reference below is excellent!</p><p><a href="https://medium.com/front-end-weekly/matrix-rotation-%EF%B8%8F-6550397f16ab">Matrix Rotation ♻️</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HvW6BaIKkZvd9TWgpPdWfQ.png" /><figcaption>Rotate matrix with map</figcaption></figure><p>To break down this solution high level:</p><ol><li>Reverse entire matrix</li><li>Use outer map to get all the column index’s</li><li>Use inner map to change each row with column values</li></ol><p>Hope this was helpful for someone!</p><p>I am ending week 6 of Hack Reactor. My 10 month old is wildly crawling and climbing everywhere. Our exercise the last 2 weeks included solving N-Queens and learning about HTTP, REST API, mechanisms of how internet traffic is transmitted and MVC. With jQuery, we got some practice getting data from a serve without a page refresh with Parse API as the back-end. Definitely, feels like there constantly is a lot to learn!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=65a9c34aa0a6" width="1" height="1" alt=""><hr><p><a href="https://blog.devgenius.io/lets-rotate-a-matrix-clockwise-javascript-beginners-65a9c34aa0a6">Let’s rotate a matrix clockwise! JavaScript Beginners</a> was originally published in <a href="https://blog.devgenius.io/">Dev Genius</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[JavaScript: Traverse Tree Recursively]]></title>
            <link>https://blog.devgenius.io/javascript-traverse-tree-recursively-2e525cb176e2?source=rss-49d75f61c6ac------2</link>
            <guid isPermaLink="false">https://medium.com/p/2e525cb176e2</guid>
            <category><![CDATA[tree-data-structures]]></category>
            <category><![CDATA[codingbootcamp]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[recursion]]></category>
            <dc:creator><![CDATA[Tina Luk]]></dc:creator>
            <pubDate>Sun, 02 Aug 2020 18:13:20 GMT</pubDate>
            <atom:updated>2020-08-03T08:50:23.299Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*N8dHLB4d1Xrl1l3M" /><figcaption>Photo by <a href="https://unsplash.com/@niko_photos?utm_source=medium&amp;utm_medium=referral">niko photos</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>The ability to traverse a tree is an important basic foundational concept. A <a href="https://en.wikipedia.org/wiki/Tree_(data_structure)">tree</a> is a data structure with a collection of nodes with a hierarchical pattern. Each node is its own data structure. A tree’s structure has a single ‘root’ node and each node has a value and a reference pointing to its children nodes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rrJfBlE1ir21Cizw9WSn7A.png" /><figcaption>Example of Tree Data Structure with the value 2 as the root node. Reference: <a href="https://en.wikipedia.org/wiki/Tree_(data_structure)">https://en.wikipedia.org/wiki/Tree_(data_structure)</a></figcaption></figure><p>The simple tree concepts to be covered in this post are:</p><ol><li>Construct a Tree class using <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Inheritance_and_the_prototype_chain">pseudoclassical instantiation</a> pattern</li><li>Create a method to add children to tree</li><li>Traverse the tree recursively depth-first</li><li>Create a map method to return a tree with same structure as original tree but with different values (2 different ways) using recursion</li></ol><p><a href="https://javascript.info/recursion#:~:text=Recursion%20is%20a%20programming%20term,that&#39;s%20called%20a%20recursion%20step.">Recursion</a> is a problem solving method where functions call themselves within it own code. The reason is to decompose the larger, complicated problems into a simpler problems which are easier to solve.</p><h3><strong>Construct a tree class and add method to add children to tree</strong></h3><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/bd46f7e266892dc4705f6e68b50c034b/href">https://medium.com/media/bd46f7e266892dc4705f6e68b50c034b/href</a></iframe><p>This is a simplified tree which takes in a single value and has a children array. At this point root1 tree looks like the following.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BpTg0y3WxqsRCx8kSQ_wkg.png" /><figcaption>Tree whiteboard structure from code above</figcaption></figure><h3><strong>Traverse tree recursively depth-first</strong></h3><p>Let’s implement a simple contains method to traverse the tree depth-first to see if a target value is contained or found in the tree.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/dc11ffcc35417437bdc8af61f331aa2e/href">https://medium.com/media/dc11ffcc35417437bdc8af61f331aa2e/href</a></iframe><p>Contains method has a base case to check if the current node’s value equals value argument passed in. Then iterates through the node’s children and recurse through each child, which results in tree traversal depth first to continue checking this base case. If base case never passes, contains method returns false.</p><h3><strong>Create a map method</strong></h3><p>Map method will return a new tree with the same structure as the original tree but the new tree will have different values from the callback function. Also, the original tree is NOT affected. Let’s look at 2 different ways to solve this using recursion, there are potentially plenty of other solutions.</p><ol><li>Use recursion with helper function and make initial copy of entire original passed in tree</li><li>Use recursion without helper function and create new tree instance and children as traversing through original passed in tree</li></ol><h3><strong>Let’s diagram the first solution:</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7m23u2ZiObSNGs0Lo4r9lA.png" /></figure><ol><li>Create a copy (not just a pointer reference) of the original passed in tree</li><li>Traverse through the new copied tree by using recursion with a helper function.</li><li>During traversal of the copied tree, apply the callback to each node’s value</li></ol><h3><strong>Let’s diagram the second solution:</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HoRbIsjMflssRfc64Cxxqg.png" /></figure><p>This solution creates the new tree as traversing through the original passed in tree.</p><ol><li>Create new instance with original root node’s value with callback applied</li><li>Traverse through original tree and add child node’s (with updated value) to new tree instance to mimic original tree’s structure.</li><li>While traversing through original tree, ensure the position of new tree’s node is in the same position as the original to retain original tree’s structure.</li></ol><p>Below is sample code of the diagrammed solutions.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/22e9779cc294ca23a5ebecd71d8c59ad/href">https://medium.com/media/22e9779cc294ca23a5ebecd71d8c59ad/href</a></iframe><p>This is the end of Week 4 of Hack reactor boot camp. This past week focused on class inheritance and sub-classes in functional, pseudoclassical and ES6 pattern. We also learned how to:</p><ul><li>Set up the prototype chain delegation of the subclasses to the super class correctly</li><li>Determine what this is referencing and how to bind this correctly, which is in all transparency is still fuzzy to me</li><li>Create different instances with object inheritance and leverage j Query, HTML and CSS to visually display this</li></ul><p>However, recursion is a concept that I am still trying to master which let me to writing a post on this. Hopefully, this would be helpful for me and others.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2e525cb176e2" width="1" height="1" alt=""><hr><p><a href="https://blog.devgenius.io/javascript-traverse-tree-recursively-2e525cb176e2">JavaScript: Traverse Tree Recursively</a> was originally published in <a href="https://blog.devgenius.io/">Dev Genius</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>