<?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 Gianfranco Nuschese on Medium]]></title>
        <description><![CDATA[Stories by Gianfranco Nuschese on Medium]]></description>
        <link>https://medium.com/@gianfranconuschese?source=rss-fa5b9ed31e3e------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/2*3CWB6-z9VoNwo5OeP79G2A.jpeg</url>
            <title>Stories by Gianfranco Nuschese on Medium</title>
            <link>https://medium.com/@gianfranconuschese?source=rss-fa5b9ed31e3e------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Thu, 19 Nov 2026 07:18:52 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@gianfranconuschese/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[Binary Heaps & Priority Queues in JavaScript]]></title>
            <link>https://medium.com/swlh/binary-heaps-priority-queues-in-javascript-44d20cf0cb6e?source=rss-fa5b9ed31e3e------2</link>
            <guid isPermaLink="false">https://medium.com/p/44d20cf0cb6e</guid>
            <category><![CDATA[algorithms]]></category>
            <category><![CDATA[data-structures]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[binary-heap]]></category>
            <dc:creator><![CDATA[Gianfranco Nuschese]]></dc:creator>
            <pubDate>Thu, 12 Mar 2020 18:18:58 GMT</pubDate>
            <atom:updated>2020-03-15T17:02:06.685Z</atom:updated>
            <content:encoded><![CDATA[<p>I worked at a computer repair shop where technicians processed computers in the order that they came in, according to how long they predicted the repair will take. Every day they had a running list of computers that needed to be opened and tested. However, if there was an emergency where a customer needed their data right away, we could sometimes push their computer to the front of the line.</p><p>The technicians were using a <strong>priority queue </strong>in order to handle repairs, where computers with the highest priority were handled first.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/530/1*oUWlvW04WmC5VGqdJ93qUA.jpeg" /><figcaption>Inspection of the inside of a Macbook.</figcaption></figure><p>When we want to process data efficiently in computer programming, we sometimes use data structures called <a href="https://medium.com/swlh/stacks-and-queues-simplified-ef0f838fc534">stacks and queues </a>to form an order for our data. A <strong>priority queue</strong> functions somewhat like a queue in that it processes data from the front of the list (or queue), but it differs when data is added to the queue. While a traditional queue simply adds the data to the back of the line, priority queues need to ensure that the new data gets a <em>proper place in the line according to its priority. </em>We’ll need to use something called a <strong>binary heap</strong> to implement our priority queue.</p><h3>Binary Heaps</h3><p>Binary heaps are data structures that are similar to <a href="https://medium.com/swlh/traversing-trees-breadth-first-and-depth-first-searches-with-javascript-316f23c9fe8f">trees</a> but have different rules.</p><ol><li>Each node in a<strong> binary </strong>heap has at most two children, but sibling order does not matter.</li><li>Heaps are as compact as possible, meaning new elements are added first from top to bottom then from left to right.</li><li>Binary heaps can have one of two formats: a <strong>Max Binary Heap</strong> or a <strong>Min Binary Heap.</strong></li></ol><ul><li>All of the child nodes in a <em>Max </em>Binary Heap are smaller than their parent</li><li>All of the child nodes in a <em>Min</em> Binary Heap are greater than their parent</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*L0g7CDZCCQZIi481NAERkg.png" /><figcaption>A max binary heap.</figcaption></figure><h4>Implementation</h4><p>We can use a class to implement adding and removing from the heap, but we need a way to store the values in order. What kind of data structures do we know in JavaScript that have a specific order? Arrays do! Let’s take a look at the model below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/334/1*ar5u4L4-qyL-6-ryZudDGQ.png" /><figcaption>A min binary heap with values in an array.</figcaption></figure><p>There’s a pattern that children and parent nodes follow in our heap array. Where any index of an array is <em>n,</em></p><ul><li>The index of the left child is <em>2n + 1</em></li><li>The index of the right child is <em>2n + 2</em></li></ul><p>In order to derive the index of the parent of a child we use <em>(n-1)/2 </em>rounded down. Using this information, we can develop our insertion and removal methods. We’ll start with a Max Binary Heap.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4b0a1087c0ed17d4d570d0e6f8a8ad5d/href">https://medium.com/media/4b0a1087c0ed17d4d570d0e6f8a8ad5d/href</a></iframe><p>When inserting and removing in a binary heap, we use a method called <em>bubbl</em>ing to sort the heap. The insertion method uses two helper functions: swap and bubbleUp. The swap function swaps the elements in our values array at the two indices passed in. Once we push the new value into the array, our bubbleUp function compares the parent of the newly added element, and swaps it if the child is greater than the parent. We reassign our current index to the element’s new index if swapped, and keeps testing parents in a loop until the element fits, or we reach the root of the heap.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e558240e10e309cb3742a3751dfe014d/href">https://medium.com/media/e558240e10e309cb3742a3751dfe014d/href</a></iframe><p>Our method for removal ( called removeMax above) also uses bubbling, but it’s a bit more complicated. We’ll first swap the the first and last element in our values array so that we can pop the max element off of the array and return it. Before we return it, we need to make sure our heap is properly sorted.</p><p>Our bubbleDown method then loops over the heap, checking the children nodes against our new root (the former last element in our array that we swapped). In order to bubble down properly, we first check the left child, and then the right child. If the parent is lesser than only one of the two children, we swap it with that child. However, if the parent is lesser than both of the children, we swap it with the greater value. We also need to ensure that both children exist. This is why we don’t swap until we’ve checked both the left and right child.</p><p>If you need more clarity on how bubbling works, you can step through the process on <a href="https://visualgo.net/en/heap?slide=1">VisuAlgo.</a></p><h3>Priority Queues</h3><p>Our priority queue isn’t that different from our Max Binary Heap, we’ll just need to change a few things. The biggest change is that our values are no longer numbers but Nodes. Each node has a value and a priority, and we need to change our implementation to consider a node’s priority instead of it’s value. I changed the method names to enqueue and dequeue instead of insert and removeMax . Finally, lower priority numbers usually signify higher priority, so we’ll need to change our Max Binary Heap to a Min Binary Heap. We’ll convert all the &gt; signs to &lt; where we are comparing priorities.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/adf91f8f50d0c97d73f89d1e2cb378b3/href">https://medium.com/media/adf91f8f50d0c97d73f89d1e2cb378b3/href</a></iframe><h3>Big O</h3><p>Binary Heaps are great for processing data in a specific order — Insertion and removal are both in O(log n) time. Searching is O(n), so if you’re looking for something faster, I would suggest using a Binary Search Tree if possible.</p><h3>Resources</h3><ul><li><a href="https://codeburst.io/implementing-a-complete-binary-heap-in-javascript-the-priority-queue-7d85bd256ecf">Implementing a Complete Binary Heap in JavaScript: The Priority Queue</a></li><li><a href="https://levelup.gitconnected.com/an-introduction-to-binary-heaps-c95b3025977">An Introduction to Binary Heaps</a></li></ul><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2Ft0Cq6tVNRBA%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3Dt0Cq6tVNRBA&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2Ft0Cq6tVNRBA%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/cf72f8fc5a7599cf2cf3d372fb37a9f5/href">https://medium.com/media/cf72f8fc5a7599cf2cf3d372fb37a9f5/href</a></iframe><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=44d20cf0cb6e" width="1" height="1" alt=""><hr><p><a href="https://medium.com/swlh/binary-heaps-priority-queues-in-javascript-44d20cf0cb6e">Binary Heaps &amp; Priority Queues in JavaScript</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>
        <item>
            <title><![CDATA[Adventures in TypeScript Declaration Files]]></title>
            <link>https://medium.com/better-programming/adventures-in-typescript-declaration-files-46e6b540b2d?source=rss-fa5b9ed31e3e------2</link>
            <guid isPermaLink="false">https://medium.com/p/46e6b540b2d</guid>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[nodejs]]></category>
            <dc:creator><![CDATA[Gianfranco Nuschese]]></dc:creator>
            <pubDate>Thu, 05 Mar 2020 17:23:05 GMT</pubDate>
            <atom:updated>2020-03-09T18:41:54.438Z</atom:updated>
            <content:encoded><![CDATA[<h4>Files that allow other developers to use types for NPM packages without having to write their own</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*2UKJhhtFZ9pnNh7J" /><figcaption>Photo by <a href="https://unsplash.com/@r3dmax?utm_source=medium&amp;utm_medium=referral">Jonatan Pie</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a>.</figcaption></figure><p>I’m currently working on a project using Express and React in order to practice my TypeScript and Jest chops. I’m using the <a href="https://screeningapidocs.cityofnewyork.us/overview">NYC Benefits Screening API</a>, and midway through writing types and interfaces for my API requests, I thought, “Wow, wouldn’t it be great if I could share my types with someone else who might want to use this API?”</p><p>After some research, I learned that I should write a type declaration file and include it in a package on NPM. In this article, I’m going to describe my workflow and talk about how you can write a file and publish it in an NPM package.</p><h3>TypeScript Declaration Files</h3><p>A declaration file holds all the types and declarations in a separate organized document in order to keep your code modular. These files allow other developers to use types for NPM packages without having to write their own. Sometimes NPM packages come with declaration files and instructions on how to use them, but what if your package doesn’t come with types?</p><p>Enter <a href="https://github.com/DefinitelyTyped/DefinitelyTyped">DefinitelyTyped</a>. DefinitelyTyped allows developers to request and contribute types for packages that don’t have them. It’s completely open-source, has resources and guides for developers to work on type declaration files together, and a publishing pipeline. You can use <a href="http://microsoft.github.io/TypeSearch/">TypeSearch</a> to search for already written types for your package.</p><p>Types are usually found in the @types folder in your node_modules folder. Even if you’ve never worked with TypeScript before, if you look at one of your old projects, you’ll probably find this folder with types for some of your NPM modules.</p><p>At this point, if you still can’t find types for your package, you’ll need to either decide to use a different package or — the more fun route — write your own type declaration file!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*61_L5LGWBE3Xoz73-obhWw.png" /><figcaption>That’s a lot of issues!</figcaption></figure><h3>Your First Declaration File</h3><p>Hold on just a minute! Before you jump into writing types for a package, you should first do some testing and research on your package to make sure you understand how it will work. If you are a newbie to TypeScript or the package is complicated, it might be quite difficult to write types for it. A good way to get your feet wet (or hands, for that matter) might be taking on some pull requests for some already written files on DefinitelyTyped.</p><p>Another potential route is to work a simpler package or a declaration file for requests to a lightweight API. In my case, there were no packages on NPM that corresponded to the NYC Benefits Screening API, so I just needed to find out how to publish my types for others to use.</p><p>TypeScript has some <a href="https://www.typescriptlang.org/docs/handbook/declaration-files/introduction.html">guidelines</a> for making declaration files, including templates and best practices. I strongly recommend reading through this section before attempting to write a declaration file. Every declaration file will be different, but the two main ways to integrate declarations are through a module and through a global namespace.</p><h3>Exporting Your Types</h3><p>If you are making a declaration file for a package that already exists, you’ll want to implement your types according to the package. Most packages are modular, but there may be a few that still use the global scope. TypeScript recommends using the modular style in order to avoid polluting the global namespace. Since my API has no packages related to it, I’ll be publishing an NPM package with the modular route.</p><p>Note: If you are adding types for an existing package, you should be writing tests or using the tests provided in the package you are typing in order to ensure your types are written correctly!</p><p>I’m following one of the templates provided on the TypeScript website, so the first lines in my file are the package the types are for and the author information.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*W_YwzBtXEjSWELJGFtACWA.png" /><figcaption>Information for my type file, using the templates from the TypeScript website.</figcaption></figure><p>In order to export the types in our file, we can simply write export in front of all our types/interfaces. However, if you have a large number of types or types that are organized into different sections, you should place them under a namespace. A namespace allows us to import all the types under one name instead of importing all the types separately. It’s also useful in avoiding naming conflicts with other types from different packages or custom types.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/842/1*G01Io-EiY1q_RMmygpBYwg.png" /><figcaption>A set of types under the namespace NYCBSA.</figcaption></figure><p>I want to be able to import using the namespace or to import each type separately, so I’ve just copied my types (without the namespace declaration) with export in front of them at the bottom of the file.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QsleXS7gQZ1fQaojRx82ig.png" /></figure><h3>Making an NPM Package</h3><p>An NPM package is fairly easy to publish, but you’ll want to test your package to make sure it works first. The way I tested my package is npm pack. This command bundles your package into an archive that can be installed using the command npm install &lt;tarball-destination.tgz&gt;.</p><p>Once you have ensured that you can import your types properly after installing your package locally, you can move on to publishing your package.</p><h4>Publishing</h4><p>Before you consider publishing, you should write a README in order to let people know what your package does and how to use it. You should also make sure all of the information in your package.json is correct. (license, description, author, dependencies, etc.). Once you’ve got that, you’ll need to make an account on NPM. After logging in on the command line using npm login, you can publish your package publicly using npm publish. You can <a href="https://www.npmjs.com/package/nycbsa_types">check out</a> the package for this example.</p><h3>Resources</h3><ul><li><a href="https://docs.npmjs.com/creating-and-publishing-unscoped-public-packages">https://docs.npmjs.com/creating-and-publishing-unscoped-public-packages</a></li><li><a href="http://blog.wolksoftware.com/contributing-to-definitelytyped">http://blog.wolksoftware.com/contributing-to-definitelytyped</a></li></ul><ul><li><a href="https://medium.com/razroo/what-are-declaration-files-in-typescript-476c1c06f353">What are Declaration Files in Typescript?</a></li><li><a href="https://github.com/cjthompson/typescript-examples">cjthompson/typescript-examples</a></li><li><a href="https://dev.to/vcarl/testing-npm-packages-before-publishing-h7o">Testing npm packages before publishing</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=46e6b540b2d" width="1" height="1" alt=""><hr><p><a href="https://medium.com/better-programming/adventures-in-typescript-declaration-files-46e6b540b2d">Adventures in TypeScript Declaration Files</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[Traversing Trees: Breadth First and Depth First Searches with JavaScript]]></title>
            <link>https://medium.com/swlh/traversing-trees-breadth-first-and-depth-first-searches-with-javascript-316f23c9fe8f?source=rss-fa5b9ed31e3e------2</link>
            <guid isPermaLink="false">https://medium.com/p/316f23c9fe8f</guid>
            <category><![CDATA[algorithms]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[data-structures]]></category>
            <category><![CDATA[depth-first-search]]></category>
            <category><![CDATA[breadth-first-search]]></category>
            <dc:creator><![CDATA[Gianfranco Nuschese]]></dc:creator>
            <pubDate>Thu, 27 Feb 2020 01:22:14 GMT</pubDate>
            <atom:updated>2020-03-02T23:02:16.398Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/562/1*yv20NoCVYhsLbNAHOMGflQ.png" /><figcaption>Source: <a href="https://xkcd.com/835/">XKCD</a></figcaption></figure><p>When I was younger, I used to have files and folders randomly strewn about on my desktop and external hard drives. As I reached high school where most of my work was done on a computer, I realized that it was really difficult to find anything on my laptop since the file organization was haywire.</p><p>It took a full weekend to completely re-organize all of my files — this was before USB 3.0 came out. Other than a few hectic times in college, my files and folders stayed pretty clean, and it helped when cloud storage started to take over.</p><h3>Trees</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/201/1*EDljI717AUw03zyjkYX9bg.png" /><figcaption>A basic tree.</figcaption></figure><p>Files and folders on computers are organized in data structures called <strong>trees</strong>. Trees are a hierarchical collection of nodes that follow some simple rules:</p><ol><li>A tree has one node, the root, from which all nodes stem, either directly or as a child of a descendant node (which also means no node can have a reference to the root)</li><li>A node can only have one reference (no node can have multiple other nodes pointing at it)</li></ol><p>I’ve previously covered a special kind of tree called a <a href="https://medium.com/@gianfranconuschese/binary-search-trees-in-javascript-d35965762dbd">binary search tree,</a> but in this blog we’ll be working with a basic implementation of a tree — see below.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ff141327ded5611be8e55f0d4433a783/href">https://medium.com/media/ff141327ded5611be8e55f0d4433a783/href</a></iframe><h3>Breadth First Search</h3><p>While our computer has a handy interface for browsing through our file tree, we need ways to programmatically traverse trees. One of these is called <strong>Breadth First Search.</strong> Breadth First Searches (referred to as BFS) traverse trees from left to right, then top to bottom, as if it were reading each row of nodes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/793/1*3B5cxVm4BhUOIv0r81MzEw.png" /><figcaption>A tree that holds different letters in each node.</figcaption></figure><p>If we utilized BFS on the example above, we’d get this answer:</p><p>First Row: H + Second Row: el + Third Row: loWorld = HelloWorld</p><p>In order to do this programmatically we’ll need to use another data structure called a <a href="https://medium.com/swlh/stacks-and-queues-simplified-ef0f838fc534?source=your_stories_page---------------------------">Queue</a>. A Queue is a way of processing data that follows a First In First Out mentality. New data gets added to the back of the queue, and data gets processed from the front of the queue. Here’s my implementation:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/58caffc6dbf1966acd93d1f8a4b46e2d/href">https://medium.com/media/58caffc6dbf1966acd93d1f8a4b46e2d/href</a></iframe><p>When we process a node from the front of the queue, we’ll check if the node has any children, and if it does, add them to the back of the queue. We’ll also need to keep track of each node’s value by adding it to an array. Here’s my implementation:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/99571739ed4844b46f33d84b6db56666/href">https://medium.com/media/99571739ed4844b46f33d84b6db56666/href</a></iframe><p>If you want to see the code in action using the tree example I posted above, see the bottom of this post.</p><h3>Depth First Search</h3><p>Depth First Search (referred to as DFS) is an alternate way of traversing a tree that uses recursion. Using DFS we can traverse trees in different ways depending on the order that we need. In each of the implementations, I’ll be referring to this number tree:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/523/1*OStQR2Q2-uJzmm3SSWs2XA.png" /><figcaption>A tree with numbers in each node.</figcaption></figure><p>We’ll also be writing a helper method for each order, and using a switch statement to stipulate the order we want to use. Here’s the outer function:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/31597b57c7e22b70a0f95aa4074c6280/href">https://medium.com/media/31597b57c7e22b70a0f95aa4074c6280/href</a></iframe><h4>Pre-Order</h4><p>Pre-Order traverses the tree vertically from top to bottom, left to right. The first value returned will <strong>always</strong> be the root. For the number tree above, we’d get a return of [10,6,3,8,7,15,20] .</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e1ec0e90c15809efb147301d9ad7ec19/href">https://medium.com/media/e1ec0e90c15809efb147301d9ad7ec19/href</a></iframe><p>We need to first push the current node’s value, and then recursively call the function on each child of the current node.</p><h4>Post-Order</h4><p>Post-Order is similar to Pre-Order except for one facet: it traverses the tree horizontally from <strong>bottom to top</strong>, left to right. The root should always be the <strong>last thing</strong> returned. The tree above would return [3,8,7,6,20,15,10] .</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0cadbd7c707e47540a4a6c4a33abcc61/href">https://medium.com/media/0cadbd7c707e47540a4a6c4a33abcc61/href</a></iframe><p>We simply reverse the order in which actions happen in our pre-order function. We recursively call the function <strong>before</strong> adding any nodes to our array.</p><h4>In-Order</h4><p>In-Order is a bit different from the other two orders. It tries to recreate some semblance of the tree structure. It does so by traversing the tree from bottom to top, left to right, similar to post-order. However, it splits the children of every node in two, processing first the left half, then the parent node, then the right half. Our example would return [3, 6, 8, 7, 10, 15, 20].</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8bded94b3801708a6992f06743a16558/href">https://medium.com/media/8bded94b3801708a6992f06743a16558/href</a></iframe><p>Since our there are no restrictions on the number of children each node can have, we need to split the nodes ourselves. In-order DFS is easily implemented with Binary Search Trees, where each node can only have a maximum of 2 children, and the left and right nodes are specifically defined. In fact, because of the way Binary Search Trees are sorted, when DFS is used on a binary search tree it returns a sorted array of all node values.</p><h3>When to use BFS and DFS</h3><p>BFS and DFS both have a time complexity of O(n) at worst. BFS is better for deeper trees since it will take a lot more memory to operate on wider trees. The opposite applies to DFS — it will take a lot of memory to traverse deeper trees while it works well with wider trees. Since they are both meant for searching, you also need to consider what results you are searching for. Take a look at the stack overflow I’ve linked in the resources section for further explanation.</p><h3>Resources</h3><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FzaBhtODEL0w%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DzaBhtODEL0w&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FzaBhtODEL0w%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/eadb6d1b1a07c6d856dac536bd95f492/href">https://medium.com/media/eadb6d1b1a07c6d856dac536bd95f492/href</a></iframe><p><a href="https://stackoverflow.com/questions/3332947/when-is-it-practical-to-use-depth-first-search-dfs-vs-breadth-first-search-bf">When is it practical to use Depth-First Search (DFS) vs Breadth-First Search (BFS)?</a></p><h3>Full Implementation of Searches</h3><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a490e57c9139c562b14ce14c52af2b6f/href">https://medium.com/media/a490e57c9139c562b14ce14c52af2b6f/href</a></iframe><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=316f23c9fe8f" width="1" height="1" alt=""><hr><p><a href="https://medium.com/swlh/traversing-trees-breadth-first-and-depth-first-searches-with-javascript-316f23c9fe8f">Traversing Trees: Breadth First and Depth First Searches with JavaScript</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>
        <item>
            <title><![CDATA[Binary Search Trees in JavaScript]]></title>
            <link>https://medium.com/@gianfranconuschese/binary-search-trees-in-javascript-d35965762dbd?source=rss-fa5b9ed31e3e------2</link>
            <guid isPermaLink="false">https://medium.com/p/d35965762dbd</guid>
            <category><![CDATA[binary-search-tree]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[data-structures]]></category>
            <dc:creator><![CDATA[Gianfranco Nuschese]]></dc:creator>
            <pubDate>Thu, 20 Feb 2020 17:05:19 GMT</pubDate>
            <atom:updated>2020-02-20T21:25:27.101Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*H6hkJ3XAcKVaNUKe0osWzw.jpeg" /><figcaption>An ancient tome of advertisements.</figcaption></figure><p>Before the advent of cellphones and the internet, we used these things called phone books. Most of you probably know what a phone book is, but just in case: a phone book is a directory where businesses pay to list their phone numbers, usually arranged by type of business, and then alphabetically within each section.</p><p>Let’s say you hear from a friend that they used a service called “Roach-B-Gone”, but they forgot the number. Since it’s 1991, we have to look in the phone book. We open it up to around the halfway point and see an listing for “Larry the Locksmith”. We’re in the “Locksmith” section, and we need to get to the “Pest Control” section. We know we need search toward the right half of the book, so we <em>effectively eliminate</em> the entire left half of the book.</p><p>If we flip to the halfway point of the right half of the book, we end up at the “Towing” section, where we can eliminate everything after it since our company is now to the left of where we’re at. If we continue this process, eventually we’ll reach “Roach-B-Gone”. We’ve just employed the logic of a Binary Search Tree.</p><h3>Tree Basics</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*X3iHJlW41Yli2xF6qISw3w.png" /><figcaption>A basic tree structure.</figcaption></figure><p>Trees are data structures that employ a hierarchy that connect nodes to one another. They are non-linear and can store any type of data. Trees start at the <strong>root </strong>(above the root is 2) node which can be connected to many different nodes and form many paths. Trees follow a top-down hierarchy, where a node that points to another node it called a <strong>parent</strong>, and the node it points to is the <strong>child. </strong>In the example above,<strong> </strong>2 is the parent to children 7 and 5, while 5 is the parent to child 9. The child nodes of 7 — (2,10,6) — are called <strong>siblings</strong> since they share the same parent. the node 4 is called a <strong>leaf </strong>because it has no children.</p><p>Some common examples of trees are the HTML DOM, or file and folder structures on a computer.</p><h4>Binary Search Trees</h4><p>A Binary Search Tree is a data structure that organizes our data in a specific configuration, allowing us to insert and search through our data quickly. The tree in the example above is NOT a valid Binary Search Tree. Binary Search Trees follow 2 specific rules:</p><ol><li>Each parent nodes can have a <strong>maximum of 2 child nodes.</strong></li><li>The left child of a parent node must be lesser than the parent, and the the right child must be greater. <em>We’ll use numbers to represent this, but note that this can also be used with strings considering their alphabetical order.</em></li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hEFEFfHINKIVHv439WzVFA.png" /><figcaption>A valid binary search tree.</figcaption></figure><h3>Implementation</h3><p>We’ll start by implementing the Node class, which by definition has a left and right reference to other nodes, and then we’ll implement insert and find.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5706a82ab517f9ec38fed7037166f106/href">https://medium.com/media/5706a82ab517f9ec38fed7037166f106/href</a></iframe><p>You’ll notice that I used recursion to implement the find and insert methods — you could also use iteration it you’d like.</p><h3>Time Complexity</h3><p>Binary Search Trees at best can have a time complexity of <strong>O(log n) </strong>for insertion and search. However, this is not guaranteed because not all Binary Search Trees are perfectly sorted.</p><p>As an example let’s consider a singly linked list. A singly linked list that is ordered from least to greatest is technically a binary search tree. The root is the smallest value, and all the “right” nodes are larger. If we needed to insert a new largest number, or search for the largest number, we’d need to search through every single node. In this case, our time complexity would be <strong>O(n)</strong>. When implementing these trees, it’s important to pick a node near the midpoint of your data for your tree to work most efficiently.</p><h3><strong>Resources</strong></h3><ul><li><a href="https://medium.com/better-programming/singly-and-doubly-linked-lists-in-javascript-7515f47c9f60">Singly and Doubly-Linked Lists in JavaScript</a></li><li><a href="https://medium.com/swlh/small-math-to-big-o-901a90998871">Small Math to Big O</a></li></ul><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2F5cU1ILGy6dM%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3D5cU1ILGy6dM&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2F5cU1ILGy6dM%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/e8051df4e12ad272bad6849a84aa15d0/href">https://medium.com/media/e8051df4e12ad272bad6849a84aa15d0/href</a></iframe><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d35965762dbd" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Stacks and Queues, Simplified]]></title>
            <link>https://medium.com/swlh/stacks-and-queues-simplified-ef0f838fc534?source=rss-fa5b9ed31e3e------2</link>
            <guid isPermaLink="false">https://medium.com/p/ef0f838fc534</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[queue]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[stack]]></category>
            <dc:creator><![CDATA[Gianfranco Nuschese]]></dc:creator>
            <pubDate>Thu, 13 Feb 2020 22:44:15 GMT</pubDate>
            <atom:updated>2020-02-14T16:56:29.001Z</atom:updated>
            <content:encoded><![CDATA[<h4>A breakdown of stacks and queues in JavaScript.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/473/1*r4Bfo3rrFprzFM2zbgzZXA.jpeg" /><figcaption>Visual guide to stacks. <a href="https://dev.to/rinsama77/data-structure-stack-and-queue-4ecd">Source</a></figcaption></figure><p>Stacks and Queues are probably the most self-explanatory data structures, but to some they can still seem intimidating. Let’s think of them in terms of real-world applications.</p><p>You use a stack every day when you are browsing the internet or editing text. A stack is what keeps track of the websites visited/changes made so that our back/forward and undo/redo buttons function properly. <em>Whatever goes on top of the stack is the first thing to get removed.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/533/1*EB-l8KQzphdSqBoDfKDnSg.png" /><figcaption>Visual representation of a queue. <a href="https://dev.to/rinsama77/data-structure-stack-and-queue-4ecd">Source</a></figcaption></figure><p>If you’ve ever waited in line for anything, you’ve been part of a queue. <em>The front of the line always gets processed first.</em></p><p>Stacks and queues can be implemented in different ways, but they <strong>must </strong>follow the rules highlighted above in italic.</p><h3>Stack Implementation</h3><p>A stack can be thought of like… a physical stack. In terms of programming however, we can think of a stack as an array. However, we need to limit the mutation of the array so it follows the<strong> Last In First Out(LIFO) rule.</strong></p><p>We’re going to consider a teacher grading papers and entering them into her grade-book for this example. When the teachers finishes grading a paper, she places it in the stack. Once she’s finished grading, she’ll remove papers from the top of the stack to enter into the grade-book.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0dfc582fde519f217b7f481f04668d94/href">https://medium.com/media/0dfc582fde519f217b7f481f04668d94/href</a></iframe><p>This is a simple implementation of a stack — notice that the <strong>last</strong> paper that gets graded is the <strong>first</strong> one that gets “popped” off the stack and into the grade-book. We’ve used push and pop to operate on the end of the array, but couldn’t we do this with unshift and shift too?</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e225913b362d759ea96ee39ee2ffa857/href">https://medium.com/media/e225913b362d759ea96ee39ee2ffa857/href</a></iframe><p>This implementation does follow the <strong>LIFO</strong> rule, but it’s not very efficient. Remember that arrays are indexed in JavaScript, so every time we change the beginning of the array, the rest of the array gets re-indexed.</p><p>We’ve uncovered the second rule of stacks and queues — an overall rule for data structures in general. The purpose of using a data structure is that we’re improving on the time and/or number of operations it takes to process that data — it’s <strong>time complexity</strong>. (If this sounds unfamiliar, check out my blog on <a href="https://medium.com/swlh/small-math-to-big-o-901a90998871">Big O Notation</a>).</p><p>Stacks and Queues are most efficient at <strong>insertion</strong> and <strong>removal, </strong>at <strong>O(1)</strong> or<strong> </strong>constant time. Using shift and unshift re-indexes the array, so at best we’re in O(n) time, where the time grows as the length of the array grows. Push and pop only change the end of the array, so it works in constant time. However, we don’t want to accidentally use another method on an array, so it’s better to limit ourselves by implementing it using another data structure — <a href="https://medium.com/better-programming/singly-and-doubly-linked-lists-in-javascript-7515f47c9f60">a linked list</a>.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ee9d163648ac3cc94bcab2152046cf9d/href">https://medium.com/media/ee9d163648ac3cc94bcab2152046cf9d/href</a></iframe><p>Now we’ve limited the methods for our stack, we’ve ensured that it is efficient and follows the <strong>LIFO</strong> rule.</p><h3>Queue Implementation</h3><p>If we can implement a stack with an array, surely we can do the same with a Queue, right? In this example, we’re going to consider a print queue — the printer is going to handle documents <em>in the order that they were sent in</em>, in other words, <strong>First In First Out (FIFO)</strong>.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/91a2f940ee62d91acbe4036a2d8ed6cc/href">https://medium.com/media/91a2f940ee62d91acbe4036a2d8ed6cc/href</a></iframe><p>In order for our queue to follow FIFO, we need to remove from the opposite end that we add to. That means that we’ll have to end up using shift or unshift, which will reduce our efficiency through re-indexing. We need to use a different data structure to implement our Queue.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f65e72c1057de04272b48137aed12516/href">https://medium.com/media/f65e72c1057de04272b48137aed12516/href</a></iframe><p>In this example we’re using enqueue to add elements and dequeue to remove elements.</p><h4>Other Operations</h4><p>Remember that Stacks and Queues are used for their efficiency in insertion and removal, so their time complexity for accessing and searching are limited to your implementation. In the case of our linked lists, they are <strong>O(n). </strong>However, as long<strong> </strong>as your implementation has constant time for Insertion/Removal and follows the LIFO/FIFO rules,<strong> </strong>your stack/queue will work.</p><h3><strong>Resources</strong></h3><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FwjI1WNcIntg%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DwjI1WNcIntg&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FwjI1WNcIntg%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/c4136234aeea70c77e1581200bb81af2/href">https://medium.com/media/c4136234aeea70c77e1581200bb81af2/href</a></iframe><ul><li><a href="https://dev.to/emmabostian/stacks-vs-queues-in-javascript-4d1o">Stacks vs. Queues In JavaScript</a></li><li><a href="https://medium.com/javascript-in-plain-english/javascript-what-are-stack-and-queue-79df7af5a566">JavaScript: What are Stack and Queue?</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ef0f838fc534" width="1" height="1" alt=""><hr><p><a href="https://medium.com/swlh/stacks-and-queues-simplified-ef0f838fc534">Stacks and Queues, Simplified</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>
        <item>
            <title><![CDATA[You’re Not My (Data) Type: An Intro to TypeScript — Part 2]]></title>
            <link>https://levelup.gitconnected.com/youre-not-my-data-type-an-intro-to-typescript-part-2-b2001f9e2225?source=rss-fa5b9ed31e3e------2</link>
            <guid isPermaLink="false">https://medium.com/p/b2001f9e2225</guid>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[type]]></category>
            <dc:creator><![CDATA[Gianfranco Nuschese]]></dc:creator>
            <pubDate>Thu, 06 Feb 2020 01:57:06 GMT</pubDate>
            <atom:updated>2020-02-06T03:27:15.677Z</atom:updated>
            <content:encoded><![CDATA[<h3>You’re Not My (Data) Type: An Intro to TypeScript — Part 2</h3><p><em>Note: This is a continuation of an earlier blog that I’ve written </em><a href="https://levelup.gitconnected.com/youre-not-my-data-type-an-intro-to-typescript-38dab9cdc90a"><em>here</em></a><em>. If you are new to TypeScript, I highly recommend starting with the first blog before moving onto what’s below.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7QwRdAxb9Q8wejjQJiFJsQ.png" /><figcaption>TypeScript is a superset of JavaScript.</figcaption></figure><p>Now that we’ve covered basic assignment for primitive data types and data structures, we can move onto some of the more non-traditional features that TypeScript offers us.</p><h3>New Types in TypeScript</h3><p>Since TypeScript is a superset of JavaScript, it has access to all the data types available in JavaScript. However, we must also remember that because TypeScript is a tool that gets compiled into JavaScript, TypeScript has access to new types.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/61a3af6853359006dbc9d3fe6b011c67/href">https://medium.com/media/61a3af6853359006dbc9d3fe6b011c67/href</a></iframe><h4>Tuples and Union Types</h4><p>The first type we’ll look at is a <strong>tuple</strong>. A tuple is an array of fixed length that has pre-determined types in each slot. In the object above, we’ve defined that the team property of the player object is a tuple — an array with a string and a number <strong>in that order.</strong> Below is an example of an error we’ll get if the tuple is incorrectly assigned.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6njXYkuzHlN5Zgg6OWcS2Q.png" /><figcaption>Incorrect type assignment on a tuple</figcaption></figure><p>We run into an issue with TypeScript’s type inference — remember TypeScript can infer your types for you. This is what pops up in VSCode’s highlight on the type-inferred object above.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/898/1*1nUZPEAZfwq4nvIQ6U6KqQ.png" /><figcaption>Type Inference of a Union Type</figcaption></figure><p>Notice that when writing the tuple, we declare the types inside the array team:[string, number], but TypeScript has inferred it differently. This is what’s called a <strong>Union</strong> type. When a variable can have multiple types, we list the types it can be separated by a “|”. In this case, TypeScript has inferred our tuple to actually be an array that can have either strings <strong>or</strong> numbers in it. Keep in mind when using tuples, you’ll <strong>have to declare</strong> them instead of relying on type inference.</p><h4>Enum Types</h4><p>An Enum type is a way of giving names to a set of numeric values. In the example above, we’ve made an enum called FieldPosition and assigned names to the four types of positions available for our player. We assign the “GOALIE” value to Bob by calling FieldPosition.GOALIE.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CooilN5eN65VuuitnYxsdw.png" /><figcaption>Assignment of Enum Type</figcaption></figure><p>Since &quot;GOALIE&quot; is the first item in our array, it is a name for the numeric value 0, which also explains why we’ve pre-defined the type as a Number. Enums start at 0 much like arrays, but if we define the starting number, each numeric value after that will follow in order.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0sluhpdGi-f5UdUDc8hdJg.png" /><figcaption>Assigning a new number to the first Enum type.</figcaption></figure><h4>The Any Type</h4><p>The any type is self-explanatory — it is used when we don’t know what type our variable should or will be. The any type should be used as rarely as possible, because it is poor planning and somewhat antithetical to the purpose of TypeScript. A good alternative is to rely on type inference.</p><p>In the example above, our active property on player is assigned an any type, so we’ve put a string to show that he is ‘injured’. However, in our type inferred version, we’ve put a boolean false , which seems more intuitive, and better planned by locking down the type.</p><h4>Literal Types and Type Aliases</h4><p>In TypeScript, we can also restrict our types to specific values. <strong>Literal</strong> types are somewhat like the const keyword in JavaScript, locking down the value of our variable. However, using <strong>Union</strong> types, we can limit our type to a few choices instead of only one value. Let’s use this to replace our Enum type from our example above.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jj-XQgwWtEI5LFkv1OVM0Q.png" /><figcaption>Using a Literal type for the position property</figcaption></figure><p>Now our position property can only be one of the strings ‘GOALIE’|’STRIKER’|’MIDFIELD’|’DEFENDER’ . Since we are specifically declaring the values the type can be, we can’t take advantage of type inference. However, we can store our literal type in a type <strong>alias, </strong>so that we can reuse it elsewhere if we need.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*muLReSCrzTK5WpLw1bb19g.png" /><figcaption>Using a type alias to define a literal type.</figcaption></figure><p>In this case, we’ve used the alias of FieldPosition to store our type using the type keyword. Now anywhere we assign FieldPosition, we’re limited to our four string values.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cgujSaSFq5iFFIts47LQiA.png" /><figcaption>Type Assignment error with FieldPosition Alias</figcaption></figure><p>Two important things to note here: you can use any type or value with a type alias or literal type. I’ve just used strings here. For example, we could create a jersey number type with type JerseyNumber = number or typeJerseyNumber = number | string depending on what typing we wanted. Type Aliases are used most often with union or tuple types.</p><p>Type aliases are are great for establishing variables, but they shouldn’t be used with objects. Remember a type alias is just that — an alias. If we wanted to make any changes to the object, we’d have to <a href="https://blog.fullstacktraining.com/typescript-interfaces-vs-types/">change the type</a> as well. To make our objects more flexible, we use interfaces.</p><h3>Interfaces</h3><p>An interface is like a pre-declared object with some exceptions. An interface can take optional parameters by adding a “?”. Classes that use interfaces are not limited to interface parameters, as long all required parameters are present. Interfaces can also extend one another like classes.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/761baf04c3cbfff451343de0341de9db/href">https://medium.com/media/761baf04c3cbfff451343de0341de9db/href</a></iframe><p>Above, I’ve refactored our player object into an interface. I’ve created a new player with our interface but TypeScript throws an error.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/614/1*wShHh5fJgZP-soHq12JbnQ.png" /><figcaption>Object missing values required in interface</figcaption></figure><p>Player1 has a name and jerseyNumber, but it doesn’t have an age. Since age is <strong>NOT </strong>an optional parameter, TypeScript throws an error.</p><p>Let’s now take a look at the class declaration of Player. In the constructor we’re calling public before all our variable parameters to make them accessible outside the class, and all the parameters with a “?” are optional. Notice we’re not getting any errors with active, but we’re getting an error with jerseyNumber .</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/598/1*0hNcORaeGhKJuLvQ5Av_xg.png" /><figcaption>Implementation of class Player using PlayerConfig</figcaption></figure><p>This is because we <strong>need to declare the parameters in our class constructor. </strong>Our class can always add more properties as long as each class instance <strong>has a name and age as defined in the interface. </strong>Bob has no errors because we’ve accounted for the additions in our class constructor. Dan is also valid because it fulfills the requirements of our original interface.</p><p>This is bad planning, however. We should be changing or extending our interface to account for all of these properties.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/599/1*7d7WMvtfdUabWzPErH3PCA.png" /><figcaption>Final implementation of class with interface</figcaption></figure><h3>Function Types</h3><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/14e3672587a22f8a4e2e9c4d5d8eee18/href">https://medium.com/media/14e3672587a22f8a4e2e9c4d5d8eee18/href</a></iframe><p>On last thing to look at is function typing. We can assign a type to the function’s return value by putting the type after a colon after the parameters. If we take a look at the first add function up top, we know it’s incorrect because that function should always return a number. <strong>TypeScript knows too because it can use type inference with functions.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/586/1*zP0p9ynmkP3tjD3y_AgACA.png" /><figcaption>TypeScript inferring the return type error</figcaption></figure><p>Since we’ve declared that the return value needs to be a string, it’s showing an error on the return portion of our function. However, it would be better to simply declare a number typing or let Typescript infer the type.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/577/1*ue_H77udRCnrTfHkFhP6xA.png" /><figcaption>Type inference on add function</figcaption></figure><p>That last function has a void typing. Since the function <strong>doesn’t return anything, </strong>its return value doesn’t exist. However, in order to avoid errors and the better understand our code, we mark void because a function in Javascript will always return undefined if it isn’t specified.</p><h3>Resources</h3><p><a href="https://levelup.gitconnected.com/youre-not-my-data-type-an-intro-to-typescript-38dab9cdc90a">You’re Not My (Data) Type: An Intro to TypeScript</a></p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FBwuLxPH8IDs%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DBwuLxPH8IDs&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FBwuLxPH8IDs%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/d81c3fa004d9b3258dede879bbb1bb84/href">https://medium.com/media/d81c3fa004d9b3258dede879bbb1bb84/href</a></iframe><ul><li><a href="https://www.typescriptlang.org/docs/home.html">Familiar With TypeScript already?</a></li><li><a href="https://medium.com/javascript-in-plain-english/typescript-with-node-and-express-js-why-when-and-how-eb6bc73edd5d">How (and why) you should use TypeScript with Node and Express.</a></li><li><a href="https://www.typescriptlang.org/docs/handbook/functions.html">Documentation - More on Functions</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b2001f9e2225" width="1" height="1" alt=""><hr><p><a href="https://levelup.gitconnected.com/youre-not-my-data-type-an-intro-to-typescript-part-2-b2001f9e2225">You’re Not My (Data) Type: An Intro to TypeScript — Part 2</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[You’re Not My (Data) Type: An Intro to TypeScript]]></title>
            <link>https://levelup.gitconnected.com/youre-not-my-data-type-an-intro-to-typescript-38dab9cdc90a?source=rss-fa5b9ed31e3e------2</link>
            <guid isPermaLink="false">https://medium.com/p/38dab9cdc90a</guid>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[software-development]]></category>
            <dc:creator><![CDATA[Gianfranco Nuschese]]></dc:creator>
            <pubDate>Sun, 02 Feb 2020 23:05:44 GMT</pubDate>
            <atom:updated>2020-02-06T01:58:21.626Z</atom:updated>
            <content:encoded><![CDATA[<h3>You’re Not My (Data) Type: An Intro to TypeScript — Part 1</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7QwRdAxb9Q8wejjQJiFJsQ.png" /><figcaption>TypeScript is a superset of JavaScript</figcaption></figure><p>If you’ve ever used or written an API before, you know that an essential part of using it correctly is understanding the data in the response. In order to work with the data, you need to understand the<strong> shape</strong> it comes in, and the <strong>types of data</strong> within that shape. TypeScript allows us to pre-determine the shapes and types of our data in order to <strong>avoid errors</strong> and have <strong>organized code</strong>.</p><p>TypeScript is a superset of JavaScript, so any valid JavaScript is also valid TypeScript. It also means that it <strong>must be compiled</strong> into regular JavaScript before the browser or node can run it. Since TypeScript tells our code what data type we’re expecting <strong>before runtime, </strong>it<strong> </strong>saves time by catching errors earlier. It makes our code <strong>more predictable and readable</strong>.</p><p>This may sound confusing, but we can simply think of TypeScript as a tool that helps us write better code. Our TypeScript won’t be so radically different from our compiled JavaScript.</p><h4>Types in JavaScript</h4><p>JavaScript is <strong><em>dynamically typed</em></strong>, which means that variables can be declared without restricting them to a specific data type. In case you forgot, JavaScript has 8 different primitive data types as specified by the <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures">MDN</a>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*D6xcdRfdGN3VKJ3hMARXOg.png" /><figcaption>Primitive Data Types</figcaption></figure><p>In this post, we’ll work with a few of these primitive data types and some data structures.</p><h4>Compiling to JavaScript</h4><p>In order to use TypeScript, all we have to do is install the npm package. If you’d like to install it globally on your machine, you can use the -g flag. Otherwise, run it without the -g in your npm-enabled repo of choice.</p><pre>npm install -g typescript</pre><p>In order to compile our TypeScript, we’ll need to run a command — tsc or TypeScript Compiler.</p><pre>tsc your-typescript-file.ts </pre><p>TypeScript can be incorporated into your build tools and used with frameworks, but the easiest way to get started is to compile it yourself in the command line. <em>NOTE: I will be using VSCode to demonstrate because it has great integration with TypeScript — I highly recommend using it!</em></p><h3>Establishing Primitive Types</h3><p>We’ll start with a simple web page that takes in two numbers, an optional string, and returns the two numbers added together with or without the string. Try out the function in the Codepen below.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fcodepen.io%2FGiagnus64%2Fembed%2Fpreview%2FOJPYBEj%3Fheight%3D600%26slug-hash%3DOJPYBEj%26default-tabs%3Djs%2Cresult%26host%3Dhttps%3A%2F%2Fcodepen.io&amp;display_name=CodePen&amp;url=https%3A%2F%2Fcodepen.io%2FGiagnus64%2Fpen%2FOJPYBEj&amp;image=https%3A%2F%2Fscreenshot.codepen.io%2F1259883.OJPYBEj.small.83de2a74-077e-4e6b-a4ba-4596cc47a53c.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=codepen" width="800" height="600" frameborder="0" scrolling="no"><a href="https://medium.com/media/c23355187f133cefe925125f4c155a5b/href">https://medium.com/media/c23355187f133cefe925125f4c155a5b/href</a></iframe><p>Looks like we forgot to parse our integers when we pulled the values from our inputs, so all we’re getting is string concatenation. We’re not getting any errors because our code is semantically correct — we had to wait until we ran the code to see that something’s wrong. Let’s take a look at how TypeScript would help us in this situation.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/de99bdd066f9dab45ac5bd791db95cf0/href">https://medium.com/media/de99bdd066f9dab45ac5bd791db95cf0/href</a></iframe><p>Let’s break down the add function first. We’re now telling our add function to expect a specific type for all the variables we’re passing into it — it expects thing1 and thing2 to be numbers, the phrase to be a string, and showString should be a boolean. Now when we try to compile this code, TypeScript will give us the following errors:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sZIMD4ADNlgqvfLSwYywdg.png" /><figcaption>Look at these wonderful errors!</figcaption></figure><p>TypeScript tells us the exact lines that our errors are on, and what the errors are. Amazing! All we need to do is add parseInt when passing into our add function.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fcodepen.io%2FGiagnus64%2Fembed%2Fpreview%2FvYEwVwx%3Fheight%3D600%26slug-hash%3DvYEwVwx%26default-tabs%3Djs%2Cresult%26host%3Dhttps%3A%2F%2Fcodepen.io&amp;display_name=CodePen&amp;url=https%3A%2F%2Fcodepen.io%2FGiagnus64%2Fpen%2FvYEwVwx&amp;image=https%3A%2F%2Fscreenshot.codepen.io%2F1259883.vYEwVwx.small.5fb9da1e-34db-4e74-9f54-ceb65d1b9b85.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=codepen" width="800" height="600" frameborder="0" scrolling="no"><a href="https://medium.com/media/fe1c8bb8c9435a29bcc7a15b8f68f61a/href">https://medium.com/media/fe1c8bb8c9435a29bcc7a15b8f68f61a/href</a></iframe><h4>HTML Element Types</h4><p>When we declared our variables for our HTML elements above, we included the ! as HTMLXElement at the end of the declaration. TypeScript also has built in types for HTML elements to ensure that you don’t do any illegal operations on those elements. For example, if we tried to call answer.value in our code above, TypeScript would give us an error because value is never used on a span element. DOM typing is a more advanced topic so I’m not covering it in depth here, but check the resources at the bottom of the page for more info.</p><h3>Object and Data Structure Typing</h3><p>Now that we’ve covered some primitive types, let’s move onto structural typing. TypeScript allows us to define what our objects and arrays will look like ahead of time. Remember that in JavaScript, calling an unknown property of an object just results in undefined instead of throwing an error.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3d110d01998985f5a2ecc295c18ea72b/href">https://medium.com/media/3d110d01998985f5a2ecc295c18ea72b/href</a></iframe><p>In the top part of the code above, we’re defining an object and saving it to a variable, Person. Before we define the object, we use TypeScript to define what keys the object will have, and the types that those keys’ values need to be. Now if we try to assign the string “24” to the age value, we’ll get an error. <em>Note: Another benefit of VSCode is that we’ll get errors right away even before compile time via code highlighting. Even faster error checking!</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7LF7JKP6JDdUqgKcoja_cg.png" /><figcaption>Highlighting wrong type assignment error with objects</figcaption></figure><p>We also have to define the type(s) that our hobbies array can hold.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eHy5MYUdj41hDFk-k7BG2g.png" /><figcaption>Highlighting wrong type assignment error with array</figcaption></figure><p>These errors will also happen if you try to mutate the object incorrectly after its definition:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EaSgMv3sYqhFaqZ2Crh-WQ.png" /><figcaption>Highlighting wrong type assignment error with objects</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*K0s96m7jYfF7fcYE0MfZ6A.png" /><figcaption>Highlighting wrong type assignment error with objects</figcaption></figure><p>We’ll also get an error if we try to add another key-value pair that’s not pre-defined.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tWHZSTI_6Q5xAbJVbahpyw.png" /><figcaption>Highlighting extra key value error with objects</figcaption></figure><p>Pre-defining your structures can come in handy when you know the shape that your object or array needs to take, but what if you need to add something to either of them? It seems a bit tedious to have to update everything twice; that’s not very DRY. TypeScript can account for that through <strong>type inference.</strong></p><h3>Type Inference</h3><p>If you don’t pre-define the types for your data structures, TypeScript can <strong>infer </strong>the type from the assigned value. Let’s take a look at the code in the second half of the gist above highlighted in VSCode.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/868/1*aEMrv3Zk2lxxnmdqTT5WGQ.png" /><figcaption>Highlight of type-inferred object</figcaption></figure><p>Whoa! TypeScript did all that work of typing our object for us through inference. Now we can add another key-value pair without worrying about changing our definition. This is especially useful when you know that your types will be fairly simple.</p><h3>And More…</h3><p>TypeScript is a deep language with lots of features that improve upon JavaScript. I’ve covered some of the basics regarding primitive data types in this blog. In the <a href="https://medium.com/@gianfranconuschese/youre-not-my-data-type-an-intro-to-typescript-part-2-b2001f9e2225">next installment</a>, I’ll cover types that are unique to TypeScript, function typing, and interfaces.</p><h3>Resources</h3><p><a href="https://medium.com/@gianfranconuschese/youre-not-my-data-type-an-intro-to-typescript-part-2-b2001f9e2225">You’re Not My (Data) Type : An Intro to TypeScript — Part 2</a></p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FBwuLxPH8IDs%3Fstart%3D8466%26feature%3Doembed%26start%3D8466&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DBwuLxPH8IDs&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FBwuLxPH8IDs%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/4d3b116dd2ef28efce33a6072e549adc/href">https://medium.com/media/4d3b116dd2ef28efce33a6072e549adc/href</a></iframe><ul><li><a href="https://medium.com/javascript-in-plain-english/typescript-61097f3b0dc4">TypeScript: Meet JavaScript’s Parent</a></li><li><a href="http://www.typescriptlang.org/docs/home.html">Familiar With TypeScript already?</a></li><li><a href="https://medium.com/@tomsu/typescript-tips-tricks-c8fdef998d50">TypeScript — Tips &amp; Tricks</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=38dab9cdc90a" width="1" height="1" alt=""><hr><p><a href="https://levelup.gitconnected.com/youre-not-my-data-type-an-intro-to-typescript-38dab9cdc90a">You’re Not My (Data) Type: An Intro to TypeScript</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[Intermediate Sorting Algorithms in JavaScript]]></title>
            <link>https://medium.com/@gianfranconuschese/intermediate-sorting-algorithms-in-javascript-4ec8b641b32?source=rss-fa5b9ed31e3e------2</link>
            <guid isPermaLink="false">https://medium.com/p/4ec8b641b32</guid>
            <category><![CDATA[merge-sort]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[sorting-algorithms]]></category>
            <category><![CDATA[radix-sort]]></category>
            <category><![CDATA[software-development]]></category>
            <dc:creator><![CDATA[Gianfranco Nuschese]]></dc:creator>
            <pubDate>Tue, 21 Jan 2020 01:33:11 GMT</pubDate>
            <atom:updated>2020-01-22T02:40:52.692Z</atom:updated>
            <content:encoded><![CDATA[<h4>Merge, Quick, and Radix Sort</h4><p>Recently I walked through some <a href="https://medium.com/javascript-in-plain-english/simple-sorting-algorithms-in-javascript-57d512ceaf5d">simple sorting algorithms</a> with JavaScript. I use the term “simple” because the algorithms are a bit easier to understand and implement, but the downside is their <a href="https://medium.com/swlh/small-math-to-big-o-901a90998871">time complexity</a> is high — O(<strong><em>n²</em></strong>) at worst. In this blog, we’re going to walk through some more complicated algorithms and aim to shorten our sorting time. (If you want to see ruby implementations, I’ve included them at the bottom of this post.)</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2FqucJWFolJN6rS%2Ftwitter%2Fiframe&amp;display_name=Giphy&amp;url=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2FqucJWFolJN6rS%2Fgiphy.gif&amp;image=https%3A%2F%2Fi.giphy.com%2Fmedia%2FqucJWFolJN6rS%2Fgiphy.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="220" frameborder="0" scrolling="no"><a href="https://medium.com/media/6b860b54f36902799bf902d6926c9a9f/href">https://medium.com/media/6b860b54f36902799bf902d6926c9a9f/href</a></iframe><h3>Recursion</h3><p>Merge and Quick Sort use a concept called recursion. <a href="https://medium.com/free-code-camp/how-recursion-works-explained-with-flowcharts-and-a-video-de61f40cb7f9">Recursion</a> is when a function calls itself inside of itself. Every recursive function needs a base case to return so that the function doesn’t get stuck in an infinite loop calling itself.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2F1onboJZSge0CY%2Ftwitter%2Fiframe&amp;url=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2F1onboJZSge0CY%2Fgiphy.gif&amp;image=https%3A%2F%2Fi.giphy.com%2Fmedia%2F1onboJZSge0CY%2Fgiphy.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="514" frameborder="0" scrolling="no"><a href="https://medium.com/media/d11f4894b2d2c49720d93873092a8b34/href">https://medium.com/media/d11f4894b2d2c49720d93873092a8b34/href</a></iframe><p>We’ll write a quick recursive function in order to explore how recursion works.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/eed65187ee5e55785a99d69528512948/href">https://medium.com/media/eed65187ee5e55785a99d69528512948/href</a></iframe><p>I recommend throwing this into your favorite testing environment so that you can follow the call stack as the function works — remember you can always throw it into a snippet in Chrome and use the “debugger” line to step through the function. Let’s follow what happens if we want to reverse the string “bar”.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4b96d3508f852c595a577acfdbfc5e77/href">https://medium.com/media/4b96d3508f852c595a577acfdbfc5e77/href</a></iframe><h3>Merge Sort</h3><p>Now that we’ve covered recursion, let’s start working on implementing our sorting algorithms. Both Merge and Quick sort take advantage of the fact that <strong>arrays of length 0 or 1 are always sorted. </strong>Merge Sort works by breaking down an array of elements in halves until left with “sorted” arrays of length 0 or 1, and then merges those sorted arrays together until left with the final sorted array. Let’s break it down.</p><p>The most important part of the sort is implementing the function that merges arrays. This function assumes that the arrays are sorted — that we’ll be working with 0 or 1 length arrays.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/76159f76c76d81bd1b80e874d0a9383f/href">https://medium.com/media/76159f76c76d81bd1b80e874d0a9383f/href</a></iframe><p>Now that we’ve built the merging function, we can use it to build the sorting function.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/94880b08d3dbab495a148d4804c45f4c/href">https://medium.com/media/94880b08d3dbab495a148d4804c45f4c/href</a></iframe><p>It seems too simple, but let’s think about our solution: Our <strong>base case</strong> is to return an array of length 0 or 1 that is sorted. If not, we split the array in half, merge sort the two arrays, and merge the sorted arrays together. Here’s a visual breakdown:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/876/1*17LDTpCYEugOKC6q112qQg.png" /><figcaption>A visual breakdown of Merge Sort</figcaption></figure><h3>Quick Sort</h3><p>Quick Sort splits arrays just like merge sort, but instead of finding a midpoint, it uses a pivot point. Once a pivot point is found, we shift all the values that are lesser than the pivot point to the left of the array, and all the values greater to the right. At that step the pivot point is “sorted”. The function becomes recursive when we do the same to each side of the pivot point until our array is sorted.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/629/1*WpvBjuS-qD4vrO5Ot1aDvA.gif" /><figcaption>First pass of Quick Sort</figcaption></figure><p>The visual aid and our implementation will always pick the first item in the array as our pivot point. The current pivot point is yellow. The red color represents the array value we’re currently iterating over. Purple means the value is greater than the pivot point, and green means less than. Whenever we find an item that is <strong>less than</strong> the pivot value we swap it with the current iteration, placing it at the<strong><em> </em>beginning of the unsorted portion</strong> of the array. Once we reach the end, we swap the pivot point with the last number we swapped, placing in front of all the values less than, making it sorted and designated by the color orange.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/629/1*Ii2cvVpMksNAOxIMMbGNtQ.gif" /><figcaption>Quick Sort Left Side</figcaption></figure><p>We then do the same sort on the left side of the pivot point, eventually reaching our base case — (seen above for 5 and 15) — two arrays of length 1 that are sorted. We’ll then do the same on the right side and end up with a sorted array. Take note that we’re swapping all of these numbers in place — as opposed to Merge Sort where we’re splitting arrays and merging them back together.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/629/1*BintjyXlDQbdOUEciEwIYA.gif" /><figcaption>Quick Sort Third Side</figcaption></figure><p>Let’s get started with our helper methods. We’ll need two this time: a swapping helper method and a pivot helper method. Our pivot method will need to return a pivot index so that when we recursively call it, we know where to start our new pivot.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/39638a24d81e6f90f66b560343c5fd24/href">https://medium.com/media/39638a24d81e6f90f66b560343c5fd24/href</a></iframe><p>We’ll need to establish default arguments for our Quick Sort method as well, since we’ll be passing in different arguments on every pivot. You should notice that our base case acts a little differently than normal — we’re only calling pivot if our array is unsorted, and simply returning the original array at the end of the function. This is because we’re mutating the array <strong>in place, </strong>so as long as we pass in the proper numbers to pivot, we’ll eventually return the same array but sorted.</p><h4>Big O of Merge and Quick Sort</h4><p>So since we’re splitting arrays up with these sorts, we can expect to have at least O(<strong><em>log n</em></strong>). Remember that log finds <strong>How many of <em>one number</em> do we multiply to get <em>another number? </em></strong>—since we’re splitting arrays into one or zero elements, it stands that we’ll have to <strong>double</strong> the elements <strong><em>n</em></strong> times to get to the length of our original array. Since we’re doing comparisons in both sorts, we’ll be comparing every element in the array, which means we’ll be doing <strong><em>n</em></strong> comparisons <strong><em>log n</em></strong> times. Therefore, at worst our sorts have a time complexity of O(<strong><em>n log n</em></strong>). However, Quick Sort is a bit different.</p><p>The efficiency of our sort actually depends on our pivot point. In the best case, our pivot point would be roughly the midpoint of the numbers in the array, leading to an even distribution of splits on either side. Our implementation picked the first element in the array every time. If we had the worst case of an <strong>already sorted </strong>array, we’d end up splitting the array <strong><em>n</em></strong> times and comparing numbers <strong><em>n</em></strong> times giving us O(<strong><em>n²</em></strong>). If you remember, this is not better than our simple sorting algorithms. We could get around this by always picking a random element in the array, but on the chance that we picked the highest or lowest number in the array, we’d still end up with O(<strong><em>n²</em></strong>).</p><h3>Radix Sort</h3><p>Every sorting algorithm I’ve covered, including the simple ones, have all been based on comparing values. Radix sort is unique in that it doesn’t compare values but sorts them into “buckets” based on their digit placement. Techically, Radix Sort only works with numbers <strong>but</strong> it can be used with strings and images since they can be converted to binary.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/831/1*Hs8HH6LI9ZQv_GNI03-NUA.gif" /><figcaption>Radix Sort First Pass</figcaption></figure><p>We’re going to be working with base 10 numbers in our implementation, but the sort can be used with other numbers. The numbers get sorted into buckets based on their digit placement. The digit highlighted in red is the one that the sort is currently based on. The sort then puts the numbers back in the list starting with the 0 bucket until all buckets are empty. The process needs to be repeated <strong><em>x</em></strong> times, where <strong><em>x</em></strong> is the amount of digits that the largest number in the sort has.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/831/1*6KCnpmuRM1-_CMdXt0et8A.gif" /><figcaption>Radix Sort Final Passes</figcaption></figure><p>This sort will employ three helper functions — getDigit, digitCount, and mostDigits. We’ll use getDigit to find the digit we need to sort by in our quick sort implementation. digitCount will be used in the mostDigits function to find the max number of digits we need to iterate over. These functions can be written in different ways — like converting numbers to strings and back — but I’ve included the math heavy routes since they add to the understanding of why Radix Sort works.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/22231fa5f508e6480d55d0c3ce3f74ee/href">https://medium.com/media/22231fa5f508e6480d55d0c3ce3f74ee/href</a></iframe><p>Now that we’ve got out helpers, our sort implementation is a little more involved than the ones above. Take note of line 18: after everything is placed into buckets, we’re reassigning “nums” to a new array that uses “.concat” and the spread operator to flatten the arrays in the buckets — isn’t that cool!?</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ce839d56d7fb6917649693822921b3f3/href">https://medium.com/media/ce839d56d7fb6917649693822921b3f3/href</a></iframe><h4>Big O of Radix Sort</h4><p>We’re iterating over <strong><em>n</em></strong> numbers <strong><em>k</em></strong> times, therefore the worst case time complexity is O(<strong><em>nk</em></strong>) where <strong><em>n</em></strong> is the length of the array and <strong><em>k</em></strong> is the number of digits in those numbers. It’s in linear time, which is faster than merge and quick sort, so it’s a popular choice for large data sets.</p><h4>Ruby Implementation of Sorts</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/66216dea2df7d2982b32a4f042c70f88/href">https://medium.com/media/66216dea2df7d2982b32a4f042c70f88/href</a></iframe><h3>Resources</h3><ul><li><a href="https://visualgo.net/en/sorting">Sorting (Bubble, Selection, Insertion, Merge, Quick, Counting, Radix) - VisuAlgo</a></li><li><a href="https://en.wikipedia.org/wiki/Comparison_sort">Comparison sort</a></li><li><a href="https://guide.freecodecamp.org/miscellaneous/freecodecamp-algorithm-merge-sort-guide/">Freecodecamp Algorithm Merge Sort Guide</a></li><li><a href="https://github.com/trekhleb/javascript-algorithms/tree/master/src/algorithms/sorting/radix-sort">trekhleb/javascript-algorithms</a></li></ul><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FRGuJga2Gl_k%3Ffeature%3Doembed&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DRGuJga2Gl_k&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FRGuJga2Gl_k%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/79c68a010f80cd328daa2d37a578ee93/href">https://medium.com/media/79c68a010f80cd328daa2d37a578ee93/href</a></iframe><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FSLauY6PpjW4&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DSLauY6PpjW4&amp;image=http%3A%2F%2Fi.ytimg.com%2Fvi%2FSLauY6PpjW4%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/b4e516a36ead2dedaf371edfabbfe1ef/href">https://medium.com/media/b4e516a36ead2dedaf371edfabbfe1ef/href</a></iframe><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4ec8b641b32" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Singly and Doubly-Linked Lists in JavaScript]]></title>
            <link>https://medium.com/better-programming/singly-and-doubly-linked-lists-in-javascript-7515f47c9f60?source=rss-fa5b9ed31e3e------2</link>
            <guid isPermaLink="false">https://medium.com/p/7515f47c9f60</guid>
            <category><![CDATA[data-structures]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Gianfranco Nuschese]]></dc:creator>
            <pubDate>Sat, 18 Jan 2020 01:06:24 GMT</pubDate>
            <atom:updated>2020-01-20T22:42:30.076Z</atom:updated>
            <content:encoded><![CDATA[<h4>Lists aren’t just arrays</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*YqCGzgmJGRDq17CU_9AZlQ.png" /><figcaption>Not that kind of link…. Source: <a href="https://yattatachi.com/tbt-how-the-legend-of-zelda-was-kinda-its-own-genre">https://yattatachi.com/tbt-how-the-legend-of-zelda-was-kinda-its-own-genre</a></figcaption></figure><p>When programmers see the word “list”, we usually immediately think “array”.</p><p>Arrays are great for storing data to iterate over, but since they have numbered indexes, manipulating elements in the array can be costly in terms of time and space complexity.</p><p>For example, if we wanted to insert a new element at the 10th index in a 100-element array, we’d have to re-index the other 90 elements after insertion.</p><p>If we need to work with a list of data that is constantly updated, we might want to use a data structure known as a <em>linked list</em>. A linked list can be thought of like a chain — it is a group of nodes with an established head, tail, and length.</p><p>Each node contains a value and a pointer to the next node in the chain. Singly-linked lists have pointers to the next node in the list while doubly-linked lists have pointers to both the previous and the next node in the chain.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/615/1*5wRMqVjLatOGX88VrZgacA.jpeg" /><figcaption>Examples of a singly and doubly-linked lists.</figcaption></figure><h3>Creating a Singly-Linked List</h3><p>(I recommend following along with the example at <a href="https://visualgo.net/en/list">Visualgo</a>). We need to create classes for a Node and for the List. See below for the properties of each.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/972/1*HlMnlX2X0_NQP1luY3PPhQ.png" /><figcaption>The base of our linked list class</figcaption></figure><p>In order to manipulate anything in our linked list we’ll need to follow three rules:</p><ol><li>Make sure to increase or decrease the length of the list when adding or removing nodes.</li><li>Make sure the list has the correct head, tails, and all nodes have accurate pointers.</li><li>When removing, make sure all pointers to removed nodes are severed, to ensure the node is properly deleted from memory.</li></ol><h4>Push and unshift</h4><p>When we add a node to either side of the list, we need to make sure the head and tail of our list are correct.</p><p>Since a list with one node’s head and tail are the same, we need to account for that case in our implementation. Take a look at the commented code below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/684/1*0Ymt-Ye3cAXRfRrCW3wYTg.png" /><figcaption>Implementation of push</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GyzBOIxCqbLerqMcxcV6zA.png" /><figcaption>Implementation of unshift</figcaption></figure><h4>Pop and shift</h4><p>When we’re removing a node from either side of the list, we’ll need to account for two more things — a list that is left with one node (because we’ll need to make sure our tail and head are accurate), and an empty list (so we can avoid runtime errors).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/798/1*sPllRZfSjjnbykMYZFnHMg.png" /><figcaption>Implementation of shift</figcaption></figure><p>By the nature of the linked list, we have access to the new head of the list by simply checking the current head’s pointer.</p><p>However, when we are popping off of the list, we need to iterate through the list in order to find the new tail. I’ll be employing a helper method that we can reuse in later methods on our class called getNodeAtIndex.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/812/1*rRULaTVIOkxq26vASv4y0A.png" /><figcaption>Implementation of getNodeAtIndex</figcaption></figure><p>This function uses a counter and iterates through the list until we get to the index of the node we need. In this case, we’ll need the second to last node, or list length minus two.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/868/1*D026fOiPEXd2rp-uk6dquA.png" /><figcaption>Implementation of Pop</figcaption></figure><h4>Getting and setting</h4><p>Since we already implemented the get method above for use in our pop implementation, all we need to do is implement the set method.</p><p>This method finds a node at the specified index, and changes its value to the passed-in variable. It will also use our getter method. We just need to handle the case if the node is not found.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/716/1*g4oksa5_Z-IK6u9tYz3oBA.png" /><figcaption>Implementation of setNodeAtIndex</figcaption></figure><h4>Inserting and removing</h4><p>Inserting and removing items from linked lists is made easier by all the previous methods we’ve just written. We’ll need to follow these steps:</p><ol><li>Check if the index exists in the linked list (return false if not).</li><li>If removing/adding at the beginning or end of the list, use the already written methods (no more worrying about the tail/head!).</li><li>Get the nodes before and after the inserted/removed node and assign their pointers properly.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0lkoKImmmtRjG1gQP5vgOw.png" /><figcaption>Implementation for removeFrom and insertAt</figcaption></figure><p>I’ve included the full implementation in a GitHub gist at the bottom of the page, along with a method to print our nodes for testing.</p><h3>Doubly-Linked Lists</h3><p>Doubly-linked lists have a similar implementation, but the references to both the previous and next nodes in the list have some benefits and disadvantages.</p><ol><li>We have to keep track of both <em>previous </em>and <em>next</em> pointers and make sure they are properly set when mutating the list.</li><li>Since we have access to the previous node reference, we no longer need to iterate over the list for the pop method.</li><li>Doubly-linked lists use more memory per node since they hold two pointers, but it allows us to traverse the list in both directions.</li><li>Doubly-linked lists have constant time for insertion and deletion at a known position while singly-linked lists have linear time.</li></ol><h3>Singly-Linked List Full Implementation</h3><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/36945acbb5f41a40afb6c49f2f03cda8/href">https://medium.com/media/36945acbb5f41a40afb6c49f2f03cda8/href</a></iframe><h3>Doubly-Linked List Full Implementation</h3><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f2dd16c7b5668894459037660d1619d1/href">https://medium.com/media/f2dd16c7b5668894459037660d1619d1/href</a></iframe><h3><strong>Resources</strong></h3><ul><li><a href="https://en.wikipedia.org/wiki/Linked_list#Linked_lists_vs._dynamic_arrays">Linked list</a></li><li><a href="https://www.tutorialspoint.com/difference-between-singly-linked-list-and-doubly-linked-list-in-java">Difference between Singly linked list and Doubly linked list in Java</a></li><li><a href="https://medium.com/journey-of-one-thousand-apps/data-structures-in-the-real-world-508f5968545a">Data Structures In The Real World — Linked List</a></li><li><a href="https://medium.com/swlh/small-math-to-big-o-901a90998871">Small Math to Big O</a></li></ul><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FnjTh_OwMljA%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DnjTh_OwMljA&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FnjTh_OwMljA%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/42e0f27b84f7f25006b4cb0f48c87c53/href">https://medium.com/media/42e0f27b84f7f25006b4cb0f48c87c53/href</a></iframe><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7515f47c9f60" width="1" height="1" alt=""><hr><p><a href="https://medium.com/better-programming/singly-and-doubly-linked-lists-in-javascript-7515f47c9f60">Singly and Doubly-Linked Lists in JavaScript</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[Let’s Talk about Tests, Baby]]></title>
            <link>https://javascript.plainenglish.io/lets-talk-about-tests-baby-dbc51c6d316c?source=rss-fa5b9ed31e3e------2</link>
            <guid isPermaLink="false">https://medium.com/p/dbc51c6d316c</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[jest]]></category>
            <category><![CDATA[testing]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[software-development]]></category>
            <dc:creator><![CDATA[Gianfranco Nuschese]]></dc:creator>
            <pubDate>Tue, 07 Jan 2020 21:20:08 GMT</pubDate>
            <atom:updated>2020-01-08T16:29:47.805Z</atom:updated>
            <content:encoded><![CDATA[<h4>… and all the good things and the bad things that may be</h4><p>Testing and Test-Driven Development is one of the most valuable skills in a developer’s toolkit. When I say testing, I don’t mean quick manual tests like using debugger/console.log (JS) or using Pry/Byebug (Ruby). I’m talking about writing separate test files with a library like Jest (JS) or Rspec (Ruby).</p><p><em>“So you’re telling me I have to write code that tests the code I just wrote?”</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0WNQnOC3tcQDzAW4j9lGow.jpeg" /><figcaption>#relatable</figcaption></figure><h3>Why Test?</h3><p>Writing tests is beneficial to your code in multiple ways.</p><p><strong>It makes you think about your code. </strong>When writing tests, you have to think about all of the edge cases that may or may not pass. What happens if you pass in a number where a string is expected? Or if something ends up as undefined or null? Writing tests acts as a self-check and allows you go back and refactor — which itself is another benefit.</p><p><strong>It helps you write cleaner code</strong>. If you have an encapsulating function that calls upon other functions, and that encapsulating function fails, it’s difficult to pinpoint where your logic went wrong. Testing helps you refactor your code to reusable, modular fragments that can be tested on their own before testing their integration. If you are having trouble following your code while writing tests, how do you think someone else will feel if they have to work with your code?</p><p><strong>It helps future-proof your code. </strong>Testing not only leads to cleaner and easier to read code — but the tests themselves can aid others in understanding your logic. It can also help you revisit code you haven’t seen for a while. Another benefit comes with test automation. If you need to add a feature or change code that already has tests, the tests can help you find errors in the fresh code, and prevent such errors from reaching the build.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/680/1*KUMkgeVv2kxWpbpI7gUnhA.png" /><figcaption>Should have written tests….</figcaption></figure><h3>Types of Tests</h3><p>Now that we know <em>why</em> testing is important, let’s look at the different kinds of tests.</p><h4>Unit Tests</h4><p>Unit tests are the most isolated type of test. They usually only involve testing one function, or a few lines of code. They are the easiest to write, and easiest to infer what the result might be. A majority of the tests programmers write are unit tests.</p><h4>Integration Tests</h4><p>Integration tests are for pieces of code that are <em>integrated </em>together, like a function that calls other functions. They are a little more difficult to write, because errors can pop up in more places (which is why we have unit tests). Integration tests are less frequent than unit tests, but just as important.</p><h4><strong>End-To-End Tests</strong></h4><p>End-to-End tests ensure that whatever code is written is reflected in the browser, these are sometimes called UI tests. An example would be validating the DOM after adding, removing, or changing some element. These are the most complex tests because they usually have multiple steps and require extra setup to run.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgfycat.com%2Fifr%2Fhotorangecoypu&amp;url=https%3A%2F%2Fgfycat.com%2Fhotorangecoypu-therewasanattempt-bettereveryloop&amp;image=https%3A%2F%2Fthumbs.gfycat.com%2FHotOrangeCoypu-size_restricted.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=gfycat" width="500" height="500" frameborder="0" scrolling="no"><a href="https://medium.com/media/ea8536ec7d05e76b59a23ba94d797cd2/href">https://medium.com/media/ea8536ec7d05e76b59a23ba94d797cd2/href</a></iframe><h3>Setup</h3><p>Many testing libraries have two or all three of the necessary tools for testing integrated into one framework, but many frameworks allow integration with other libraries, so you can customize your tests accordingly.</p><ul><li><strong>Test Runner </strong>— a tool that executes the tests you’ve written and summarizes the results.<strong> </strong>Examples: Mocha (JS), Cucumber (Ruby/Multiple Languages)</li><li><strong>Assertion Library</strong> — a tool that defines logic conditions for tests. Example: Chai (JS), Rspec (Ruby)</li><li><strong>Headless Browser </strong>— a tool that simulates browser interaction for End-to-End testing. Examples: Puppeteer (JS), Capybara (Ruby/Multiple Languages)</li></ul><h3>Testing Example: Jest</h3><p>In the following examples I’ll be using Jest — a JavaScript based testing framework that incorporates a test runner and assertion library in one. In order to use Jest we’ll need to add it to our dev dependencies with the following command:</p><pre>npm install --save-dev jest</pre><p>In order to run our tests we’ll need to change the “test” script to run “jest” in our package.json:</p><pre>&quot;scripts&quot;: {<br>   &quot;test&quot;: &quot;jest&quot;<br>},</pre><p>Before we get into the examples, let’s break down the basics of a sample test. Here’s the function we’re testing:</p><pre>function add(num1, num2){<br>   return num1 + num2 <br>}</pre><p>And here’s the test we’ll write for it:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vyAaJJbgnI46SbhV2PWozA.png" /><figcaption>Diagram of a Jest Test</figcaption></figure><p>Not all testing examples will be exactly the same, but they will all usually have the these parts. The part underlined by blue is the <strong>description</strong> — it should describe what this test is doing. This is a generic description, but you could and should be more specific if you can — something like “Adds 2 + 2 to equal 4”. The “test” function in Jest takes in two parameters, the description and a callback function. The callback function uses the keyword “expect” and takes in the <strong>code you are testing,</strong> and a <strong>matcher with an expected output</strong>.</p><p>The matcher is the most important part, you can think of it as a comparison in word form. There are many matchers like toBeNull, toStrictlyEqual, toBeTruthy, etc. You can even add “.not” before the matcher if you are testing for the opposite of an expected output. Every framework has tons of matchers so make sure and find the right matcher for your test — they matter when it comes to the data type. The matcher we’re using above is toBe (which is almost the same as toEqual), but only because our expected output is a primitive type — a number. If we were matching an array, toBe would test for the string equivalent of each array to be the same, it would <strong>NOT</strong> test if the arrays have the same elements.</p><p>The tests should output something like this in your command line.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sk3BGap6eV8k9SwzU1dFig.png" /><figcaption>Command line testing summary.</figcaption></figure><p>Let’s try with a more robust example. Here’s the file we’ll be testing:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/cc771a45a8af3168759e247d42c880f0/href">https://medium.com/media/cc771a45a8af3168759e247d42c880f0/href</a></iframe><p>We’ll need to write our tests in another file the same name with “.test” appended to it — my file above is “app.js” so my test file is named “app.test.js”. Note the syntax we’re using to export the functions — we’re working in node so we need to use the “module.exports” — and below, the “require” syntax, in order for our tests to run properly.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d5eb49fe754a238fcfd038715886765f/href">https://medium.com/media/d5eb49fe754a238fcfd038715886765f/href</a></iframe><p>You might have noticed that we have two tests in our integration test function. We can stack multiple tests into one function if makes sense for organization. Let’s run our tests on and see what happens.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZJZo28mf7PT4w1k2tlpDBg.png" /><figcaption>Our unit test fails… but the integration test works??</figcaption></figure><p>How did our integration test fail when our unit test worked?? This is a strange case where the error is <em>actually </em>in the test. Our function doesn’t return the array after swapping two elements, so our test was expecting an array but instead got “undefined” because our swap function <strong>doesn’t return anything.</strong> You should also take a look at all the information that our tests gave us for the failure — they tell us what our matcher was looking for, what the result was instead of what we expected, and even tells us the part in our test code where it failed.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/aa729ddd218c1f2a2943705b1678278e/href">https://medium.com/media/aa729ddd218c1f2a2943705b1678278e/href</a></iframe><p>Instead of changing the original function, we simply save the swapped array to a variable, and test that variable to make sure the swap happened correctly. The file above also demonstrates that tests don’t strictly need the function call to be attached to the matcher — in this case the test only verified that the variable with the function output was correct.</p><p>I’ve included some resources below for more information on testing, and how to run end-to-end tests.</p><h3><strong>Resources</strong></h3><p><a href="https://medium.com/the-mission/end-to-end-e2e-testing-react-apps-with-selenium-webdriver-and-node-js-is-easier-than-you-think-bfa71f289786">End to End (e2e) Testing React Apps With Selenium WebDriver And Node.js is Easier Than You Think</a></p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2F7r4xVDI2vho%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3D7r4xVDI2vho&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2F7r4xVDI2vho%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/3ad942eb0575357b0fbe6db22016ca95/href">https://medium.com/media/3ad942eb0575357b0fbe6db22016ca95/href</a></iframe><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2Fr9HdJ8P6GQI%3Fstart%3D1762%26feature%3Doembed%26start%3D1762&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3Dr9HdJ8P6GQI&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2Fr9HdJ8P6GQI%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/84a453be4a86ddfc598237fbd447d957/href">https://medium.com/media/84a453be4a86ddfc598237fbd447d957/href</a></iframe><p><a href="https://medium.com/@gianfranconuschese/what-automation-can-do-for-you-rake-in-ruby-on-rails-ce6a729984e">https://medium.com/@gianfranconuschese/what-automation-can-do-for-you-rake-in-ruby-on-rails-ce6a729984e</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=dbc51c6d316c" width="1" height="1" alt=""><hr><p><a href="https://javascript.plainenglish.io/lets-talk-about-tests-baby-dbc51c6d316c">Let’s Talk about Tests, Baby</a> was originally published in <a href="https://javascript.plainenglish.io/">JavaScript in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>