<?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 Spencer Smith on Medium]]></title>
        <description><![CDATA[Stories by Spencer Smith on Medium]]></description>
        <link>https://medium.com/@smithspencer817?source=rss-9cdda60a5b00------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*UWCyIJP0aejCrzBR</url>
            <title>Stories by Spencer Smith on Medium</title>
            <link>https://medium.com/@smithspencer817?source=rss-9cdda60a5b00------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 18 Nov 2026 10:31:30 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@smithspencer817/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[Node.js Fundamentals (Personal Notes)]]></title>
            <link>https://smithspencer817.medium.com/node-js-fundamentals-personal-notes-82d7154021fc?source=rss-9cdda60a5b00------2</link>
            <guid isPermaLink="false">https://medium.com/p/82d7154021fc</guid>
            <dc:creator><![CDATA[Spencer Smith]]></dc:creator>
            <pubDate>Sun, 20 Dec 2020 20:11:08 GMT</pubDate>
            <atom:updated>2020-12-20T20:11:08.539Z</atom:updated>
            <content:encoded><![CDATA[<h3>How Does JavaScript Run?</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pHulkOt6whP9C8wjJsEjCg.png" /></figure><h3>How Does Function Execution Context Work?</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*I-BipjXHezOi1OF1exj_eg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rH0qa2inrTKa4dwzFrpcMQ.png" /></figure><h3>How Does Global Execution Context Work?</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6AwVO1ZbZUzyCHvlH9mZKg.png" /></figure><h3>How Does the Execution Stack Work?</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IUyX8JIQYNTEn7knmWgdyw.png" /></figure><h3>How Does the Event Queue Work?</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gQ6kGOr8p6ow6yRnOUg20w.png" /></figure><h3>How Does the Scope Chain Work?</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nByHcNX68qbaVejWc5bEVg.png" /></figure><h3>How Do Closures Work?</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YJ_pht-dKcx9UBY-SQIQPA.png" /></figure><h3>How Does ‘This’ Work?</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MbzX3wMRWiemI6yRLnWEGg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6JlQXpft-5WtQtqSrQTD9Q.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=82d7154021fc" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Quick Take: Express vs. Django vs. Ruby on Rails]]></title>
            <link>https://smithspencer817.medium.com/quick-take-express-vs-django-vs-ruby-on-rails-3e25b64bd91c?source=rss-9cdda60a5b00------2</link>
            <guid isPermaLink="false">https://medium.com/p/3e25b64bd91c</guid>
            <dc:creator><![CDATA[Spencer Smith]]></dc:creator>
            <pubDate>Mon, 14 Dec 2020 01:01:54 GMT</pubDate>
            <atom:updated>2020-12-14T01:01:54.555Z</atom:updated>
            <content:encoded><![CDATA[<p>I applied for a company this week that was hiring for a Python position. Python was the first language I ever learned and I felt very comfortable with the syntax, but I hadn’t yet used it to build a project. I got in touch with one of their employees who told me that the company would consider me if I was able to build a project with Django by the time they started kicking off interviews.</p><p>While I didn’t wind up getting the interview, I did take him seriously and whipped together a basic polling app over the next couple of days. The exciting part for me is that Django was the last of the three mainstream back-end web frameworks that I hadn’t yet been exposed to, the other two being Express.js and Ruby on Rails.</p><p>I’m definitely still in the early stages with Django, but I’ve now spent enough time with it that I can thoughtfully consider the advantages and disadvantages of all three frameworks when making decisions on how to architect my server-side projects.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*US12UCC_3AwoIDBn7MFv7Q.jpeg" /></figure><h3>Ruby on Rails</h3><h4>Advantages</h4><p>Rails is so simple to use once you get past the initial learning curve. Complex models and migrations are easily composable from the command line, and Rails’ built-in ActiveRecord ORM allows you to define complex relationships between several models in minutes. Since Rails comes packaged with SQLite3 by default, you don’t need to spend time configuring your database connection in development unless you’re wanting to use a NoSQL database like MongoDB. Rails follows a ‘convention over configuration’ philosophy and development becomes lighting fast once you learn the conventions. It’s a great framework for beginners looking to get their feet wet with back-end web development.</p><h4>Disadvantages</h4><p>Rails is a very opinionated framework, having specific rules about where most things should be and how most things should work. This is great for when you’re wanting to build a basic CRUD API to communicate with your front end, but the strict adherence to following certain rules makes the framework feel more difficult to customize. The starter templates come with a ton of directories that make the app feel large and monolithic before you’ve even written a single line of code. Rails performs a little more slowly than other back-end frameworks, which is probably one of the main explanations for its decline in popularity over the last couple of years despite its massive community.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*i2fRBk3GsYLeUk_Rh7AzHw.png" /></figure><h3>Express.js</h3><h4>Advantages</h4><p>Developers describe Express as being a “lightweight” framework. Since Ruby on Rails was the first framework I ever learned, the benefits and advantages of knowing a lightweight framework like Express were immediately apparent. While frameworks like Rails and Django give you a ton of toys right out of the box, Express’s minimalistic approach gives you total control over the feel and customization of your server. This is critical when you are dealing with an app that doesn’t follow normal conventions and needs to behave in a very specific way.</p><h4>Disadvantages</h4><p>It’s hard to point out a lot of the disadvantages to using Express, because the main “disadvantages” could just as easily be viewed as positives or features. Since Express basically just gives you the ability to start your server and define your routes, any other layers you choose to implement such as authentication, data validation, database integration, ORM, etc. are entirely on you. This can be a little intimidating for beginners, so you’ll want to make sure you have a good understanding of the common “parts” that make up an API if you choose Express as your first framework. Two of the most commonly used ORMs in Express are Sequelize and Knex.js, and in my experience, the built-in Rails and Django ORMs were both better documented and easier to understand.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3ByF2bI_th39NCQ9a0Q9Yw.png" /></figure><h3>Django</h3><h4>Advantages</h4><p>Django follows the ‘convention over configuration’ philosophy and similar to Rails, the conventions make it easy to spin up basic apps very quickly. Django seems to bring together the best of both worlds between Express and Rails, offering the developer just enough freedom to be dangerous but providing enough of the right tools to help automate common tasks. The documentation is extensive and very well-written. By following the walk-through on the website, I went from knowing nothing about the framework to building a basic polling app in a <em>day</em>. Django does require a little more configuration than Rails, but the file system doesn’t seem nearly as bloated and is far easier to navigate.</p><h4>Disadvantages</h4><p>Django uses regular expressions for route handling. The structure isn’t complicated, it’s just the syntax that might take some getting used to, especially for beginners. The way Django handles its file system is also a little weird at first, as you’ll frequently find yourself nesting directories inside of other directories that share the same name by necessity. Django seems to be perfect for medium-sized projects; a little too heavy-duty for a smaller app, but becomes more challenging to manage as you add more components to your app (all of your models, for example, have to be at the same level in the same directory, which can make models difficult to organize if you have a lot of them).</p><h3>Conclusion</h3><p>I’m glad that I learned Rails first as it gave me a good big-picture view of the key components that make up back end development. That said, it was when I started working in Express that I grew the most as a developer — removing the “training wheels” that Rails provides forced me to understand how all of the parts of an API work on a deeper level. There are a ton of libraries that work very well with Express, so there are a variety of ways to find a stack that works for your situation. I imagine I’ll find myself defaulting to Express more times than not, unless I’m in a situation where I need a standard API with basic CRUD capability quickly, in which case I’d prefer Django.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3e25b64bd91c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding Modules in Node.js]]></title>
            <link>https://smithspencer817.medium.com/understanding-modules-in-node-js-ecac051e0f4?source=rss-9cdda60a5b00------2</link>
            <guid isPermaLink="false">https://medium.com/p/ecac051e0f4</guid>
            <dc:creator><![CDATA[Spencer Smith]]></dc:creator>
            <pubDate>Sun, 06 Dec 2020 01:39:35 GMT</pubDate>
            <atom:updated>2020-12-06T01:39:35.757Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cUum8psNAvDEH2nGwzaKaA.png" /><figcaption>Example of a simple JavaScript Immediately Invoked Function Expression that logs “Hello World” to the console</figcaption></figure><p>I’ve encountered the term <strong>Immediately Invoked Function Expression (IIFE)</strong> a ton while preparing for my interviews. Initially it was very frustrating — every time I googled something like “Top 100 JavaScript Interview Questions” the topic would come up, but I could never find enough real-life implementations to understand the use cases.</p><p>For anyone who isn’t familiar with the term, an IIFE is just a way to create a module in JavaScript. To fully understand modules and why they’re useful, we first need to understand global scope and <strong>why it behaves differently in a file than it does in a browser</strong>.</p><h3><strong>Global Scope</strong></h3><blockquote><strong><em>IMPORTANT</em></strong></blockquote><blockquote><em>Before we start, it’s important to double-down on the distinction that global scope works differently in the </em><strong><em>browser</em></strong><em> than it does in a </em><strong><em>file with a .js extension</em></strong><em>. I’ll do my best to clarify the differences by labeling the example images with their respective environment</em></blockquote><h4>Similarities between global scope in the browser and in a file</h4><p>Every JavaScript program has a <strong>global object</strong> that contains useful properties and methods.</p><p>In the <strong>browser</strong>, this global object is referred to as the <strong>window</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*phsDdu8ZJtQiFNGrFXrxAw.png" /><figcaption>***BROWSER***</figcaption></figure><p>In a Node.js file, this global object is simply referred to as <strong>global.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pJR2aneInCSAh6k4OC21ig.png" /><figcaption>***FILE WITH .JS EXTENSION***</figcaption></figure><p>You use the global object all the time, frequently by accessing the <strong>.log</strong> method attached to the global object’s <strong>console</strong> property.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AqZd-_NxShcYOYE9eob9lA.png" /><figcaption>***BROWSER***</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FlLHdzC9s4UdyZe885ksTA.png" /><figcaption>***FILE WITH .JS EXTENSION***</figcaption></figure><p>Fortunately, methods and properties that belong to the global scope can be referenced directly. So while it’s possible to log something to the console with <strong>window.console.log</strong> in a browser or <strong>global.console.log</strong> in a Node.js file, we can just make a direct call to the console property.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ybpUkY3kUg4St__A3MDljQ.png" /><figcaption>***BROWSER***</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*davCjzAHEYHrczUqCPwdyA.png" /><figcaption>***FILE WITH .JS EXTENSION***</figcaption></figure><h4>Differences between global scope in the browser and in a file</h4><p>The best way to illustrate the difference in browser and file global object behavior is to simply create some variables and functions. We’ll use a constant <em>name variable</em> and a <em>sayName function</em> in both the browser and a .js file.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hwWwYQCBvyTb4YwOEVlOBw.png" /><figcaption>***BROWSER***</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ccyb7xyTuSPnEDTT0SMGvg.png" /><figcaption>***FILE WITH .JS EXTENSION***</figcaption></figure><p>In the <strong>browser</strong>, any variable or function that we declare gets added to the global <strong>window</strong> object. This can lead to some weird behavior.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*17vSCXLW_SjWt_Pd-3wfpQ.png" /><figcaption>***BROWSER***</figcaption></figure><p>A feature of Node files with the .js extension is that variables and functions we define in files are <strong>not attached to the global object</strong>. Instead, they are scoped locally to the file in which they were declared — meaning that files with the .js extension <em>are</em> <strong>modules</strong> themselves.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZW3EavbuRshsTHKG1mTMgQ.png" /><figcaption>***FILE WITH .JS EXTENSION***</figcaption></figure><p>The main benefit of .js files (and therefore modules) is that they allow us to <strong>encapsulate</strong> our code into private collections of variables and functions. The variables and functions defined within a file won’t pollute the global scope and can only be made available to other modules if we choose to expose them. <strong>The reason why this works is because all .js files that are run with Node.js are immediately wrapped with an IIFE at runtime, giving them their own local scope.</strong> We’ll explain this in more depth in the next section.</p><p>Alternatively in the browser, it’s easy to envision a scenario where we accidentally overwrite one of the window object’s built-in methods or properties, which could lead to a myriad of annoying side effects.</p><h3>Privatizing Data &amp; Methods</h3><p>The best way to illustrate how IIFEs work is to build one from the ground up. First, we create an<strong> anonymous function. </strong>This anonymous function can be in the form of a nameless function declaration…</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cc8Ed56ResMefa4LFCcslw.png" /></figure><p>… or if you prefer ES6 syntax, you can use an anonymous arrow function.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eqjucWqVM8oZF23xXPhrRQ.png" /></figure><p>Next, we wrap the anonymous function in a set of parentheses.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lybgnvTqWcQdOaf4nGYr1w.png" /></figure><p>What does wrapping our anonymous function in parentheses do? It converts our function into an <strong>expression</strong>.</p><p>What’s special about an expression? An expression in JavaScript is a unit of code that evaluates to a single value. In our case, wrapping our anonymous function in parentheses creates an expression that evaluates to a single<strong> function object</strong>.</p><p>Since our new parentheses create an expression that evaluates to a function, we simply need to invoke that function to complete our IIFE.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/977/1*vRzilYTAI-jNtOdLgxfGIA.png" /></figure><p>Our <strong>FUNCTION</strong> is wrapped with parentheses (making it an <strong>EXPRESSION</strong>) and is <strong>IMMEDIATELY INVOKED</strong> by the second pair of parentheses.</p><p>When we invoke an IIFE, what we’re really doing is we’re invoking the anonymous function <em>inside</em> the IIFE. Since the anonymous function has its own private function scope, we can add variables and functions to the IIFE without having to worry about them affecting other parts of the program.</p><p>Let’s give each of our IIFEs a variable.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ud6Y82gxERbegKlEW1gS2A.png" /></figure><p>One thing to notice is that we’ve defined the constant variable greeting twice, once per IIFE. Since each IIFE creates its own <strong>function scope</strong>, the greeting variable has different meanings depending on context.</p><p>We can play by the same rules with functions inside of an IIFE.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QQ9M4bs4O7Bjxv1g9AdmWw.png" /></figure><p>Since both IIFEs have two different function scopes, their respective <em>sayHello</em> functions are going to log different greeting values to the console.</p><p><strong>To help conceptualize things, you can think of each IIFE as being its own separate file</strong>. Just like the .js files we described before, they have their own local scope and can be given private functions and variables that will only be accessible by other IIFEs if we choose to expose them.</p><p>Therefore, the two IIFEs we’ve created in this <em>single</em> index.js file…</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*S_XZXv31AbXq9piambwhBg.png" /></figure><p>Is basically the same thing as having both IIFE’s in two separate files</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Bimjv4OyHd_Xh2XU81PAhA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0cl7GR8-rQKoWbiKzEGgKQ.png" /></figure><h3>Exposing Data and Methods</h3><p>To publicly expose functions and data that other IIFEs might find useful, we simply use a return statement to <strong>return an object </strong>containing the functions and data that we want to make public.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3M79b_MEovUSVnTj6YB65Q.png" /></figure><p>The connection we want to make is how similarly this behaves to <strong>module.exports</strong>, which you’ve probably seen many more times than IIFEs if you have any experience in Node or React.</p><p>Since IIFEs have modular functionality and files with .js extensions are actual modules themselves, let’s again split our code into two separate .js files.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VnF643Sdcr3-rM_m1q2Qsg.png" /></figure><p>Remember that earlier we said .js files are wrapped with an IIFE at runtime, so we would be nesting IIFEs inside of IIFEs with our current setup. Let’s get rid of the IIFEs…</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RtJ3uCbcLPuMDjF8il8NaQ.png" /></figure><p>… and replace with the return statements with <strong>module.exports</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*D2p1PvxTKyKIO_h3qOpPmA.png" /></figure><p>Let’s say that the first file (first.js) wants to borrow some functions that were defined in the second file. Let’s follow the flow of how that would work.</p><p>First, the module we’re importing from needs to have defined the function that we want to import.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/885/1*njDCrs5T582O9n4PR53ziw.png" /></figure><p>Secondly, we need to make sure that the function has been exposed by the module with module.exports</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/881/1*juusULVgvTlHtec0xjN3WA.png" /></figure><p>In the file where we want to import the functionality, we simply call the <em>require()</em> function on the file path that points to the file where the exports are.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0Y7J2C6Rgsxarw7s_Cz5Lw.png" /></figure><p>The require function finds the exports and assigns them to variables. In our case, we used ES6 destructuring to store the exports.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uWK1B0Xv0QV8FBnVNJjAgQ.png" /></figure><p>The first file now has access to the <strong>imported exports</strong> (??) from the second file and can evoke those imported functions as needed.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7xk5wh580rVqernKfwlSBQ.png" /></figure><p>Now that the first file has access to the exports from the second file, the first file can now use those functions just like the second file can.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sd291r-2LfVDgP4EPdeUow.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ecac051e0f4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Learning Strategies for your Software Engineering Job Search]]></title>
            <link>https://smithspencer817.medium.com/learning-strategies-for-your-software-engineering-job-search-193ca3d0626?source=rss-9cdda60a5b00------2</link>
            <guid isPermaLink="false">https://medium.com/p/193ca3d0626</guid>
            <dc:creator><![CDATA[Spencer Smith]]></dc:creator>
            <pubDate>Sat, 28 Nov 2020 23:50:46 GMT</pubDate>
            <atom:updated>2020-11-29T00:02:16.474Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*c4T-HXCo4qlNtggm5TunUA.png" /></figure><p>I’ve been obsessed (in a healthy way) with figuring out how to use my time in the most efficient way possible for as long as I can remember. Sometimes “work smarter not harder” is more easily said than done — there are a number of variables that can throw off your groove on any given day. Not to mention there comes a point where nothing substitutes reps and plain old hard work. That said, I still love having structures and systems that allow me to squeeze the most productivity out of my hours.</p><p>This article aims to answer one question:</p><blockquote>If I had a perfectly open week where all of my time was completely under my control, how should I choose to spend it to get the most out of my learning?</blockquote><p>While these kinds of days (much less weeks) can be few-and-far-between (see: non-existant) in a real working environment, it’s still useful to have some methods in your toolbox.</p><h3>Big Picture Strategies</h3><p>“Big Picture” ideas are more macro level — meaning, these ideas have to do with deciding…</p><ol><li>What you’ll choose to do across a span of multiple days</li><li>How to best divide your day up into “blocks” of time</li></ol><p>This is opposed to “Little Picture” — or micro level — where you’d focus more on how to structure learning <em>within</em> a specific block of time.</p><h4>Spaced Repetition</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QETKVWTJsGTiqHZ9Z8oNSw.png" /></figure><p>As you can see from the chart above, reviewing information is just as important as digesting the information in the first place. It’s much better to spend an hour or a couple of hours a day practicing a new skill than it is to spend every Saturday trying to pull off a learning marathon with a week of time in between.</p><p>The whole idea is based on the fact that the earlier you are in your learning process, the faster your newly-gained knowledge will naturally deteriorate over time. By following up on your learning with spaced repetition, you retain more information and you avoid wasting time re-teaching yourself things you should already know.</p><h4>53 Minutes On, 17 Minutes Off</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SYDQp8mKnTO6qsyjkH_jMg.jpeg" /></figure><p>Generally speaking, people are great at honing in on tasks for a little under an hour before they begin to lose focus. It’s very important to understand that when we say 53 on and 17 off, we <em>really </em>mean<strong> ON </strong>and <strong>OFF</strong>. If you’re working for 53 minutes and checking your social media every 10, you’re not <strong>ON</strong>. Alternatively, if you’re resting for 17 minutes but you decide to spend it checking your email, you’re not <strong>OFF </strong>(unless you genuinely find it fun or relaxing to check your email, I’m sure there’s someone out there).</p><p>What are things you can do during your break?</p><ol><li>Drink water (!!!)</li><li>Get away from screens</li><li>Go for a walk — outside if possible</li><li>Eat a low-carb snack (fruit is great)</li><li>Listen to music</li><li>Call a friend / family member</li></ol><h4>If you’re working on a lot of different things, aim to give about two hours of attention to each project daily</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yxz-2YvgDEGp2q_VX7_jVA.png" /></figure><p>Ability to retain information drops after two hours, then falls off a cliff after 4 hours.</p><p>Don’t get me wrong — a lot of the time you <em>have</em> to work on something for 4+ hours. You might not have a choice. Maybe you have a big interview tomorrow and you’re drilling Leetcode problems or you’ve got a major project deadline coming up.</p><p>That said, it’s good to be aware that your productivity on those projects is going to drop dramatically after just a few hours. If you have several things to work on and you have some flexibility in your schedule, you might be better off giving your full attention to one thing for two hours before moving on to the next thing.</p><h4>Plan to do harder things in the morning, easier things in the afternoon</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3K2HSIPUPwgno9inbM39Cw.jpeg" /></figure><p>Generally speaking, your brain reaches peak “alertness” around 10:00 a.m. This is the best time of the day to work on tasks that require intense concentration. Personally, I prioritize algorithms and data structures in the mornings and save more monotonous tasks — like job applications or physical exercise — for the afternoon. Most people naturally start winding down after lunch and hit a “slump” between 2:00–4:00 p.m.</p><h3>Little Picture</h3><p>As mentioned before, the “little picture” focuses more on the micro-level. If you’re following the 53/17 pattern described above, this is intended to help you plan your learning <em>within</em> any given 53-minute block.</p><h4>Master the Fundamentals First</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WGzJxb3UdEy58a4t8YcaDw.jpeg" /></figure><p>Advanced concepts in any domain are built on a foundation of strong fundamentals. For this post specifically, I’m going to focus on fundamentals for algorithms and data structures.</p><p>For algorithms, you won’t truly understand recursion until you understand functions, you won’t truly understand functions until you understand scope, you won’t truly understand scope until you understand variables, etc.</p><p>The way I see it, the fundamentals for algorithms can be broken down into three levels:</p><blockquote>Level 1</blockquote><ol><li>Primitive values (integers, strings, booleans, etc.)</li><li>Conditionals (if-else)</li><li>Control flow (while loops, for loops, etc.)</li><li>Functions and scope</li><li>Classes and instances</li></ol><blockquote>Level 2</blockquote><ol><li>Basic data structures (arrays, hashes, linked-lists, stacks, queues, sets, binary trees, graphs, etc.)</li><li>Sorting algorithms (insertion sort, bubble sort, selection sort, merge sort, quick sort, radix sort)</li></ol><blockquote>Level 3</blockquote><ol><li>Being able to perform Create, Read, Update, and Delete (CRUD) actions on <em>any</em> data structure from <em>any point</em> (beginning, end, middle) within that data structure</li><li>Understand the <strong>time and space complexity</strong> (Big-O) implications of performing any CRUD action on any given data structure</li></ol><p>Can you manipulate <strong>multiple pointers</strong> to <em>read</em> an array? Can you <em>delete</em> a <strong>node from any given spot on a tree</strong> and understand how to move the surrounding nodes in response?</p><p>Once you’re able to confidently answer questions like these, you’ll be able to consider the pros and cons of each data structure and the tradeoffs you’ll need to consider when deciding which structures to use.</p><h4>The 85% Rule</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*9wsXESicGX6HjyhMT6bfLw.jpeg" /></figure><p>When it comes to moving up “levels” in my understanding of fundamentals, I try my best to avoid moving on until I have a solid grasp of the previous level.</p><p>What qualifies as a “solid grasp” is going to vary from person to person, but my personal standard settles in around 85% mastery. If you insist on 100% mastery, you’ll be really great at the first couple of steps, but you will have taken forever to achieve that mastery and might be failing to see things from a broader perspective.</p><p>Do you have to understand everything about music theory before you even pick up an instrument? Do you have to know what goes into growing the perfect tomato before you make a pizza?</p><p>If you take 85% mastery and begin to put it into real, deliberate practice, the remaining 15% will probably close naturally. Following the 85% rule will prevent you from moving too quickly, but without sacrificing any of your momentum to do so.</p><h4>Blooms Taxonomy</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/890/1*CFwjbyxhZz73F3k_AYSyVw.png" /></figure><p>The chart explains itself, but Blooms Taxonomy is one of my favorite ways to gauge my understanding of a concept or subject. It begins with a foundation of simply recalling or remembering facts and builds its way up to creation.</p><p>If I’m not positive on “where I’m at” with my understanding of something, I’ll start from the bottom and ask myself questions as I move up tiers. One great way to check how well you know something is to try<strong> teaching</strong> it using simple terminology in such a way that someone with zero experience might have a shot at understanding you.</p><p>Personally, I’ve attempted multiple times to teach my girlfriend how Linked Lists work. When she understood, I understood.</p><h3>Putting it all together</h3><p>This is an example of how I might lay out a week with all of the above principles in mind. While you might look at the schedule and see that each day is “only” 8 hours of total work, I hope you’ll find that the balance of doing a little bit of everything daily (while also not neglecting your health) leads to more efficient hours, better retention, and sustainable success.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*t8iJvh4y4m5RhozKaltAoA.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=193ca3d0626" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Reversing a Linked List explained as a children’s story]]></title>
            <link>https://medium.com/swlh/reversing-a-linked-list-explained-as-a-childrens-story-c9b8d1681dd7?source=rss-9cdda60a5b00------2</link>
            <guid isPermaLink="false">https://medium.com/p/c9b8d1681dd7</guid>
            <category><![CDATA[algorithms]]></category>
            <category><![CDATA[linked-lists]]></category>
            <category><![CDATA[data-structures]]></category>
            <category><![CDATA[object-oriented]]></category>
            <dc:creator><![CDATA[Spencer Smith]]></dc:creator>
            <pubDate>Fri, 20 Nov 2020 22:06:56 GMT</pubDate>
            <atom:updated>2020-11-23T19:15:55.897Z</atom:updated>
            <content:encoded><![CDATA[<h3>Reversing a Linked List, but as a Children’s Story</h3><p>Once upon a time, there was a <strong>magic bridge</strong>…</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yCP7vyU_RJjNCTafApsrmw.png" /></figure><p>The magic bridge was made up of round, <strong>magic stepping stones</strong>, and each magic stepping stone had a <strong>magic rope</strong> connected to it that pointed in one direction. The magic bridge had two rules that you always had to follow if you wanted to travel across it:</p><ol><li>You can only walk along the magic rope in the direction that it is pointing</li><li>The magic bridge will continue on forever until one of the magic ropes points to an “end” sign.</li></ol><p>One day, two engineers were standing at the entrance to the magic bridge.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*i0N4Fixxw27R4dopQ-XW6Q.png" /></figure><p>The red engineer said to the blue engineer, “It’s sad that this bridge only goes in one direction. We’re always going from <em>here</em> to <em>there</em>, but what if the engineers over <em>there</em> want to come <em>here</em>?”</p><p>The engineers started thinking of ideas on how to reverse the direction of the bridge. Suddenly, the blue engineer realized a loophole in the bridge’s rules.</p><p>“I know we can only <em>walk</em> along the tightrope in one direction,” said the blue engineer, “but what if we could <em>jump</em> from stone to stone without having to step foot on the tightrope at all?”</p><p>“Brilliant!” exclaimed the red engineer. “But these stones are not very large and we could easily fall off the bridge if we’re not careful jumping. <strong>One of us should always be one stone ahead</strong> to <em>catch</em> the other when they try to jump.”</p><p>Excited to exploit the loophole and reverse the bridge, the blue engineer stood on the first stone while the red engineer stood at the entrance to the bridge.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*emRG_hFOlYU1N2DbGcA2kg.png" /></figure><p>“Hold on,” said the red engineer. “Remember the second rule of the bridge: It will continue on forever until the final stone points to an <strong>end</strong> sign. <strong>We need to put an end sign right here, because where I’m standing will eventually be the end</strong>.”</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*myKONWGsEuPW_x3BTsCwnw.png" /></figure><p>“Good thinking,” said the blue engineer. “Now I can take the rope on the first stone and have it point <em>back</em> to the end sign. Then you can jump over the rope and join me on the first stone!”</p><p>The blue engineer took the rope and pointed it towards the red engineer.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DEWs6Wt3_WNcV2HheERKXw.png" /></figure><p>Since the blue engineer was already at the first stone, the red engineer was able to jump over the first stone knowing that the blue engineer would be there to catch him.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YsN2uoC__3MMQrIjlQLo0Q.png" /></figure><p>“Well dang,” said the engineers — having realized their predicament.</p><p>Their strategy had worked well for first stone, but now they couldn’t get to the second stone. <strong>They couldn’t <em>walk</em> to the next stone because there was no magic rope, and they couldn’t <em>jump</em> to the second stone because there was nobody there to catch them.</strong></p><p>This was going to be harder than they thought. “We need a third engineer,” said the red engineer.</p><p>The engineers reset the bridge to its original state and sought out a third engineer to help them with their problem.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*V5T3f-1lkei2dxrBH9_Z_Q.png" /></figure><p>“I have an idea,” said the green engineer. “<strong>What if I go to the second stone before the blue engineer changes the direction of the magic rope on the first stone? </strong>That way when the blue engineer is done, he can jump over and join me on the next stone over!”</p><p>Following the magic rope, the green engineer walked to the second stone, the blue engineer walked to the first stone, and the red engineer stood at the end sign.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wH4FSPaSdhbnyuSjB74reQ.png" /></figure><p>First the blue engineer grabbed the rope at the first stone and pointed it back to the red engineer.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DXTbyKMdTpN1c0bH5_mlEw.png" /></figure><p>“Careful now,” said the green engineer. “If the blue engineer joins me at the second stone right now, the red engineer won’t have anyone to catch him when he jumps to the first stone.”</p><p>Heeding the green engineer’s advice, the red engineer jumped over the magic rope to the first stone where the blue engineer was already standing to catch him.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uinoKQ30IoTJKa1svf2R6g.png" /></figure><p>“Perfect,” said the green engineer. “Now the blue engineer can jump over here and join me! I’ll be here to catch him, so it’s not a problem that there isn’t a rope between us.”</p><p>Starting to see the pattern, the blue engineer jumped to the second stone with the green engineer.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1DDJOkSIJOVMpCWjdI4MRQ.png" /></figure><p>Knowing he needed to lead the way, the green engineer then <em>walked</em> across the magic rope to the third stone.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kcwMzJ_-JiwqFQskFReU4Q.png" /></figure><p>The pattern was now totally clear. The blue engineer pointed the rope at the second stone back towards the red engineer…</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LrvfQf-AKkwXUVpVS73lkw.png" /></figure><p>…then the red engineer<em> jumped</em> over to join the blue engineer…</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nTOBBeMDj9JTeIRJP6OnIw.png" /></figure><p>…then the blue engineer<em> jumped</em> over to join the green engineer…</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7USWdH8VFTrGoAevqwuG3A.png" /></figure><p>…and finally, the green engineer <em>walked</em> across the rope to the fourth stone.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gTX9lCO_voQj7LtICs4aNg.png" /></figure><p>Finding themselves in a groove, the engineers continued to follow their pattern.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*U_o-QjM1lRib4RYYYpAWhw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6sd9n3ZxzzF7wjC0usPi4A.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yPlLi_pSth4ntqqcMQylfg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*c8hSykC8NbUPMuP6HZ7wOw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3mAcQ1KddgDZfbdCXpF2LA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ebPTzt-jnHL-8Evq63iRKA.png" /></figure><p>Once the blue engineer finally got to the end sign, the team knew they had fully reversed the magic bridge and they lived happily ever after.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LUwOeQHptG8UnSDB-1coXQ.png" /></figure><h3>So how does it look in code?</h3><p>Reversing a linked list depends heavily on its order of operations. Using the characters and props above, let’s represent this story with some pseudocode.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BLR_2czShj5nWNYN_0X9MQ.png" /></figure><p>Brilliant! Everything here almost works perfectly well, we just have to do two things:</p><ol><li>Replace the “end signs” with <strong>null</strong> values</li><li>Replace the <em>.nextStoneOver</em> and <em>.magicRope</em> properties with <em>.next </em>values</li></ol><p>Once we’ve done that, the code above will look like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YpC8iGE8H_HAq6AbWnVuOw.png" /></figure><p>This code works perfectly well to reverse a linked list, but your prospective employer will probably have less of an adverse reaction if you name your variables something more descriptive than colors and change <strong>firstStone</strong> to <strong>head</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rWxe9tvyHjxahGjBs4G0_Q.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c9b8d1681dd7" width="1" height="1" alt=""><hr><p><a href="https://medium.com/swlh/reversing-a-linked-list-explained-as-a-childrens-story-c9b8d1681dd7">Reversing a Linked List explained as a children’s story</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[Understanding Inheritance in JavaScript Through Object Creation]]></title>
            <link>https://medium.com/swlh/understanding-inheritance-in-javascript-through-object-creation-df2f9e891a09?source=rss-9cdda60a5b00------2</link>
            <guid isPermaLink="false">https://medium.com/p/df2f9e891a09</guid>
            <category><![CDATA[constructor]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[prototypal-inheritance]]></category>
            <category><![CDATA[object-oriented]]></category>
            <category><![CDATA[classical-inheritance]]></category>
            <dc:creator><![CDATA[Spencer Smith]]></dc:creator>
            <pubDate>Sun, 15 Nov 2020 22:44:55 GMT</pubDate>
            <atom:updated>2022-09-19T18:19:32.129Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qfDKobfUHgHdglTlf1c37A.jpeg" /><figcaption>Src: <a href="https://www.latimes.com/sports/dodgers/story/2020-08-27/dodgers-mookie-betts-stand-against-racism-jackie-robinson-mlb">https://www.latimes.com/sports/dodgers/story/2020-08-27/dodgers-mookie-betts-stand-against-racism-jackie-robinson-mlb</a></figcaption></figure><p>When first learning programming, I was very pleased by what seemed to be the inherent objectivity of code. Everything appeared to be very black and white, cut and dry, yes or no. I totally understood that there were many different ways to approach any given problem, but ultimately either your unique approach worked or it didn’t — there was no in-between.</p><p>My first encounter with how subjective programming can be came when I started to <em>truly</em> learn about inheritance. I say ‘truly’ because I first learned about class constructors when I taught myself Python and my genuine impression at that point was “okay I got it, this is what all classes look like and this is how all inheritance works.” Class inheritance <em>was</em> inheritance to me. I had no idea that there were different <em>types</em> of inheritance or even different <em>implementations</em> of those types.</p><p>Eric Elliot has done a phenomenal job with his <a href="https://gist.github.com/Geoff-Ford/c985b67a1a27deadb970d828b6a90282">JavaScript interview series</a> here on Medium and his articles are largely responsible for seismically shifting the way I understand inheritance and objects. His explanation of when, how, and why we choose between <a href="https://medium.com/javascript-scene/master-the-javascript-interview-what-s-the-difference-between-class-prototypal-inheritance-e4cd0a7562e9">different implementations of inheritance</a> (or object composition over inheritance altogether) was the main motivation behind this article.</p><p>We’re going to examine five ways you can construct new object instances and discuss each approach’s advantages and disadvantages with regard to inheritance by considering the following questions:</p><ol><li>How is an instance created?</li><li>Which properties and methods does each instance have access to?</li><li>How does an instance gain access to new methods and properties?</li><li>How is this approach similar to or different from other approaches to object creation?</li><li>What are the general pros, cons, and use cases for this approach?</li></ol><blockquote>“Favor object composition over class inheritance.”<br>~ The Gang of Four, <a href="http://www.amazon.com/gp/product/0201633612?ie=UTF8&amp;camp=213733&amp;creative=393185&amp;creativeASIN=0201633612&amp;linkCode=shr&amp;tag=eejs-20&amp;linkId=WMUILDJNIUXY4NSH">“Design Patterns: Elements of Reusable Object Oriented Software”</a></blockquote><h3>Object Literals</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/984/1*AMqk-Jng5adD2Ja-T5sOIg.png" /></figure><h4>How is an Object literal instance created?</h4><p>Setting a variable to be an <strong>empty object</strong> is the same thing as calling <strong><em>new Object()</em></strong><em>.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ahP6LZaNrQESziRjDrPUCg.png" /></figure><p>Whenever we simply declare a new Object with open-and-closed curly braces, this is known as an Object literal.<em> </em>Object literals <em>implicitly</em> call on the constructor property <em>within</em> the <strong>Object prototype</strong> to create instances of Object literals.</p><p>All object constructors in JavaScript, including but not limited to the Object() constructor, call on a <strong>constructor property </strong>to <em>construct</em> instances.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nwEjv6aJQQPyMK7_8-9ZFg.png" /></figure><h4>Which properties and methods does each Object literal instance have access to?</h4><p>While the athlete Object here might not have any immediately visible properties or methods, it does come with one built in.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*40q7nr-cvbWGCcvg8Kb-EA.png" /></figure><p>This<strong> __proto__</strong> property, short for <strong>prototype</strong>, is attached to any <em>instance</em> of an Object and points to the prototype of the object constructor that was used to create that instance.</p><p>In JavaScript, all objects inherit properties and methods from a <strong>prototype </strong>that uses its<em> </em><strong>constructor property</strong> to construct new instances of that Object.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/875/1*N-QuePiJKmAOUI0FbcLI5A.png" /></figure><p>Since Object literals are essentially the same thing as calling the new Object() constructor function, Object literals inherit all methods and properties associated with the Object prototype such as <em>toString</em> and <em>hasOwnProperty.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*J7r0jj0-cVVL1NDZILfmYA.png" /></figure><h4>How does an Object literal instance gain access to new methods and properties?</h4><p>Instances of Object literals are easy to extend. You can give them new properties and methods by simply attaching them to the new <em>instance</em>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dL0Eabikl-zFY69OKrzeUg.png" /></figure><p>Whenever we extend <em>instances</em>, those new properties and methods belong to <em>that </em>individual instance — meaning <em>other</em> instances do <strong>not</strong> have access to these new properties and methods.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sqx9LG4Y4m5g6ZbjZDzcgA.png" /></figure><p>Since Object literals inherit from the Object prototype, we would need to extend the Object prototype to allow <em>all instances</em> of Objects to share custom properties.</p><p>While this <em>technically</em> works, it’s very uncommon and leads to some weird behavior.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*d1mi1cCr6GQpQdMWv0vHgg.png" /></figure><p>Since data structures like arrays are Objects by in JavaScript, adjusting the Object prototype allows all objects in the entire program to inherit whatever functionality is added to it. Messing with built-in datatype constructors like Object(), String(), and Number() is known as <strong>monkey patching</strong> and it’s much worse in practice than it is in theory.</p><h4>How is using Object literals similar to or different from other approaches to object creation?</h4><p>Since <strong>factory functions</strong> are basically just functions that return Object literals, you can think of a factory function as a machine that uses arguments to more easily generate customized Object literals.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0BZwbvCPHdpn-AtazGdvGQ.png" /></figure><p>Any<em> instances</em> created from the factory function will behave similarly to Object literals and instances of <em>new Object()</em>;</p><p>Standalone Object literals can be more individual and specific than when Objects literals are<strong> used as prototypes</strong>. In our above examples, we gave most of the Object literals a name property of “Mookie.” Since not all athletes are named Mookie, those Object literals would <em>not</em> be good candidates to serve as a prototype. Objects <strong>used as prototypes</strong> need to be able to describe<em> all </em>instances of that object.</p><p>The way we approach inheritance with Object literals is most dissimilar to <strong>object constructor functions</strong> and <strong>class constructors</strong>. Instances of Object literals are only one step down the <strong>prototype chain</strong> from the Object prototype, but the other two are at least two steps down. Object literals are better for <strong>object composition</strong> whereas the other two more closely resemble <strong>classical inheritance</strong> patterns.</p><h4>What are the general pros, cons, and use cases for Object literals?</h4><p>Pros: Very simple structure with only one level of inheritance that is easy to understand syntacticly and conceptually. Great for object composition.</p><p>Cons: The only way to provide methods and properties to <em>all </em>instances of Object literals is to <em>monkey patch</em> the Object prototype, which gets messy in a hurry. Since we have to individually define the properties for <em>every</em> new Object literal, declaring a bunch of them all over the place would take forever.</p><p>Use cases: Object literals are best used as prototypes for other objects, so they are better for when you are intentionally trying to favor object composition (with Object.assign and Object.create) over class inheritance.</p><h3>Factory Functions</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vnChLfqkiQsAY4f0poZOsg.png" /></figure><h4>How is a factory function instance created?</h4><p><strong>Factory functions</strong> can be thought of as machines that generate Object literals. The main takeaway from this is that instances generated by factory functions will behave <em>identically</em> to the Object literals we discussed in the previous section.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EME6vx6a8IbqmpKHM66ttA.png" /></figure><p>Both objects have three attributes (name, age, team), one method (run), and a <strong>__proto__</strong> property which points to the <strong>Object.prototype</strong>. The Object.prototype contains a constructor which is used to construct new Object instances.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xah4HOGzRGL2S7pI4-CeiQ.png" /></figure><h4>Which properties and methods does each factory function instance have access to?</h4><p>Objects produced by factory functions have access to the <strong>arguments</strong> passed into the <strong>function parameters</strong> as <strong>properties</strong>.</p><p>Note the differences between the <em>mookie</em> instance created by the <strong>factory function </strong>below and the empty <em>bryce</em> instance.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aEzEZUcLsHR2dYKYTK7SCg.png" /></figure><h4>How does a factory function instance gain access to new methods and properties?</h4><p>If each <em>instance</em> created by a factory function is basically an Object literal, and Object literals are created with the constructor belonging to the Object.prototype, this means that factory function instances inherit from the Object.prototype.</p><p>We would need to again monkey patch the Object.prototype to create any new methods or properties that could be shared by<em> all </em>factory function <em>instances.</em></p><p>Since these factory function instances behave identically to Object literals, property and method extension is easy.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*k3cVcJHXGNrSOA9WbworqA.png" /></figure><h4>How is using factory functions similar to or different from other approaches to object creation?</h4><p>Although factory functions look different from Object literals, their <em>instances</em> behave identically since they were <em>both</em> built by the <strong>Object.prototype constructor</strong>. Instances of both are also great candidates to use when intentionally trying to <em>favor object composition over inheritance</em> since the need to manipulate the Object.prototype makes <strong>prototypal inheritance</strong> tricky.</p><h4>What are the general pros, cons, and use cases for factory functions?</h4><p>Pros: It’s basically a machine that churns out Object literals with customized properties, which is much faster than individually declaring a ton of Object literals.</p><p>Cons: Since<strong><em> </em></strong><em>instances</em> generated by <strong>factory functions</strong> come packaged with specific, customized properties (such as “name”, “age”, and “team”), they would <em>not</em> be good candidates for <strong>use as prototypes</strong>.</p><p>Use cases: Great for <em>favoring object composition over inheritance</em> with <strong>Object.assign</strong>. Take the example below, where we use the assign method to easily <strong>compose</strong> a new object by <em>combining</em> two different objects.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zok65QWcmZBTKen17erijA.png" /></figure><h3>Object Literals as Prototypes</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HocNv0zRf5tlU5eRj3Jq6A.png" /></figure><h4>How is an instance created by using an Object literal as a prototype?</h4><p>The X-factor of this approach to object creation is the use of the <strong>Object.create </strong>method.</p><p>Before we move on, it is <em>crucial</em> to understand the difference between the way we’ve created objects so far and the way Object.create creates objects.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*45iF_tsOe7aAuFsbFnHyKQ.png" /></figure><p>For the <em>mookie</em> instance, Object.create takes in the <em>athlete</em> Object literal as an argument. Object <strong>arguments</strong> passed into Object.create are <strong><em>used as the prototype for instances</em></strong> instantiated with Object.create.</p><p>Alternatively, the <em>bryce</em> instance above calls on the Object function constructor to create a new Object instance with the properties described in <em>athlete </em>copied over as attributes.</p><p>Let’s see what these results look like under the hood.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DCnvWJNVvYumAHGJNSkYYw.png" /></figure><h4>Which properties and methods does each instance have access to?</h4><p>Hopefully you noticed that in the example above that the <em>bryce</em> instance now <strong><em>has </em></strong>the properties and methods described in the <em>athlete</em> object but the <em>mookie</em> object does not. What gives?</p><p>Even though the <em>mookie</em> instance only has a <strong>__proto__</strong> property, it can still access the <em>athlete</em> properties and methods just like <em>bryce</em> can. Let’s add a “name” property to the <em>mookie</em> object so the run method doesn’t log undefined.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-tLX6K-9akA7zdj99T07gA.png" /></figure><p>This is a great opportunity to reinforce our understanding of the <strong>prototype chain</strong>. Remember that when you call a method on any object, such as <em>mookie.run()</em>, that object looks at all of its properties and methods and tries to find a method by the same name.</p><p>If the object can’t find the method within itself, it then looks to its <strong>prototype</strong>. What is in mookie’s <strong>__proto__</strong> property?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*viPjoGcLZnHjINrc-5q4YQ.png" /></figure><p>The mookie instance’s <strong>__proto__</strong> property has all of the properties and methods that belonged to our original athlete Object because mookie’s prototype <strong><em>is</em></strong> the athlete Object. This is why the mookie instance can call the .run() method even though the method is a property of the athlete object, which is assigned to be the <em>mookie’s</em> prototype by <strong>Object.create</strong>.</p><p>Why is mookie’s prototype the athlete Object and not the Object.prototype? Because that’s how Object.create works.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OVx7MgA8KIlEadr7_67g0A.png" /></figure><p>Up until this point, the prototype for all of our Object literals has been the <strong>Object.prototype</strong>. With Object.create, we can reference customized objects to be used as prototypes for future instances.</p><h4>How does an instance gain access to new methods and properties?</h4><p>Just like in the previous examples where we used different approaches to create objects, individual instances of objects are very easy to extend in a way that doesn’t affect other instances.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*E1eVb1SrI5ZlvkxuPl4oQA.png" /></figure><p>But what if we want to give new properties and instances to <em>all</em> athlete instances generated with <strong>Object.create</strong>? Since the athlete object itself serves as the <strong>prototype</strong> for new instances, giving all <em>athlete</em> instances<strong><em> </em></strong>new methods and properties is as simple as extending the <em>athlete</em> object itself.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5DPGuO9yzPZHuYrvYWHMzw.png" /></figure><p>Continue to be aware of where instances access their properties and methods from. The<em> bryce</em> and <em>mookie</em> instances <em>don’t directly own</em> the new .<em>signAutograph</em> method, but their<em> prototype</em> does.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KYaeGngmVgb1eTMc2f2Uqg.png" /></figure><h4>How is using an Object literal as a prototype similar to or different from other approaches to object creation?</h4><p><strong>Prototypal inheritance</strong> with this approach is <em>way</em> cleaner than it was when we had to mess with the Object.prototype with<strong> Object literals </strong>and <strong>factory functions</strong>. We can easily extend the custom <em>athlete </em>object that we’re using as our prototype and it will only affect athlete instances that were instantiated with Object.create.</p><h4>What are the general pros, cons, and use cases for Object literals as prototypes?</h4><p>Pros: This approach works brilliantly for object composition with Object.assign. A standalone object that is combined with another object by using Object.assign is known as a<strong> mix-in</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mPCzIoirrxfqdo7FFnyxBA.png" /></figure><p>Cons: The problem we encounter with the code above is that we can only extend the prototype (clearly defined as the <em>athlete</em> object in Object.create) and expect instances to inherit the extended behavior. Since the baseballPlayer object is a<strong> mix-in</strong> and <em>not</em> the <strong>prototype</strong> of the baseballMookie instance, changing the <strong>mix-in</strong> won’t result in accessible behavior by the prototype.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DBj8QiIM6urqNsKo2rwvQQ.png" /></figure><p>Use cases: This approach works very well with <strong>concatenative inheritance</strong> patterns such as Object.assign in <em>addition</em> to <strong>prototypal inheritance</strong>, meaning its <em>very</em> flexible and useful in a lot of circumstances.</p><h3>Object Constructor Functions</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/981/1*_kzVFrzt65HEYTehw6Hktg.png" /></figure><h4>How is an object constructor function instance created?</h4><p>This is our first encounter with JavaScript’s <strong>new </strong>keyword and it’s very important to understand how it works. I borrowed this efficient description from StackOverflow:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aQ8xgLaHJZbVn8s6nhGZZg.png" /><figcaption><a href="https://stackoverflow.com/questions/1646698/what-is-the-new-keyword-in-javascript#:~:text=Summary%3A,object%20from%20a%20constructor%20function.&amp;text=Sets%20the%20prototype%20of%20this,Returns%20the%20newly%20created%20object">https://stackoverflow.com/questions/1646698/what-is-the-new-keyword-in-javascript#:~:text=Summary%3A,object%20from%20a%20constructor%20function.&amp;text=Sets%20the%20prototype%20of%20this,Returns%20the%20newly%20created%20object</a></figcaption></figure><p>We can use the <strong>Athlete constructor function</strong> to bind the properties and methods defined within it to the object created by the <strong>new</strong> keyword before saving that new object in a variable.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NaSvnzf8RylMvbT8GaqIwg.png" /></figure><h4>Which properties and methods does each object constructor function instance have access to?</h4><p>Notice how the properties passed in as arguments to the constructor function wind up belonging to the <strong>instance</strong> and <em>not</em> the <strong><em>Athlete</em> constructor function prototype</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AL_D2pb-7n4Lm-pCfliuGg.png" /></figure><p>We can verify that these properties belong to the instance itself and <em>not </em>the prototype by using <em>.hasOwnProperty</em> method.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TolOKu-HwZFQdjPDl_K-NQ.png" /></figure><p>But where did the <em>.hasOwnProperty</em> method come from? The <strong>prototype chain</strong>, of course.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jKb51KH26XBDjg2eMLBlgg.png" /></figure><p>An Athlete <em>instance</em> inherits from the prototype of the<em> Athlete</em> function constructor…</p><p>…which inherits from the <strong>Object.prototype</strong></p><p>..which contains methods and properties that belong to <em>all</em> objects in JavaScript.</p><h4>How does an object constructor function instance gain access to new methods and properties?</h4><p>If we want all <em>Athlete</em> instances to inherit new behavior, we will need to adjust the <strong><em>Athlete</em> constructor function’s prototype</strong> so that instances can inherit that functionality through the prototype chain.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8iZFAZ59WqInUJh-_5O9EA.png" /></figure><p>The <em>mookie</em> instance now has access the <em>.jump</em> method that was added to the <em>Athlete</em> constructor function’s prototype through the prototype chain.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UqogJyzFvpEvRIt1Y0X0DQ.png" /></figure><h4>How is using an object constructor function similar or different from other approaches to object creation?</h4><p>This method most closely resembles a typical constructor that we would use for <strong>class inheritance</strong>. Instances can be used along with other objects for <strong>object composition</strong>, but the structure more closely resembles<strong> prototypal inheritance </strong>patterns.</p><p>Instances that use this pattern are <em>two levels down</em> from the <strong>Object.prototype</strong> in the <strong>prototype chain</strong>. This is different from <strong>Object literals</strong> and instances created by <strong>factory functions</strong>, which inherit from the <strong>Object.prototype</strong> as opposed to inheriting from prototypes that we defined ourselves.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AFE0fWs3MRSY8IJTjlmjAg.png" /></figure><p>If we compare the <em>mookie</em> Object literal instance and the <em>tatis</em> <em>Athlete</em> instance, we can see that the the <em>tatis Athlete</em> instance is one step further down the prototype chain than the <em>mookie</em> Object literal instance.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0bTI1HUQOfYb5o11vTcipA.png" /></figure><h4>What are the general pros, cons, and use cases for an object constructor function?</h4><p>Pros: Easily allows us to create many instances of a custom object “type” — in our example case, instances of <em>Athletes</em>. Both instances and prototypes are easily extendable, and having the Athlete.prototype as a bridge to the Object.prototype allows us to use <strong>prototypal inheritance</strong> without needing to mess with the Object.prototype.</p><p>Cons: IMPORTANT: You <em>cannot</em> afford to forget the <strong>new</strong> keyword when creating new instances. If you forget the <strong>new</strong> keyword, the <strong>this</strong> keyword will bind itself to the <strong>global ‘this’</strong> (which in a browser would be the <strong>window</strong> object). That’s gonna get weird in a hurry.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Lxo7hLLOglPcGC9DUL2pgA.png" /></figure><h3>Class Constructors</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/994/1*GTYcbPfae9Vx3lE2HOQGPQ.png" /></figure><h4>How is a class instance created?</h4><p>Classes use the <strong>new</strong> keyword alongside class constructors to create new instances. The syntax is identical to the approach when we use <strong>object constructor functions</strong>. Every class has a<strong> </strong>constructor that defines properties<strong> </strong>which will belong <em>directly</em> to new instances, but methods defined <em>outside</em> of the <strong>constructor </strong>scope will belong to the <strong>Class.prototype</strong>, <em>not</em> the instance itself.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2lxDUNpDRAOCBMXZYcACww.png" /></figure><h4>Which properties and methods does each class instance have access to?</h4><p>Instances<strong><em> </em></strong>of classes can access any method or property that belongs to itself or whichever prototype was referenced to construct the instance.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*H4RLvsxKokKv8VFFcV74Ow.png" /></figure><h4>How does a class instance gain access to new methods and properties?</h4><p>Class instances are easily extendable just like with other approaches to object creation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aSuTC0m1dwlMAEzhSqvGsA.png" /></figure><p>Class<strong> </strong>prototypes are also easily extended, which allow instances to take advantage of any new properties and methods that are added later.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_77Jxr0R6zRLwBvjRkigdw.png" /></figure><h4>How are class constructors similar to or different from other approaches to object creation?</h4><p>Classes in JavaScript still use <strong>prototypal inheritance</strong>, but they are designed to <em>look </em>like they use <strong>classical inheritance</strong>. That’s not confusing, right?</p><p>Class syntax in JavaScript was conceived to help prevent confusion for developers that previously worked with <strong>Object-Oriented programming languages</strong> like Java and C++, but under the hood, it’s still<strong> prototypal inheritance</strong> because every class has a prototype that instances inherit from.</p><p>Class constructors work <em>very </em>similarly to <strong>object function constructors </strong>because the constructor function in a class <strong><em>is</em></strong> an object function constructor. The difference between <strong>classes</strong> and <strong>object function constructors</strong> is that object function constructors add to their prototype <em>after </em>definition…</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tF5e72S_f8sdDbA489eD-A.png" /></figure><p>…whereas classes can define methods that belong to the <strong>class prototype</strong> <em>within</em> the class definition itself.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PqGdfiVA9zIrfZ8rqox_Dw.png" /></figure><p><strong>Class constructors</strong> also allow us to create hierarchies and taxonomies with <strong>sub-classes </strong>or <strong>child classes</strong>. We can<strong><em> </em></strong>extend the <em>Athlete</em> class into a <em>BaseballPlayer</em> child class<strong> </strong>to give our <em>tatis</em> instance more baseball-specific properties and methods in <em>addition</em> to the properties and methods it inherits from the <em>Athlete</em> parent class.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UezB6-jNprrjrnw7GRFO2w.png" /></figure><p>Notice how the <em>tatis</em> instance, which was constructed by the BaseballPlayer <strong>child class</strong>, has access to all of the methods and properties defined in both <em>BaseballPlayer and Athlete</em> <strong>parent class</strong>. The <em>mookie</em> instance, constructed by the <em>Athlete</em><strong> </strong>parent class, does <em>not</em> have access to the properties defined within the <em>BaseballPlayer</em> child class<strong>.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3XuGnAg-rcCgvvxPmfRcLA.png" /></figure><p><strong>What are the general pros, cons, and use cases for this approach?</strong></p><p>Pros: Closely resembles class syntax in other programming languages which can help programmers new to JavaScript. While this is all <strong>prototypal inheritance</strong> under the hood, it <em>emulates</em> <strong>classical inheritance</strong>.</p><p>Cons: Classes create rigid taxonomies and hierarchies that can make programs less flexible over time. Class syntax in JavaScript also enables programmers to pretend that they’re using classical inheritance, which in and of itself is a problem.</p><p>Use cases: Almost none. Class syntax should seldom <em>ever</em> be used in JavaScript unless you’re deliberately trying to follow specific <strong>Object-Oriented Programming</strong> principles. One of the best features of JavaScript is how easily it allows you to extend and compose objects without needing to limit them to a class definition, so using classes to define objects fails to take advantage of this feature.</p><p>For a more in-depth explanation as to why you should avoid using class syntax in JavaScript, read <a href="https://medium.com/javascript-scene/master-the-javascript-interview-what-s-the-difference-between-class-prototypal-inheritance-e4cd0a7562e9">this article</a> by Eric Elliott.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*smOYxtQSOeCVB59oqRCtUQ.jpeg" /><figcaption>Src: <a href="https://bleacherreport.com/articles/2902275-mlbs-unwritten-rules-have-met-a-consensus-let-fernando-tatis-jr-be-great">https://bleacherreport.com/articles/2902275-mlbs-unwritten-rules-have-met-a-consensus-let-fernando-tatis-jr-be-great</a></figcaption></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=df2f9e891a09" width="1" height="1" alt=""><hr><p><a href="https://medium.com/swlh/understanding-inheritance-in-javascript-through-object-creation-df2f9e891a09">Understanding Inheritance in JavaScript Through Object Creation</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[Where do string methods come from?]]></title>
            <link>https://smithspencer817.medium.com/where-do-string-methods-come-from-83eab792dd20?source=rss-9cdda60a5b00------2</link>
            <guid isPermaLink="false">https://medium.com/p/83eab792dd20</guid>
            <dc:creator><![CDATA[Spencer Smith]]></dc:creator>
            <pubDate>Sat, 07 Nov 2020 23:57:14 GMT</pubDate>
            <atom:updated>2020-11-20T22:22:34.320Z</atom:updated>
            <content:encoded><![CDATA[<h3>The “Talk”: Where do string methods come from?</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nedsZdHeVksJ-IHG4_MURg.jpeg" /></figure><h3>Let’s talk data</h3><p>In JavaScript, there are seven “primitive” data types…</p><p><strong>String, Number, Boolean, BigInt, Symbol, undefined, </strong>and <strong>null</strong></p><p>… and two “structural” types…</p><p><strong>Object </strong>and <strong>Function</strong></p><p>As you probably already know, each data type has some inherent functionality. For example, a string can tell us how long it is if we simply ask it about its “length” <strong><em>property</em></strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/547/1*GmXSbzMsFDoVYgp4wu816g.png" /></figure><p>An array can describe its own length, too!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/487/1*aHOjujp5qA4hEd7ncNmnsg.png" /></figure><p>Arrays even come with their own built-in <strong><em>methods</em></strong> that we can access such as map, sort, and reduce</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/580/1*CuYe2cYxZvaKGR3cJ_KhDg.png" /></figure><p>It’s not like we ever <em>told</em> the string or the array what its length is — they already knew those things. Same thing with the map method — we never exactly <em>taught</em> the array how to use it.</p><p>If we didn’t write this functionality ourselves, it must have come from somewhere else. Answering the question of <em>what</em> and <em>where</em> that “somewhere else” is will be the main objective of this article.</p><h3>Inventing our own data type</h3><p>To show how this works, we’re going to <em>pretend</em> to invent a brand new data type. I like football, so let’s make a fake <strong>FootballPlayer</strong> data type and define it using a function</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/664/1*AFHKZqfMeRJP_xc4emKgrA.png" /></figure><p>In the above example, <strong>FootballPlayer </strong>is our fake data type and<strong> peyton </strong>is an <em>instance</em> of <strong>FootballPlayer.</strong> Since our <strong>FootballPlayer </strong>datatype definition is just an empty function with no functionality or properties, <strong>peyton</strong> can’t tell us much right now.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/383/1*7xCh6JQduSuonAXwPYsxRg.png" /></figure><p>Since <strong>peyton</strong> here is just an <em>instance</em> of a FootballPlayer object and objects in JavaScript are <em>extendable</em>, it’s not hard to provide <strong>peyton</strong> with the properties we want.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/563/1*q3SPclqZGkT3hilenLWh7w.png" /></figure><p>But this<em> only </em>gives the<strong> peyton</strong> <strong><em>instance</em></strong> a career property, not the FootballPlayer constructor. It would be very annoying if we had to manually define the career property of each <strong>FootballPlayer instance</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WJl3QI8Jiw9ytc8SO0SJtQ.png" /></figure><p>To fix this, let’s re-define our <strong>FootballPlayer</strong> constructor to give every <strong>instance</strong> of <strong>FootballPlayer</strong> a .<em>career</em> attribute set to “football.” Let’s also give each instance of <strong>FootballPlayer </strong>the ability to score touchdowns with a <em>.scoreTouchdown</em> method.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9Jqb2dBV_X8v6DJgw9r-eA.png" /></figure><p>Whenever we create new <strong>FootballPlayer</strong> <strong>instances</strong>, they’ll now have access to the <em>.career </em>property and <em>.scoreTouchdown</em> method.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jq6Eyd6ulkIHx2kf8_BqCw.png" /></figure><p>What if we want to add even more properties and methods? While we could <em>again</em> redefine our <strong>FootballPlayer</strong> constructor with a <em>.salary </em>property and a <em>.getPaid</em> method…</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6VUI9yAnhQazJHiyd4bDoQ.png" /></figure><p>We’re going to handle it a different way. Introducing prototypes.</p><p>Let’s go back to our simple FootballPlayer constructor and create another <strong>peyton instance </strong>with no properties or methods:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gqDOVhfZxEQ432kAFORT9w.png" /></figure><p>Whenever a new object is created in JavaScript, the new object <strong>inherits</strong> properties and methods from a<strong> prototype</strong>. By accessing the <em>.prototype</em> property of the <strong>FootballPlayer</strong> object constructor, we can add new methods and properties that our instances will inherit.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7l_Z8Bd8JrwDHKfknao8-A.png" /></figure><h3>Piecing things together</h3><p>The reason we walked through the above example is to demonstrate the following. This code below…</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Jl0fa1yeYBEiCW_qZ9kMGg.png" /></figure><p>… is basically the same thing as this code…</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/885/1*I3hA-vDC_JrRfk1OCK7pEw.png" /></figure><p>When we created our <strong>FootballPlayer</strong> constructor and created new<strong> instances</strong>, the instances inherited whatever methods we had built into the <strong>FootballPlayer</strong> constructor prototype.</p><p>The exact same thing happens when we create new strings — we just don’t have to declare <strong>new String()</strong> to make it happen. JavaScript calls that behind the scenes for us.</p><p>Just like our <strong>FootballPlayer</strong> instances inherited the .throwDeep property we added to the FootballPlayer prototype, our<strong> String</strong> instances inherit from the <strong>String</strong> prototype. What methods and properties are inside the String prototype??</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/480/1*PC-VVImRSGcoRqGA7DSj-w.gif" /></figure><p>Arrays? Same story</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/480/1*bQT4cHdzBz9BreLqxdiMCw.gif" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=83eab792dd20" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Annotated Algorithms: Bubble Sort, Insertion Sort, and Selection Sort]]></title>
            <link>https://smithspencer817.medium.com/annotated-algorithms-bubble-sort-insertion-sort-and-selection-sort-d9df71eb6609?source=rss-9cdda60a5b00------2</link>
            <guid isPermaLink="false">https://medium.com/p/d9df71eb6609</guid>
            <dc:creator><![CDATA[Spencer Smith]]></dc:creator>
            <pubDate>Wed, 28 Oct 2020 21:29:51 GMT</pubDate>
            <atom:updated>2020-11-05T03:04:31.122Z</atom:updated>
            <content:encoded><![CDATA[<p>We’ll be doing a step-by-step breakdown of three famous sorting algorithms. While they aren’t the most optimal sorting algorithms regarding time complexity, understanding how they work can help tremendously with mastering common problem-solving techniques such as <em>sliding-windows</em> and <em>multiple pointers</em>.</p><p>Before go into each specific algorithm, let’s first go over the two things that all three of them will share in common.</p><h3>Commonality one: Sorting an array in place</h3><p>Take a look at the <strong>reverseArray</strong> function below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/929/1*9LanMK1HvvcyeYmJWMb_Mw.png" /></figure><p>This function takes in an <strong>array</strong> as an argument, initializes an empty <strong>newArray</strong> and iterates backwards over the argument <strong>array</strong> by using a <em>for</em> loop. As it iterates, the function looks at each number in the argument array, <strong><em>push</em></strong>es it into the <strong>newArray</strong>, and then <strong><em>returns</em></strong> the <strong>newArray</strong> as a result.</p><p>While this is a valid way to reverse an array, its space complexity is not great since we need to allocate <em>additional memory</em> in order to store the <strong>newArray</strong>.</p><p>What if instead of creating a <strong>newArray </strong>to store the reversed order of our numbers, we could just <strong><em>swap</em></strong> the numbers two at a time like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/605/1*pdoOiO0nxrRrXkdH2NvnAQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/590/1*zAtQkChSlJz4_J5Xz6f20w.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/787/1*W8aQtYVtRrrqwEkB0rxOeg.png" /></figure><p>By <strong><em>swapping</em></strong> the numbers in the array <strong><em>in place</em></strong>, meaning <em>without creating an additional array</em>, we improve our space complexity.</p><h3>Commonality two: The “swap” helper function</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/961/1*NMIbTU6yId2ZnG5SayPnBQ.png" /></figure><p>Now that we understand the <em>need</em> for a swap function, we can discuss the two purposes it intends to serve: it helps us <strong><em>separate our concerns</em> </strong>by abstracting away the swapping functionality and also allows us to sort our arrays <strong><em>in place</em></strong>. The function takes in <strong>two indices</strong> and an <strong>array </strong>as arguments, then uses the <strong>indices</strong> to grab two different elements and <strong><em>swap</em></strong> their places within the array.</p><p>Both of the above functions work, but the bottom one works more optimally since the swapping is done… <em>*inhales*</em> … say it with me now… <strong><em>in place</em></strong>.</p><h3>Bubble Sort</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/480/1*Z42NRhEWLpd3cedWYG3NBQ.gif" /><figcaption>Source: <a href="https://algorithm-visualizer.org/brute-force/bubble-sort">https://algorithm-visualizer.org/brute-force/bubble-sort</a></figcaption></figure><p>Bubble Sort, while being a pretty slow sorting algorithm, is pretty simple to understand and is a perfect way to introduce the <strong>swap function</strong> in practice.</p><p>We start with a <em>for </em>loop, iterating over every number in our <strong>array</strong>. We know we’ll eventually be <strong><em>returning</em></strong> the <strong>array</strong> after it has been sorted, so let’s add the array to our <strong><em>return</em></strong> statement.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/747/1*vM0N2TYG3ofzeW9MgBdOqA.png" /></figure><p>Next, we have to emulate the <em>bubble</em> in Bubble Sort. This <em>bubble</em> is just a small slice of the array that looks at <strong>two adjacent numbers</strong>: the number at index <strong><em>i</em></strong> and the number at index<strong><em> i + 1</em></strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xNSCwwk0Phdm8LEjzPbqWw.png" /></figure><p>While we can sort an <strong>array</strong> in a variety of ways, most of the time the default is sorting an array in <em>ascending</em> order; meaning that larger numbers will go on the right and smaller numbers will go on the left.</p><p>We only ask ourselves one question within each bubble: is the number on the left ( index<em> </em><strong><em>i</em></strong> ) <strong><em>greater</em></strong> than<strong><em> </em></strong>the number on the right ( index <strong><em>i + 1</em></strong> )?</p><p>If the number on the right is smaller, we swap the two numbers in place.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oI4p_fzXTutE-Nh6Fe3lVw.png" /></figure><p>Otherwise, the bubble continues to slide to the right and compare more numbers</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/480/1*pbF4kyaOLPmN4gmdMRozkg.gif" /><figcaption>Source: <a href="https://algorithm-visualizer.org/brute-force/bubble-sort">https://algorithm-visualizer.org/brute-force/bubble-sort</a></figcaption></figure><p>Now that we can wrap our minds around the bubble idea, how can we represent this bubble comparison in code? First, remember we need to check if the number at<strong><em> </em></strong>index<em> </em><strong><em>i </em></strong>is <strong><em>greater than</em></strong> the number at index <strong><em>i + 1</em></strong>. If this conditional is true, we will want to swap the two numbers.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/879/1*ic3tBYT3CDZ_9AZ4sBdfdA.png" /></figure><p>How do we swap the two numbers? Let’s borrow from the <strong><em>swap function</em></strong> that we built earlier. The <strong><em>swap function</em></strong> takes in the two indices and the array itself as arguments and uses the indices to define the swap.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/924/1*p7CwbyNA1WhrRoCzPLaHPw.png" /></figure><p>This makes up the main bulk of our logic, but there are some edge-case questions we have to address.</p><p>As it stands now, nothing is stopping our algorithm from going all the way to the very last number and then comparing the last number to a blank space on the right of the array.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/779/1*wRX1wr8w5Ncus10p6hL1zA.png" /></figure><p>To fix this problem, we tell the <em>for</em> loop to stop at the <strong><em>second-to-last</em></strong> index. This way, there’s always a number at index <strong><em>i + 1</em></strong> for us to compare.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/921/1*YLojSOT4eQvIP3r4hCMLPg.png" /></figure><p>Another issue is that our for loop only iterates over the array <em>once</em>. It’s pretty uncommon for the array to be sorted after only one iteration of the <em>for</em> loop, as you can see here:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/480/1*tgAcYeyW21d_kZnq0vaBxA.gif" /><figcaption>Source: <a href="https://algorithm-visualizer.org/brute-force/bubble-sort">https://algorithm-visualizer.org/brute-force/bubble-sort</a></figcaption></figure><p>We tell the <em>for </em>loop to repeat itself as many times as needed by wrapping it inside of a <em>while</em> loop and giving it a conditional to work with.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aW3QokNrb33Y1mT5gATyKA.png" /></figure><p>First we declare a variable <strong><em>isSorted</em></strong> and initialize it to be <strong>false</strong> since our array is initially unsorted.</p><p>We need a conditional that returns <strong>true</strong> to get inside of our <em>while</em> loop, so we use the bang ( <strong>!</strong> ) operator to reverse the truthiness of the <strong><em>isSorted </em></strong>variable.</p><p>If we are able to get inside of our conditional statement on line 7, that means we found two numbers that needed to be swapped and can safely assume that the array is still unsorted. We let the program know this, you’ll see why in a moment.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Jkqr30wOukTPAMXQp3VYXQ.png" /></figure><p>You might have noticed that this code locks us into an infinite loop because we have no way of getting ( <strong>!isSorted</strong> ) on line 5 to evaluate to false and break.</p><p>How do we know we’re done sorting? <strong><em>We go through an entire iteration of the for loop without needing to swap any numbers</em></strong>. What happens when we don’t have to swap any numbers? <strong><em>We never tell the program to change isSorted to be false on line 9 above</em></strong>.</p><p>Knowing this, we can change <strong>isSorted</strong> to be<strong> true</strong> once we get inside of the while loop.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*flkprlmB5vCUzJU_LrgEnA.png" /></figure><p>If numbers need to be swapped that round, <strong>isSorted</strong> changes to <strong>false</strong>.</p><p>If we <em>don’t</em> have any numbers to swap, <strong>isSorted</strong> remains true, <strong>!isSorted</strong> evaluates to <strong>false</strong>, we break out of the <em>while</em> loop, and return the sorted array.</p><p>Our bubble sort algorithm now works without any problems, but there is still <em>one</em> more way we can optimize it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mYfelGPgIV85YkMkddeLNw.png" /></figure><p>By adding a <strong>counter</strong> variable to keep track of <strong>how many times we have completed a round of our for loop</strong>, we take advantage of knowing that at least <em>one more number on the right side of the array will wind up in its final sorted position after running the for loop</em>.</p><p>Put another way, we avoid having to look at numbers that we already know have been sorted.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/480/1*z3UyOzGINUS4No-IHjf-HA.gif" /><figcaption>Source: <a href="https://algorithm-visualizer.org/brute-force/bubble-sort">https://algorithm-visualizer.org/brute-force/bubble-sort</a></figcaption></figure><h3>Insertion Sort</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/480/1*WwNKVEZW_mnxklQPAC-3VQ.gif" /></figure><p>Similarly to Bubble Sort, Insertion Sort moves slowly compared to other major sorting algorithms, but we can still use it to learn about and leverage multiple pointers.</p><p>We start with a <em>for </em>loop, iterating over every number in our <strong>array</strong>. We know we’ll eventually be <strong><em>returning</em></strong> the <strong>array</strong> after it has been sorted, so let’s add the array to our <strong><em>return</em></strong> statement.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/739/1*P1VNS_pNj8AkvuMrOUp1Bg.png" /></figure><p>One important thing to notice is that our <em>for</em> loop index starts at<strong><em> i = 1</em></strong> and continues up to the<strong> last </strong>element of the array ( <em>array.length</em> ), as opposed to starting at <strong><em>i = 0 </em></strong>and continuing to the<strong> second-to-last</strong> element in the array ( <em>array.length - 1</em> ). Why is this?</p><p>In Bubble Sort, we were comparing numbers to the number on the<strong><em> right ( i+ 1 ) </em></strong>whereas in Insertion Sort, we will be comparing each number to the numbers on the <strong><em>left</em></strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ym6BvnFHE1YMUBO3ksncqg.png" /></figure><p>As we iterate over our array, our goal is to take whatever number is at index <strong><em>i</em></strong>, look over all of the numbers to the<em> left </em>of index <em>i</em>, and<strong><em> insert </em></strong>the number in its proper position. Take the gif below as an example.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/480/1*RX0WWA4kaoW01nuQbfMhRg.gif" /></figure><p>At index 7, we identify the number 6 and then move 6 to the left by swapping numbers until we reach a number smaller than 6 — in this case the 5 at index 3. A byproduct of the way insertion sort works is that <strong>all numbers to the left of index i wind up in sorted order</strong> as we continue to iterate over the array.</p><p>We move the number to its properly sorted position is by using another loop inside our initial <em>for </em>loop. We could use another<em> for</em> loop, but this would force our algorithm to continue sorting numbers even beyond when we’ve placed our number in the correct position.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/899/1*dGy9oQfm4fFDz4xrbgMTwA.png" /></figure><p>Instead of a for loop, let’s use a while loop instead and give it some conditionals to pass. We want our algorithm to continue to move the number at index i to the left until:</p><ol><li>The next number to the <strong><em>left ( j - 1 )</em></strong> is smaller than the number we’re moving</li><li>We’ve reached the end of the array, or index 0</li></ol><p>These two conditionals are accounted for in the while loop in the code below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/842/1*LU19GnT3FXWhTHM2n45qjQ.png" /></figure><p>By declaring<strong><em> j </em></strong>as its own variable on line 3, we give ourselves more control of our flow once we’ve met the conditionals we’re looking for. The only catch is that we have to manually decrement<strong><em> j </em></strong>as we iterate to the left, which is addressed on line 6.</p><h3>Selection Sort</h3><p><em>Coming up…</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d9df71eb6609" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Annotated Algorithms: Kadane’s Algorithm]]></title>
            <link>https://smithspencer817.medium.com/annotated-algorithms-kadanes-algorithm-5a9834ae9402?source=rss-9cdda60a5b00------2</link>
            <guid isPermaLink="false">https://medium.com/p/5a9834ae9402</guid>
            <dc:creator><![CDATA[Spencer Smith]]></dc:creator>
            <pubDate>Fri, 23 Oct 2020 22:31:04 GMT</pubDate>
            <atom:updated>2020-10-25T14:42:58.946Z</atom:updated>
            <content:encoded><![CDATA[<h3>Understanding the problem</h3><p>One of the more common problems you might encounter in a software interview involves finding what is commonly referred to as the “maximum sub-array” within a longer array. Take a look at this example here:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/654/1*vT2ipkcSungZSeC6fqGHYw.png" /></figure><p>We want to write a function that looks at an array and discovers which slice or segment of that array contains a series of numbers that adds up to the largest possible sum.</p><p>Since we didn’t specify how long our sub-array needs to be, the maximum sub-array is actually the entire array itself!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/977/1*sB3YMChOnl5fSN92ZbpTgA.png" /></figure><p>You might be thinking, “well <em>duh</em> all of the numbers in an array added together make up the largest sub array, <em>Einstein</em>. What’s the point of looking for a sub-array if we can just add up the whole thing??”</p><p>If all instances of this problem were this simple, you’d have a point. Unfortunately, other factors can come into play. What if the function had a second argument to force you into <em>only</em> considering sub-arrays of a given <strong><em>size</em></strong>?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/672/1*ubkPfFbBgVlgFpbv7Kbzow.png" /></figure><p>We can’t exploit the loophole of adding up the entire array itself since we have some more parameters to deal with. Let’s pretend we pass in the number 3 as an argument so we only consider subarrays that contain <em>three </em>consecutive numbers.</p><p>We can consider a sliding window approach where we look at every possible combination of three consecutive numbers in the array. What would the result of the first window be?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/463/1*e3pArWILP_CnS1ashhlUMA.png" /></figure><p>Cool. What if we slide the window over by one index?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/466/1*EtmCWNgXovybEVhNWaBNNQ.png" /></figure><p>Even better! Still, it doesn’t take much time to just look at the array and realize that the largest sum in a window of three numbers would be this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/464/1*9-j8WPsCg8N63GH263gjIg.png" /></figure><p>The window logic to look over each subArray of size 3 might look like something similar to this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*g2_bIKVw4xQHojsS_WnDFg.png" /></figure><p>Which would produce the following results in your console:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/564/1*jYbS0oHDiQdRI6IvS4o--Q.png" /></figure><p>So far we’ve been able to solve the example problems with ease, but we haven’t yet introduced the main component of this problem that can make things really tricky: the inclusion of <strong>negative numbers.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/335/1*gVxFEDtDvQwPspalyNl_yg.png" /></figure><p>If we continue to include an array size as an argument for our function, we can still utilize the sliding window approach. But what if our responsibility is to determine the largest sum within the array without knowing how large our final sub-array is going to be?</p><p>Let’s take a look at one way we could theoretically go about using our window approach, but instead of sliding the window over one index at a time, let’s incrementally <em>expand</em> the window to include more numbers. We’ll start with the first number in the array as its own sub-array:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/486/1*stMCBe2yEw6o-xskh0MywQ.png" /></figure><p>Easy enough. Let’s add one more number to the window:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/482/1*12nJxGo6ZZLt5U0RByKaEQ.png" /></figure><p>Herein lies the problem with negative numbers: simply adding more numbers to the array is <em>no longer guaranteed </em>to give us a larger sum. Things get even more confusing as we iterate deeper into the array. Consider when our loop gets us one index before the -8:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/491/1*3UOFVAlqDHtMtyJW8gSvjw.png" /></figure><p>Not only are we worse off by including the -8 in the next iteration….</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/442/1*toUSaI33QMf_JpuEsqnA4w.png" /></figure><p>… but we would have been even <strong><em>better off </em></strong>had we been able to ditch the -3 from earlier in the array that is dragging our sum down</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/442/1*iXCTy1c1GgraE209GHqqPQ.png" /></figure><p>Now we’re really cooking with gas. How do we find the largest sub-array when we have <strong>no idea how long the sub-array is supposed to be</strong> and there are <strong>negative numbers everywhere</strong> dragging our sum down??</p><p>One possible solution would be to use two pointers and nested <em>for</em> loops to look over every possible combination of array slices using a function like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/852/1*bOrAyb7T3xIJoYN-xSGsiQ.png" /></figure><p>While this does <em>technically</em> work, nesting loops will result in an algorithm that performs in O(N²) or quadratic time at <em>best</em>. For those of you that haven’t gotten to Big O yet, just know that means it’s going to run really slowly. There has to be a better way….</p><h3>Kadane’s Algorithm</h3><blockquote><strong>Part 1: maxEndingHere</strong></blockquote><p>This algorithm can be a little tricky to wrap your mind around at first, but its implantation actually winds up being very elegant and concise. The first thing we want to do is to borrow from our earlier expanding window concept and declare a variable to <strong>keep track of the largest sum in our array as our window expands</strong>, but with a twist. Consider the array below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/651/1*Qa8D965YmKEm37Lbv6Frdw.png" /></figure><p>Let’s start with a window of size one at the first index and use that as the base case for our initial maximum possible sum, which we will track as a comment below the array and save in the variable <strong>maxEndingHere</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/669/1*Qt7JZ8_egYH8QS0XhC8VuA.png" /></figure><p>To update the <strong>maxEndingHere</strong> variable as we continue to expand our window further, we need to consider the following question:</p><h4>Which of these two operations will result in a bigger number?</h4><blockquote>1. The <strong>next number over</strong> in our window?</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/677/1*diDvvbfEuxOewd8B72o_WQ.png" /></figure><blockquote>2. The current <strong>maxEndingHere </strong>sum + the <strong>next number over</strong> in our window?</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/913/1*fnB1KvvP5L_BRtvfkE11jQ.png" /></figure><p>Since the <strong>next number over </strong>is 5, but the <strong>next number over</strong> PLUS the <strong>maxEndingHere</strong> variable is 8, we take 8 as the bigger number, update <strong>maxEndingHere</strong>, and also update our comment to help us follow along</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/827/1*WEvZAPujC7in58fMTHiN9A.png" /></figure><p>Let’s keep going. The next number to the right as we expand our window is -9. Which is bigger? -9 alone or -9 PLUS <strong>maxEndingHere</strong>?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/942/1*mn5oFAfjf0aOYrT2JTQZSg.png" /></figure><p>Since -1 is a bigger number than -9, we choose to set<em> that </em>number as the new<strong> maxEndingHere</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/833/1*JwGkn-iQ9dms-dkiJ6RmTw.png" /></figure><p>For the next window we finally find an instance where the first option of our two options is larger.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/909/1*Q02dKFwTTXXaWUDH5hOUqQ.png" /></figure><p>Since the <em>next number over</em> ( 1 ) is larger than <strong>maxEndingHere</strong> + the <em>next number over</em> ( -1 + 1), we instead choose to set <strong>maxEndingHere</strong> to be the <em>next number over</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/987/1*GY15VGOIXtVldVeBUKdJgA.png" /></figure><blockquote>Part 2: maxSoFar</blockquote><p>Getting an understanding of how <strong>maxEndingHere</strong> works is the main part of the algorithm, but you probably noticed that the value of <strong>maxEndingHere</strong> moves up and down a lot as we go. How do we keep track of the largest sum that we’ve encountered so far? You guessed it, another variable!</p><p>In addition to another variable to save our <strong>maxSoFar</strong>, we have another series of questions to help us determine its value.</p><p>To illustrate, let’s back up in our loop to the point where our window only contains the first two numbers in our array</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/942/1*mn5oFAfjf0aOYrT2JTQZSg.png" /></figure><p>Like last time, since -1 is larger than -9, we select that value</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/961/1*mt_V44FvT8QVlPG_7VtKYg.png" /></figure><p>But wait, now don’t we have to change <strong>maxEndingHere</strong> to also equal -1? Don’t you think <strong>we should keep track of the <em>previous</em> maxEndingHere value</strong> so we don’t lose that biggest value before we update it?</p><p>Absolutely. Let’s add two more questions and a variable.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/956/1*7ayBSDKghfpITEgmjaoxSw.png" /></figure><p><strong>maxSoFar </strong>allows us to save the <strong>biggest value that we’ve come across so far</strong> as we continue to iterate through our loop. Since we know the <strong>maxEndingHere</strong> value is going to be constantly going up and down, we otherwise wouldn’t be able to recall our previous largest values.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/991/1*45joIHKMpd60PFTSjXZLsw.png" /></figure><blockquote>Part 3: Putting it all together</blockquote><p>Now that we’ve got the main concepts down, this is what the algorithm would look like in its entirety:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/954/1*XGkcG6CL1KYs2pLr1dN3lw.png" /></figure><p>Let’s break it down line by line</p><p>First things first, we need values to store in our two variables initially, so we just set their values to be whatever the <strong>first number in the array</strong> is.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*87xdmo5WTmnJfQMn99k1yA.png" /></figure><p>Then we iterate over every number in the array by using a <em>for</em> loop. To determine the value for the <strong>next number over</strong> (which we will use to determine our <strong>maxEndingHere</strong> variable), we grab the array at index <em>i</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*P-DBHeqXH8O74_MJ94Gd9w.png" /></figure><p>Remember how we determine the value of <strong>maxEndingHere</strong>? We decide which number is larger:</p><p>The <strong>next number over</strong> — OR — the <strong>next number over + maxEndingHere</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/956/1*dB4jLtx_WLnQGWJ9GRxBjw.png" /></figure><p>Finally, we use the <strong>maxEndingHere</strong> value to determine the largest value between <strong>maxEndingHere</strong> and <strong>maxSoFar</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/945/1*dvpfG39rthisuSpnZwlnIw.png" /></figure><p>Lastly, we simply return whatever the value is for <strong>maxSoFar</strong> after we’ve broken out of our <em>for</em> loop!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*qTkCuCVhbWhYMP1YS7brCw.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5a9834ae9402" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Rails as an API]]></title>
            <link>https://medium.com/swlh/getting-the-ball-rolling-with-a-basic-rails-app-69101eda5d48?source=rss-9cdda60a5b00------2</link>
            <guid isPermaLink="false">https://medium.com/p/69101eda5d48</guid>
            <dc:creator><![CDATA[Spencer Smith]]></dc:creator>
            <pubDate>Thu, 23 Jul 2020 01:16:28 GMT</pubDate>
            <atom:updated>2020-08-07T00:12:13.643Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*US12UCC_3AwoIDBn7MFv7Q.jpeg" /></figure><p>When first learning how to program, a lot of the projects you start with are already halfway finished. You might be learning from a Udemy course that gives you a default file structure, or maybe you’re enrolled with a Bootcamp that frequently starts you off with some pre-written code in an IDE. You’re comfortable working on a partially-competed project, but when you yourself have to create everything from scratch, you’re not always exactly sure how to light the fuse. This is a step-by-step guide for how to generally go about building a basic Rails API from scratch. For our demonstration, we’ll pretend that we’re building a basic Uber app where the relationships are as follows:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UXpDRw-t0LTyiaGwR_uVag.png" /></figure><h3>1. Rails New Appname</h3><p>Move into the directory where you’d like your project to be located and run <strong><em>rails new &lt;your-app-name-here&gt;</em></strong> into the terminal.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*clumz74Ul27xoqI82J-fYA.png" /></figure><p>This is going to give you a ton of structure that will allow you to get to the more customized parts of your project a little faster. In a nutshell, here are a few of the most important things that Rails is giving you “for free” when you enter this command. It’s good practice as a beginner to check these files out before doing anything else with your project.</p><blockquote><strong>config/routes.rb</strong></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/841/1*zRQYevGyCfWuH-HpRx7-ow.png" /></figure><p>This is where you will declare which routes will be available in your controllers. This should be empty to begin with, but routes will be added with future commands.</p><blockquote><strong>db/seeds.rb</strong></blockquote><p>Whenever you’re building the backend for a new app, it is essential that you populate your app with some “dummy data.” You’ll use this dummy data later on to ensure that your model relationships are working as expected, but for right now we can leave this file blank.</p><blockquote><strong>app/controllers, app/models, app/views</strong></blockquote><p>All three of these files will be blank to begin with, but it’s good to locate them before you need to use them. As we move forward, you’ll be checking these files to ensure that your program is being updated correctly. For right now, just make sure these folders exist.</p><h3>2. Generate resources for non-join models</h3><p>For our example, since Ride is the join model between Driver and Passenger, we’ll begin by working on the latter two. <strong><em>This means we will do all of step two for both Driver and Passenger before moving on to step 3.</em></strong></p><p>While you may prefer to add your models, controllers, and views folders with separate commands, <strong><em>rails generate resource</em></strong> allows you to combine these steps into a single command. The structure is as follows:</p><blockquote>rails generate resource ClassName first_attribute:integer second_attribute third_attribute:boolean</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*idnoJ7XfuXC9exf4cgzbhQ.png" /></figure><p><strong><em>Notice that when declaring your attributes, any attribute that is a string may simply be declared without a colon</em></strong>. In this example, since the driver’s name will be a string, we do not need to include a colon followed by the data type.</p><p>Let’s take a look at what this command is going to do for us:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/936/1*v001kO5otMVxwCE0_50hvw.png" /></figure><p>Thanks, Rails! With that single command, the above files have all been generated for us. While the test folders are important to be aware of, we’re just going to concern ourselves with the folders in yellow blocks for right now. Included in the yellow blocks are a migration, a model, a views folder, and access to the seven RESTful routes.</p><h3>3. Generate resource for join model</h3><p>We will be generating the exact same resources as we did for the non-join models, but we’ll declare the associations through “references.” The structure is as follows:</p><blockquote>rails generate resource JoinClassName model_one:references model_two:references</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*U9muEUd5PW_m1G4-yQ16Yg.png" /></figure><p>Just as we did with the Driver and Passenger models, we get a migration, a model, a views folder, and access to the seven RESTful routes.</p><h3>4. Check out file structure</h3><p>After generating resources for all of your models (including join models), it’s now a great time to look at your file structure again to see if all of your files have been updated appropriately. Do one model at a time and ask yourself the following questions:</p><blockquote>Did my routes update in config/routes.rb?</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/907/1*8e2OR7inNo0m3cethW-5dw.png" /></figure><blockquote>Were the migrations generated with the appropriate attributes and data types?</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*05ICxGmmTOBzbZTUVCRS4A.png" /></figure><blockquote>Do we have a model file under app/models?</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/768/1*zss-9fx1YO0Hryz7Vqe4-g.png" /><figcaption>Notice that the relationships have not yet been defined. We’ll address this in the next step.</figcaption></figure><blockquote>Was my model controller added to app/controllers?</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/950/1*z9zz8oUYVdBFZslxGUXDXA.png" /></figure><blockquote>Do I have new views subfolders under app/views?</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/329/1*zDravCeMGFDzS5WB1Tli5g.png" /></figure><h3>5. Add relationships to models</h3><p>Do one model at a time. As you’re going from model to model, it’s still not a bad idea to cross-check your model relationships with your migrations to ensure that everything lines up the way you intend.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/822/1*h5rpLpd_411UOlMdn2khlA.png" /></figure><p>You’ll probably notice that in the instance of the join model, Rails has already filled in the relationships for us!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/730/1*i4R7K7iP11usoDgO2bfKaA.png" /></figure><h3>6. Migrate the database</h3><p>After you’ve added your relationships to your models, most of your basic setup is complete. Our next goal should be populating the database with dummy data and using that data to test our models in the console, but to do this we have to first run our migrations.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YYzuSSnkglS8p7W0Vkptnw.png" /></figure><p>If your migration was successful, you can now go inside of your schema file under <strong><em>db/schema.rb </em></strong>to check once again if your database will have the appropriate column names and data types.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OinT7am2ZKIk4O7JUdI5qA.png" /></figure><h3>7. Test model relationships and attributes in console</h3><p>After we’ve migrated our database and checked our schema, we should now go inside of our rails console by entering <strong><em>rails c</em></strong> in the command line. After entering the console, we should check for at least the following four things:</p><p>Can I create new, temporary instances of my models?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Yyt-WIvWrV06dCnz51bhKw.png" /></figure><p>After creating an instance, can I access its attributes?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/808/1*MlmcURa7yUVcwt9MTkWoHA.png" /></figure><p>Can I check an instance’s relationships to other models?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/851/1*euyjtixS4eJd5uw0LwzGPA.png" /></figure><p>Do I have access to all instances of this class?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XKekNvOJNZw9vESlTAohbA.png" /></figure><h3>8. Create dummy data and seed the database</h3><p>Now that we’ve tested that we can create new instances of our models, we may now “seed” our database with dummy data that we can use to further test our program. There are a number of ways you can do this, but one popular Ruby gem that can help is the Faker library.</p><p>First, we’ll need to add <strong><em>gem “faker”</em></strong> to our Gemfile located in the main directory.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QRFsuGFK6X1ylCM0I90HUg.png" /></figure><p>Next, we’ll run bundle install in the terminal to install our new Faker gem</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/872/1*AsgZ3sCnB0tI2kT1MuwMUw.png" /></figure><p>After we’ve calibrated our Gemfile by installing all of our gems, you can now use the <strong><em>seeds.rb</em></strong> file under <strong><em>db/seeds.rb. </em></strong>Use iteration and the .create method to generate some instances and fill your database with fake data.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xIE5axfqiVkCPhoUtjA58w.png" /></figure><p>After you’re happy with how your seed data looks, go ahead and attempt to seed your database in the console by running <strong><em>rails db:seed. </em></strong>It’s normal to have a couple of minor bugs (such as misspellings or missing parentheses) that need to be addressed before the database will accept your data.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jkV0D1NcLGgLbHU5kgrYzw.png" /></figure><h3>9. Test dummy data in console</h3><p>We will essentially be going back into the console exactly as we did in step 7, but now we’ll be able to more easily test our relationships and see if the seed file populated our database as we intended.</p><p>Can I access <strong>all</strong> instances of this class?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jQ0fP19auG9kbGeURtv2qQ.png" /></figure><p>Can I access the <strong>attributes</strong> and <strong>relationships</strong> for a specific instance?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*q26DkLoDwOHuP_CD1b17_Q.png" /></figure><h3>10. Add validations to models</h3><p>Now that we’ve successfully seeded our database, it would be smart to make sure we can’t accidentally create new instances of classes using the wrong data. For example, if we’re creating a new passenger, we’ll need to know their name as a string and age as an integer. But what if we completely screw up the data types?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jzAxM8xDtwMuDZb_Rdkvsg.png" /><figcaption>Please don’t try this at home</figcaption></figure><p>Rails didn’t complain because we haven’t yet explicitly instructed the models to check for certain conditions before creating new instances. The integer 103 was converted to a string “103” and false converted to zero for age. This is where validations come in handy. Let’s add some conditions to the name and age attributes to prevent these contaminated instances from persisting.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*H8RNHHYKH_eDN_rJnIfqHQ.png" /></figure><p>There are plenty of options for validations you could add to your app, but for our example we’re just going to add the following validations:</p><ol><li>Passenger must pass in a name and it has to be a unique name</li><li>Passenger must pass in an age</li></ol><h3>11. Test validations in console</h3><p>After setting up validations in our models, let’s go back into our console and try to create “bad” instances. Notice how when our attempt at creating an instance doesn’t meet the validations, Rails won’t allow the instance to be persisted to the database. You can make sure the errors are what you expect them to be by checking <strong><em>instance.errors.full_messages</em></strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KXhzK4XZMD9M-7R_HwvXOw.png" /></figure><blockquote>**IMPORTANT**: From here, you can do all of the following steps for as many of your controllers as you wish. But keep in mind that whichever controller corresponds to the data that you plan to use as your main API is probably where you should start.</blockquote><h3>12. Add RESTful route actions to controllers</h3><p>While the standard reference to actions in Rails is CRUD, I actually like to think of the correct order being RCUD. The reasoning behind this will become more clear as you gain more experience, but ultimately it just makes more sense to be able to see (read) things before you’re able to create things.</p><p>Go through all of the models and your RESTful routes. You may not need all of them in each model and you can easily comment them out later, but they’re nice to have. <strong><em>Another thing to consider is that if you’re not using .erb files in your views folder, we can leave out the “new” and “edit” routes.</em></strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/874/1*uC6KLDh2MjQ8RXMOL1GO9Q.png" /></figure><p>If you wind up completing the back end of your project and realize there are certain routes that you never needed, you can comment out the routes and adjust the config/routes.rb file later.</p><h3>13. Add Strong Params as a private method</h3><p>Strong params can be viewed as a filter to ensure that your data is updated or created appropriately and they are represented as a method beneath a “private” keyword near the bottom of your file. <strong><em>These will be necessary to handle our “create” and “update” routes.</em></strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/924/1*8vAq8GjknfjZ9jyJd62LOw.png" /></figure><h3>14. Add variables to routes</h3><p>For our routes to have access to the data they will be responsible for handling, we need to provide them with variables containing appropriate data.</p><p>Since our<strong> INDEX </strong>route will be responsible for displaying all instances of our data, we can simply give it a variable containing all of the instances.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/534/1*0dGLBN1emI1JhGbJrzLStg.png" /></figure><p>Our <strong>SHOW</strong> route is responsible for displaying just one instance of a class, so for now all we need to do is to find whichever particular instance we’re looking for. We can do this by finding the instance by their ID, which is unique and stored in our params hash.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/644/1*CsXkMM2Q8XBQrhwnvrn5nw.png" /></figure><p>To <strong>CREATE</strong> a new instance when the program passes through the create route, we need access to multiple attributes for any given instance. Let’s make use of our newly-implemented strong params.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/693/1*XQq4QEyr2xPQ72jDJ2Sseg.png" /></figure><p>If we want to <strong>UPDATE</strong> an instance, we break our process down into two steps: first we find the particular instance we’re looking for, <em>then</em> we update it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/724/1*UIIUJ4NDBCRPx7PHggqsXQ.png" /></figure><p>Lastly, <strong>DELETE</strong>-ing an instance also requires two steps: find the instance, then destroy the instance.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/594/1*Z7_KXjpou3B2lJ1kG3jREA.png" /></figure><p>You might have noticed that the first thing we do for several of our routes is find a specific instance of a class. If you’d like to reduce your code by a few lines, you can use Rails’ built-in <strong>before_action </strong>method. This method will allow you to automatically trigger a given method before any number of routes that you specify. This isn’t totally necessary, but it can help a lot with readability as your program grows larger. Refer to the picture below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fT7UifxHyI8fQ3UjTSySGQ.png" /></figure><h3>15. Render JSON</h3><p>Our API is just about done on the back-end, but if we want our changes to be passed back to the front-end and rendered appropriately, we’ll need to call <strong>render json </strong>at the bottoms of our routes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GUEicggH5yospFqZNYffkQ.png" /></figure><h3>16. Application Controller inherits from ActiveRecord::API</h3><p>You may have noticed that all of our controllers inherit from another controller: ApplicationController. The default behavior of this controller is to inherit from ActiveRecord::Base, so we simply need to change it to inherit from ActiveRecord::API</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/902/1*cCqJiAD_AtLCqRnrTNl-dg.png" /></figure><h3>17. Houston, we have a server!</h3><p>Congrats! Now all we have to do to get this bad boy up and running is to go into our terminal and enter <strong>rails server </strong>or <strong>rails s </strong>for short.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/974/1*ksGwmUA0TEiPOHEy1JlwZA.png" /></figure><p>To view our new, functional API, we simply need to go to <strong>localhost:3000/api-controller-name-here</strong> in the browser</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XD2yAmTdL1MHDmqdVdUW8g.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=69101eda5d48" width="1" height="1" alt=""><hr><p><a href="https://medium.com/swlh/getting-the-ball-rolling-with-a-basic-rails-app-69101eda5d48">Rails as an API</a> was originally published in <a href="https://medium.com/swlh">The Startup</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>