<?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 John Eckert on Medium]]></title>
        <description><![CDATA[Stories by John Eckert on Medium]]></description>
        <link>https://medium.com/@johnteckert?source=rss-2a0d8b922932------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*Hw9I0hUYLBcVXzZE0vkCJA.png</url>
            <title>Stories by John Eckert on Medium</title>
            <link>https://medium.com/@johnteckert?source=rss-2a0d8b922932------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 21 Nov 2026 19:52:32 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@johnteckert/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[Service Workers]]></title>
            <link>https://medium.com/@johnteckert/service-workers-38693e874279?source=rss-2a0d8b922932------2</link>
            <guid isPermaLink="false">https://medium.com/p/38693e874279</guid>
            <category><![CDATA[api]]></category>
            <category><![CDATA[service-worker]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[pwa]]></category>
            <category><![CDATA[progressive-web-app]]></category>
            <dc:creator><![CDATA[John Eckert]]></dc:creator>
            <pubDate>Sat, 21 Jul 2018 17:31:08 GMT</pubDate>
            <atom:updated>2018-07-21T17:31:08.903Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QSoyzHHcExuA_2_NgFY5JA.jpeg" /></figure><p>Service Workers are essential for building <strong>Progressive Web Apps</strong>. They sit between your app and the rest of the world and allow you to control how your app sends and receives data and how it behaves when it is offline or running in the background.</p><p>Service Workers are part of the<strong> Web Workers API</strong>, so to understand how they work, let’s take a step back and explore the API a little bit. Also, you might want to read up on the <a href="https://medium.com/@johnteckert/the-main-event-loop-3928adcd2413"><strong>JavaScript Event Loop</strong></a> before continuing.</p><h3>Web Workers API</h3><p>The <strong>Web Workers API</strong> is a <strong>browser API</strong> that makes it possible to execute an operation in a background thread independent from the main execution thread of the web app.</p><p>This is a handy tool for dealing with anything that is going to eat up a significant amount of processing power. By delegating that task to a worker, your app can execute it in a <strong>separate thread</strong>, allowing the <strong>main thread</strong> to continue running the rest of your app (including the UI) without <strong>blocking</strong>!</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2F5Zesu5VPNGJlm%2Ftwitter%2Fiframe&amp;display_name=Giphy&amp;url=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2F5Zesu5VPNGJlm%2Fgiphy.gif&amp;image=https%3A%2F%2Fi.giphy.com%2Fmedia%2F5Zesu5VPNGJlm%2F200.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="244" frameborder="0" scrolling="no"><a href="https://medium.com/media/b912d206353caa4b2b2c6e0a5d1427f8/href">https://medium.com/media/b912d206353caa4b2b2c6e0a5d1427f8/href</a></iframe><p>Workers are created via a constructor that runs a named <strong>JavaScript</strong> file which contains the code that will run in the <strong>separate thread</strong>.</p><p>An individual worker is essentially a background task running in its own <strong>thread</strong> that can send messages to and receive them from the main thread. It’s important to note that because the worker runs in a different <strong>global context</strong> than the current<strong> window</strong>, the code that you run in the worker doesn’t have access to the <strong>DOM</strong> or some of the default methods or properties of the <strong>window</strong> object.</p><p>However, your worker does have access to things like<strong> XMLHttpRequest</strong>, <strong>WebSockets</strong>, and<strong> Fetch</strong>. For a full list of what is available to workers, check <a href="https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API/Functions_and_classes_available_to_workers">here</a>.</p><p>Data is sent between workers and the main thread through messages using .postMessage() to send messages and the .onMessage() <strong>event handler</strong> to respond. The message itself is contained in the data property of the Message event.</p><p>The <strong>Web Workers API</strong> consists of multiple types of workers:</p><ul><li><strong>Dedicated Workers</strong> are the most basic version. They are only accessible from the script that called them.</li><li><strong>Shared workers</strong> can be utilized by multiple scripts running in different windows.</li><li><strong>Service Workers</strong> are specifically for communicating with the network. They sit between your web application and the outside world.</li><li><strong>Audio Workers</strong> allow audio processing for the <strong>Web Audio API</strong> to be done inside a web worker context.</li></ul><h3>Service Workers</h3><p>Ok, back to service workers. A service worker is some <strong>JavaScript</strong> that can control the website it is associated with. It does this by intercepting requests, evaluating them and either allowing them to continue or modifying them to produce the desired behavior.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2Fa9wFQSc0oRQGI%2Ftwitter%2Fiframe&amp;url=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2Fa9wFQSc0oRQGI%2Fgiphy.gif&amp;image=https%3A%2F%2Fi.giphy.com%2Fmedia%2Fa9wFQSc0oRQGI%2F200.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="240" frameborder="0" scrolling="no"><a href="https://medium.com/media/bf90dea13a73ef84d30ba361b548ff79/href">https://medium.com/media/bf90dea13a73ef84d30ba361b548ff79/href</a></iframe><p>Service workers are <strong>event-driven</strong>, and they can use <strong>message events</strong> to receive information from other scripts and <strong>fetch</strong>, <strong>push</strong>, and <strong>sync</strong> events to respond to your app’s behavior.</p><h4>Life Cycle</h4><p>The life cycle of a service worker is separate from that of the web page:</p><ol><li><strong>Registration. </strong>You register your service worker in the <strong>JavaScript</strong> for your page. Once registered, the browser will download and install the service worker. The first time a user accesses a site controlled by a service worker, it is automatically downloaded. On return visits, the service worker is downloaded every 24-hours in order to keep it up to date.</li><li><strong>Installation. </strong>If this is the first time the service worker has been downloaded, it will be installed.</li><li><strong>Activation.</strong> Once installed the new service worker enters the activation<strong> </strong>stage. If there are any open pages being controlled by the previous service worker, the new worker will wait until they are no longer loaded before activating, making sure that there is only one version of the worker active at a time. Once the new service worker is activated, it will have control over all pages within its scope.</li></ol><h4>Use Cases</h4><p><strong>Service workers</strong> have a lot of interesting uses, and I am sure there are more to come, but some of the most common include:</p><ul><li><strong>Push notifications. </strong>Service workers can receive notifications from your server, even when your app is not active. This allows them to send push notifications to your user, whether they are currently on your site or not.</li><li><strong>Modify your app’s behavior when the user is offline. </strong>Service workers can intercept network requests, and by using the <strong>fetch API</strong>, can be used to serve the user a resource from their cache or a different resource, when one is unavailable.</li><li><strong>Background syncing of data. </strong>Service workers can be used to defer action until the user has a stable connection. This can help you ensure that any data that the user has tried to send is actually sent.</li></ul><h3>In Conclusion</h3><p>Service workers are a really powerful tool for creating web apps that provide value to your user — even when they are offline — controlling how your code interacts with the outside world.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2FWowj1abwRkpSo%2Ftwitter%2Fiframe&amp;url=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2FWowj1abwRkpSo%2Fgiphy.gif&amp;image=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2FWowj1abwRkpSo%2Fgiphy.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="335" frameborder="0" scrolling="no"><a href="https://medium.com/media/20970f743f490d8d67ddb65ae2de8b3b/href">https://medium.com/media/20970f743f490d8d67ddb65ae2de8b3b/href</a></iframe><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=38693e874279" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Main Event… Loop]]></title>
            <link>https://medium.com/codezillas/the-main-event-loop-3928adcd2413?source=rss-2a0d8b922932------2</link>
            <guid isPermaLink="false">https://medium.com/p/3928adcd2413</guid>
            <category><![CDATA[event-loop]]></category>
            <category><![CDATA[computer-science]]></category>
            <category><![CDATA[concurrency]]></category>
            <category><![CDATA[api]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[John Eckert]]></dc:creator>
            <pubDate>Sun, 15 Jul 2018 21:38:52 GMT</pubDate>
            <atom:updated>2018-07-30T08:09:08.081Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BoYe1mYh2k25kuBpWvKXzQ.png" /></figure><h4>A quick look at the JavaScript concurrency model</h4><p>JavaScript is a <strong>single-threaded</strong> language, which means it can only process one command at a time, but it is also <strong>asynchronous</strong> which means that events can happen outside of the main flow of your program. At first glance, those two ideas seem like they might be contradictory, so let’s take a deeper dive into what’s going on under the hood.</p><p>First, let’s take a look at what the <strong>runtime environment</strong> actually looks like.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*r5qEjvWDYXHTu-a6_Y7S7g.png" /></figure><p>As you can see the <strong>runtime</strong> consists of a <strong>stack</strong> and a <strong>heap</strong>. We don’t need to worry about the<strong> heap</strong> to talk about the <strong>event loop</strong>. Basically, it’s a bunch of memory that can be allocated as needed and referred to by the <strong>stack</strong>. What we are interested in is the <strong>stack</strong> itself.</p><p>Remember how I said <strong>JavaScript</strong> was <strong>single-thread?</strong> Well, that <strong>single-thread</strong> is the <strong>call stack</strong>. As your program runs, each <strong>function call</strong> is pushed onto the <strong>stack</strong> to be executed. Then as it returns, it is popped off the top.</p><p>Since the <strong>call stack</strong> is, well — a <strong>stack</strong>, we can only execute the last item pushed onto it.</p><p>So, what happens if that function takes a long time to execute? That’s called <strong>blocking</strong>. <strong>Blocking </strong>is when the execution of your code is held up or blocked by some process, and nothing else can happen until it completes.</p><p>If that’s the case, why doesn’t our entire program freeze every time we make an HTTP request? To understand this, we need to take one giant step back and look at the bigger picture.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2Fl9t6UzOnEjUNW%2Ftwitter%2Fiframe&amp;url=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2Fl9t6UzOnEjUNW%2Fgiphy.gif&amp;image=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2Fl9t6UzOnEjUNW%2F200.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="298" frameborder="0" scrolling="no"><a href="https://medium.com/media/3656a5fd1229dcf1055254b47aec15e2/href">https://medium.com/media/3656a5fd1229dcf1055254b47aec15e2/href</a></iframe><h3>Web APIs</h3><p>While it’s true that the <strong>JavaScript runtime</strong> can only do one thing at a time, it exists within our browser, and our browser has some extra stuff to help make things run smoothly.</p><p>That ‘stuff’ is <strong>Web APIs. Client-side JavaScript </strong>has many APIs available to it. They aren’t part of the core <strong>JavaScript</strong> language, but they are built on top of it and provide extra functionality. <strong>Web APIs</strong> come in two categories:</p><ol><li><strong>Third-party APIs</strong> (which are not built into the browser) include things like the <strong>Spotify API</strong> or the <strong>Watson APIs</strong>, where you make some sort of request through a server and receive a response.</li><li><strong>Browser APIs </strong>function similarly to <strong>third-party APIs</strong> but are built directly into the browser. <strong>Browser APIs</strong> expose data from the browser and surrounding computer environment. A lot of the things that you constantly use and probably think of as defining features of <strong>JavaScript</strong> are actually <strong>browser APIs</strong>. Some examples include the <strong>DOM API</strong> which allows us to manipulate <strong>HTML</strong> and <strong>CSS</strong>, the <strong>Fetch API</strong> for making HTTP requests, and many more including <strong>Canvas</strong>, <strong>WebGL</strong>, and the <strong>Web Audio API</strong>.</li></ol><p>The <strong>browser APIs</strong> are capable of executing their own code outside of the <strong>call stack.</strong> You can think of them as separate threads that your code can make calls to but not access directly.</p><p>What happens when something you started in a <strong>browser API</strong> completes? Say you executed a <strong>fetch</strong> and got a <strong>response </strong>- we don’t want the <strong>Fetch API</strong> pushing that <strong>response</strong> to the <strong>call stack</strong> whenever it randomly completes, or we could screw up the code that is currently running. We need something to hold onto all of those responses until the <strong>call stack</strong> is ready for them. That’s where the <strong>message queue</strong> comes in.</p><h3>The Message Queue</h3><p>The <strong>message queue</strong> is responsible for holding all of the messages that are generated from processes completed by <strong>browser APIs</strong>. As the <strong>call stack </strong>empties, the <strong>messages</strong> are executed (oldest first because it’s a <strong>queue</strong>) and their <strong>callback functions</strong> are added to the <strong>call stack</strong>. We’re still missing one vital piece of the puzzle. We need something to regulate the flow between the <strong>call stack</strong> and the <strong>message queue</strong>. That something is the Event Loop.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2FwLTJn2Tnbi240%2Ftwitter%2Fiframe&amp;url=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2FwLTJn2Tnbi240%2Fgiphy.gif&amp;image=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2FwLTJn2Tnbi240%2Fgiphy.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="230" frameborder="0" scrolling="no"><a href="https://medium.com/media/83d6baad459fe42842f4f04d981f68cb/href">https://medium.com/media/83d6baad459fe42842f4f04d981f68cb/href</a></iframe><h3><strong>The Event Loop</strong></h3><p>The <strong>Event Loop</strong> is responsible for determining if the <strong>call stack</strong> is ready, and if it is, then executing the next message in the <strong>queue</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BoYe1mYh2k25kuBpWvKXzQ.png" /></figure><p>This setup, based on the <strong>event loop,</strong> is called a concurrency model, and it’s very different from a lot of other languages. One of the interesting things about it is that because of it <strong>JavaScript</strong> is <strong>non-blocking.</strong></p><p>Cool, but what does that mean?</p><p>To be <strong>non-blocking</strong> means that instead of leaving slow tasks sitting on the <strong>call stack</strong> holding up the execution of the rest of your code, <strong>JavaScript</strong> executes them <strong>asynchronously</strong> by delegating them to the <strong>browser APIs</strong>. Once the <strong>asynchronous</strong> process is completed, the <strong>JavaScript runtime</strong> relies on the <strong>event loop</strong> to process the <strong>message</strong> as soon as the <strong>call stack</strong> becomes available.</p><p>So that’s how <strong>JavaScript</strong> is able to be both <strong>single-threaded</strong> and <strong>asynchronous</strong>. I hope this post was helpful in understanding more about how <strong>JavaScript</strong> uses the <strong>event loop</strong> to work it’s magic.</p><ul><li>If you want to learn more, <a href="https://youtu.be/8aGhZQkoFbQ">this talk</a> by Philip Roberts is a really great resource.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3928adcd2413" width="1" height="1" alt=""><hr><p><a href="https://medium.com/codezillas/the-main-event-loop-3928adcd2413">The Main Event… Loop</a> was originally published in <a href="https://medium.com/codezillas">Codezillas</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Big O No!]]></title>
            <link>https://medium.com/@johnteckert/big-o-no-650ec9cacaa2?source=rss-2a0d8b922932------2</link>
            <guid isPermaLink="false">https://medium.com/p/650ec9cacaa2</guid>
            <category><![CDATA[complexity]]></category>
            <category><![CDATA[big-o-notation]]></category>
            <category><![CDATA[computer-science]]></category>
            <category><![CDATA[coding-interviews]]></category>
            <category><![CDATA[algorithms]]></category>
            <dc:creator><![CDATA[John Eckert]]></dc:creator>
            <pubDate>Sun, 08 Jul 2018 15:19:56 GMT</pubDate>
            <atom:updated>2018-07-08T15:19:56.763Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WOB7jsAtqTm7Dg7xOGkMlA.jpeg" /></figure><h4>Understanding Big O notation</h4><p>We’ve all been there, you are in an interview, and you’ve just finished solving some particularly challenging interview question. The sweat is beginning to evaporate from your forehead, your heart is beating normally again, and then your interviewer says, “So what’s the complexity of your solution?”</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2FFu9EXNUgJBRBe%2Ftwitter%2Fiframe&amp;display_name=Giphy&amp;url=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2FFu9EXNUgJBRBe%2Fgiphy.gif&amp;image=https%3A%2F%2Fi.giphy.com%2Fmedia%2FFu9EXNUgJBRBe%2Fgiphy.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="332" frameborder="0" scrolling="no"><a href="https://medium.com/media/037799ddb6e4a202479d9860c3008db6/href">https://medium.com/media/037799ddb6e4a202479d9860c3008db6/href</a></iframe><p>For new developers, especially those of us that don’t come from a computer science background, Big O Notation can be extremely intimidating. It’s a weird combination of specificity and abstraction that feels like some sort of secret handshake that everyone else knows.</p><h4>What Is It?</h4><p>Big O notation is just a way of documenting the efficiency of some code. More specifically, it describes how a change in the size of the input of a function (or algorithm, or whatever) affects its running time. Big O is also used to describe space complexity, but we are going to focus on time because I think that is the more difficult one to get a handle on. An excellent quick reference for the different complexities is <a href="http://bigocheatsheet.com/">Big-O Cheat Sheet</a>.</p><p>For me, the best way to get a handle on each of them is to understand what they are describing and then walk through some examples.</p><p>Before we get started, it’s important to remember that the big O in Big O stands for <strong>order of</strong>, so we are really only concerned with changes in the order of magnitude. This means we don’t have to worry about constants. It also means that O(n), O(2n), O(10n) are all just O(n).</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2FbhTJKZWkeKwiQ%2Ftwitter%2Fiframe&amp;url=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2FbhTJKZWkeKwiQ%2Fgiphy.gif&amp;image=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2FbhTJKZWkeKwiQ%2Fgiphy.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="175" frameborder="0" scrolling="no"><a href="https://medium.com/media/ed7d206716363942f42547619e069a91/href">https://medium.com/media/ed7d206716363942f42547619e069a91/href</a></iframe><h4>Constant Time — O(1)</h4><p>This is the dream! It means that no matter how big our input is, our algorithm will only take a finite number of steps. An example of this would be accessing an element in an array by its index. It doesn’t matter how long the array is because we don’t have to traverse it in any way, we can just grab the item directly. You’re probably not going to be writing a lot of O(1) functions, but it’s good to recognize when an action happens in constant time because it can be a handy way to improve the performance of a solution you are writing.</p><p>Also, it bears repeating that Big O notation isn’t interested in what the constant is, only that it is constant. The algorithm could take 1 step, 5 steps, or 1000 steps — it is still constant and still O(1) because we can count on it to always take the same amount of time no matter how our input changes.</p><h4>Logarithmic Time — O(log n)</h4><p>Logarithmic Time, basically means that when you double the size of your input, it increases but doesn’t double the amount of work required. This one comes into play a lot in search algorithms, but outside of that probably won’t pop up too much in general coding problems.</p><h4>Linear Time — O(n)</h4><p>Linear time means that for every new element we add to our input our algorithm runs one more time, so the speed grows in a linear relationship to the size of our input. A great example of this is a basic for loop. If we use a for loop to iterate over an array, the loop will run an extra time for each item we add to the array.</p><p>In fact, when figuring out the run time of a function that you have written, a good thing to look at is how you are iterating over your data. If you are using some sort of looping structure to move over a collection and perform an action, it is likely that you are in Linear Time.</p><p>There are a couple of scenarios to look out for that can make linear time slightly confusing. The first is multiple for loops. For example, let’s look at the following function:</p><pre>function reverseAndBack(str) {<br>   let reversed = &#39;&#39;<br>   let unreversed = &#39;&#39;<br>   for (let i = str.length - 1; i &gt;= 0; i--) {<br>      reversed += str[i]<br>   }<br>   for (let j= reversed.length - 1; j &gt;= 0; j--) {<br>      unreversed += reversed[j]<br>   }<br>   return unreversed<br>}</pre><p>Other than being completely pointless, this function has two loops, and each one increases in linear time in relation to the input. If each loop is O(n), then the speed of this function is O(n) + O(n) which is O(2n), but remember that we don’t care about constants, so we still classify this as O(n) because it’s all about orders of magnitude.</p><p>But what if we are running loops over two different pieces of data? For example:</p><pre>function combineArrays(arr1, arr2) {<br>   const combined = []<br>   for (let i = 0; i &lt; arr1.length; i++) {<br>      combined.push(arr1[i])<br>   }<br>   for (let j = 0; j &lt; arr2.length; j++) {<br>      combined.push(arr2[j])<br>   }   <br>   return combined<br>}</pre><p>In this case, we are looping over two different arrays. Both loops still happen in linear time, but we would write this as O(n+m) to denote that the runtime is dependent on two different inputs.</p><h4>Quasilinear Time — O(n log n)</h4><p>Quasilinear Time means that doubling the size of your input increases the amount of work you need to do by slightly more than double. This is a common runtime for sorting algorithms.</p><h4>Quadratic Time — O(n²)</h4><p>Quadratic time, like it’s notation suggests means that for every new element we add to our input, the number of steps increases exponentially. A great problem for visualizing this runtime is the steps problem, which is a common interview question.</p><p>In this problem, the goal is to take in a number <em>n </em>and log a series of # signs to the console that form steps, the bottom row of which is length <em>n.</em></p><pre>function steps(n) {<br>  for (let i = 0; i &lt; n; i++) {<br>    let line = &#39;&#39;;<br>    for (let j = 0; j &lt; n; j++) {<br>      if (j &lt;= i) {<br>        line += &#39;#&#39;;<br>      } else {<br>        line += &#39;_&#39;;<br>      }<br>    }<br>    console.log(line);<br>  }<br>}</pre><p>so calling steps(5) would log:</p><pre>#____<br>##___<br>###__<br>####_<br>#####</pre><p>The first warning sign here should be the nested for loops. In this example, the outer for loop is responsible for the rows, and the inner for loop is responsible for the columns of <em>#’</em>s and spaces. This means that every time we increase the value of <em>n </em>we have to run the inner for loop an entire extra time. Therefore the amount of work we are doing increases exponentially. If this one is still a little hard to visualize, this image might help.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*gBWbmMJyDoOZfLoXSlP0RQ.png" /></figure><p>As you can see in the image, adding an element to the array adds both a new row and a new column, so the increase happens in two dimensions.</p><p>Just because you have a nested for loop doesn’t always mean your runtime is O(n²). If both loops aren’t iterating over the same input, then it could be a different runtime, like O(n*m) or something else, so make sure you take a moment to look at what is actually happening in your code.</p><h4>Exponential Time — O(2^n)</h4><p>Exponential time means that if you add a single element to your input, the processing time more than doubles. Yikes! This can start to creep in when you are solving things recursively, where every new element in your input requires multiple new function calls.</p><h4>Combining Run Times</h4><p>Another thing to bear in mind is that complicated problems can have combinations of these runtimes. To evaluate your function, the best thing to do is look at each step and evaluate its runtime. Then you can combine those runtimes and remove any unnecessary constants. This should leave you with the runtime of your entire function.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2Fw0CPP48tkM6Ag%2Ftwitter%2Fiframe&amp;display_name=Giphy&amp;url=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2Fw0CPP48tkM6Ag%2Fgiphy.gif&amp;image=https%3A%2F%2Fi.giphy.com%2Fmedia%2Fw0CPP48tkM6Ag%2F200.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="244" frameborder="0" scrolling="no"><a href="https://medium.com/media/4dc6ea2f003801e4fb0388493085a69e/href">https://medium.com/media/4dc6ea2f003801e4fb0388493085a69e/href</a></iframe><p>So next time Big O comes up in one of your interviews, I hope it won’t seem so daunting and that it will be a little bit easier to figure out the complexity of your code.</p><p>If you’d like to read more about Big O, I’ve included some links below to resources that I found helpful.</p><ul><li><a href="https://www.udemy.com/coding-interview-bootcamp-algorithms-and-data-structure/learn/v4/overview">The Coding Interview Bootcamp: Algorithms + Data Structures</a></li><li><a href="http://www.crackingthecodinginterview.com/">CRACKING the CODING INTERVIEW</a></li><li><a href="https://www.edx.org/course/cs50s-introduction-computer-science-harvardx-cs50x">CS50&#39;s Introduction to Computer Science</a></li><li><a href="http://bigocheatsheet.com/">Know Thy Complexities!</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=650ec9cacaa2" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[What the GTFS is going on?!?!]]></title>
            <link>https://medium.com/@johnteckert/what-the-gtfs-is-going-on-a03433b2a6bd?source=rss-2a0d8b922932------2</link>
            <guid isPermaLink="false">https://medium.com/p/a03433b2a6bd</guid>
            <category><![CDATA[protocol-buffers]]></category>
            <category><![CDATA[api]]></category>
            <category><![CDATA[public-transit]]></category>
            <category><![CDATA[gtfs]]></category>
            <category><![CDATA[ruby]]></category>
            <dc:creator><![CDATA[John Eckert]]></dc:creator>
            <pubDate>Sat, 30 Jun 2018 21:52:14 GMT</pubDate>
            <atom:updated>2018-06-30T21:52:14.403Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pRYhVAg3vvz4bfm-JfvH3w.jpeg" /><figcaption><a href="https://www.flickr.com/photos/iandavid/3804456709">https://www.flickr.com/photos/iandavid/3804456709</a></figcaption></figure><p>This week I started working on a project using New York City subway data. When I made a request to the MTA’s API, to test my key, I got a surprise!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WvMTfLQHCUmUadqC2UnfEA.png" /></figure><p>It turns out that the MTA’s data feeds, as well as most transit data available, uses a data standard called <strong>GTFS</strong>.</p><p><strong>GTFS</strong> stands for <strong>General Transit Specification</strong>, it is an open data format for public transit data created by Google. There are two categories within <strong>GTFS</strong>, <strong>static</strong> and <strong>realtime</strong>, and they operate slightly differently.</p><p>Before <strong>GTFS </strong>there was no standard for transit data, so it’s introduction led to quick adoption by both developers and transit agencies.</p><h3>GTFS Static</h3><p>A <strong>static GTFS</strong> feed is a <strong>.zip</strong> file that contains between 6 and 13 <strong>CSV</strong> tables, each stored in a <strong>.txt</strong> file. Each of the <strong>CSV</strong> tables contains the data for one category of information about the transit system in question. The six mandatory tables are <strong>agency</strong>, <strong>routes</strong>, <strong>trips</strong>, <strong>stop_times</strong>, <strong>stops</strong>, and <strong>calendar</strong>. The 7 optional tables include things like <strong>fares</strong>, <strong>transfers</strong>, and <strong>frequency</strong>.</p><p>For a list of the fields in each table check out <a href="https://developers.google.com/transit/gtfs/reference/#routestxt">Google’s documentation</a>.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2FcOo3aeD9Jzxh6%2Ftwitter%2Fiframe&amp;url=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2FcOo3aeD9Jzxh6%2Fgiphy.gif&amp;image=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2FcOo3aeD9Jzxh6%2Fgiphy.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="286" frameborder="0" scrolling="no"><a href="https://medium.com/media/505db9a2f8ee6545492a2f5f3381291c/href">https://medium.com/media/505db9a2f8ee6545492a2f5f3381291c/href</a></iframe><h3>GTFS Realtime</h3><p><strong>GTFS Realtime</strong> is an extension of the <strong>GTFS</strong> format that allows transit agencies to provide access to real-time data about transit systems. This means developers have access to information about <strong>Trip updates</strong>, <strong>Service alerts</strong>, and <strong>Vehicle positions</strong>. The information from the feed is returned as a binary file which is then decoded using <a href="https://developers.google.com/protocol-buffers/docs/overview"><strong>protocol buffers</strong></a>.</p><p><strong>Protocol buffers</strong> specify how you want your data structured and are supplied as a <strong>.proto</strong> file which determines how your data is serialized when it is decoded. If that sounds complicated don’t worry, Google has a <a href="http://google/gtfs-realtime-bindings">repo</a> of <strong>GTFS</strong> <strong>Realtime</strong> language bindings that can do most of the work for us!</p><p>Let’s write a quick little <strong>ruby</strong> program with <strong>Sinatra</strong>, to test that everything is working correctly. I have hardcoded feed_id=21 into this example, which will give us data from the <strong>B/D/F/M</strong> line.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*neMQ1k7EoSVPg85tJBxaOg.png" /></figure><p>When this is run, we receive an array of objects. Each object represents a train and contains two sub-objects. The first is called &quot;trip&quot; and contains a trip id, the trip’s start time and the train’s route id. The second is &quot;stop_time_date&quot; which contains an array of objects containing arrival and departure information for each stop that the particular train has been to.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MqbS0lVPKxbZ8lnZTz8N4A.png" /></figure><p>Now we have a bunch of information about train times and stops, but what can we do with it?</p><p>We can combine it with the information that we pulled from the <strong>static</strong> <strong>GTFS </strong>feed! We now have information about which stop corresponds to each element’s &quot;stop_id&quot;, including the stops name, and GPS coordinates. We also have access to information about which stations accept transfers, route data, and a lot more.</p><p>By combining information from the <strong>static GTFS</strong> feed and the <strong>GTFS Realtime</strong> feed, we have a very complete set of information about the transit system… Except for what’s going to happen when they shut down the L Train!</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2FhrKmmzitRaGcg%2Ftwitter%2Fiframe&amp;url=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2FhrKmmzitRaGcg%2Fgiphy.gif&amp;image=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2FhrKmmzitRaGcg%2Fgiphy.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="281" frameborder="0" scrolling="no"><a href="https://medium.com/media/999511a39974bbfef2967f890d1ceadd/href">https://medium.com/media/999511a39974bbfef2967f890d1ceadd/href</a></iframe><p>As you can see <strong>GTFS</strong> is a really robust system for dealing with transit data, and because it was adopted so universally, you can access transit data from any city that uses it in the same way. After a quick look at the internet, it seems like there are over 1000 cities around the world that provide access to <strong>GTFS</strong> data about their public transit!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a03433b2a6bd" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Teaching A Robot To Dance]]></title>
            <link>https://medium.com/@johnteckert/teaching-a-robot-to-dance-95ee9993bb97?source=rss-2a0d8b922932------2</link>
            <guid isPermaLink="false">https://medium.com/p/95ee9993bb97</guid>
            <category><![CDATA[hackathons]]></category>
            <category><![CDATA[robotics]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[robot-art]]></category>
            <category><![CDATA[robots]]></category>
            <dc:creator><![CDATA[John Eckert]]></dc:creator>
            <pubDate>Sun, 24 Jun 2018 17:00:40 GMT</pubDate>
            <atom:updated>2018-06-24T17:00:40.048Z</atom:updated>
            <content:encoded><![CDATA[<h4>Reflections on my first hackathon</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Yg-PnGwqGc4r-96-T3Vt1g@2x.jpeg" /><figcaption>Misty</figcaption></figure><p>This past week I participated in my first hackathon as part of <a href="http://www.developerweek.com/NYC/">Developer Week NYC</a>.</p><p>It was a great experience! I got to play with an <a href="https://www.mistyrobotics.com/">awesome new robot</a> and hang out with the people who made it, I got to work on a project with some people I didn’t know, and I even learned a few things.</p><p>After participating in the event, I made a list of some things that I think were essential to me having a good experience, as well as some things I could have done to make the experience better.</p><h4><strong>1. Go into the hackathon knowing what you want to get out of it</strong></h4><p>Do you want to focus on your front end skills? Maybe you want to experiment with Python. Decide what your personal goal is ahead of time. This is a piece of advice that someone gave me, and it was spot on!</p><p>For this hackathon, there were multiple sponsors, each running their own contest. I went into it knowing that I wanted to work with Misty Robotics and I made that my focus. Deciding this ahead of time made it easier to find a team to work with because I was able to zero in on others who wanted to work on the same thing. It also made it easier to set more specific goals as we progressed, because I already had the sense that I was achieving what I set out to do.</p><h4><strong>2. Don’t be intimidated</strong></h4><p>I’m pretty new to coding, so I was a bit intimidated walking into a room full of developers and looking for a team to join. In the back of my head I was worried about being the weakest link, and because of that, I felt really uncomfortable approaching people to form a team. Guess what, everybody was new to this once! It’s been my experience that the developer community is a super welcoming and friendly bunch of people. If your honest with the people you talk to about your skill level and what your goals are (see #1), it will be much easier to find a team that fits both your skill level and personality.</p><h4><strong>3. Once you have an idea stick with it</strong></h4><p>One of the first things your team is going to have to do is figure out what they’re going to build. Depending on the specifics of your hackathon, there could be a lot of different ideas, and a lot of features that people want to add to your project.</p><p>Time is limited, and it’s easy to be overconfident about what you will be able to get done. Just like in real life, it’s imperative to agree upon what your MVP and make sure you have that done before adding that new feature you just thought of.</p><h4>4. Be organized</h4><p>It’s also a good idea before you start, to take a minute to talk about the roles of everyone on your team and who is going to be responsible for what. This conversation can be as specific or loose as the situation warrants. It will help ensure that you don’t suddenly realize that you can’t present your project because nobody seeded your database when there are 15 minutes left in the challenge, and you are frantically debugging something.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2FmIZ9rPeMKefm0%2Ftwitter%2Fiframe&amp;display_name=Giphy&amp;url=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2FmIZ9rPeMKefm0%2Fgiphy.gif&amp;image=https%3A%2F%2Fmedia3.giphy.com%2Fmedia%2Fv1.Y2lkPTc5MGI3NjExcjU0eTVxaDVqcXJxbnN5ZGU2NmxsNG1wcTE1Ynp4OWo5ZXR1dndlbiZlcD12MV9naWZzX2dpZklkJmN0PWc%2FmIZ9rPeMKefm0%2Fgiphy.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="435" frameborder="0" scrolling="no"><a href="https://medium.com/media/bd9d0444389c743cd40017c28f2d9622/href">https://medium.com/media/bd9d0444389c743cd40017c28f2d9622/href</a></iframe><h3>Bring On The Dancing Robots</h3><p>Like I said earlier, the project I chose to work on involved playing with Misty, a really cool robot made by <a href="https://www.mistyrobotics.com/">Misty Robotics</a>.</p><p>Misty has a bunch of capabilities (including proximity sensors, facial recognition, and changeable facial featuresjust to name a few) that respond to JavaScript. Misty’s commands can be sent over wifi, or saved on the robot as actions and executed by sending a POST request.</p><p>My partner and I spent most of the first morning of the hackathon just playing around with the robot and learning how she worked.</p><p>We brainstormed a bunch of ideas, trying to think of something fun and useful, that would show off the robots features and take advantage of the things that set her apart from other types of devices.</p><p>We started out with the lofty goal of trying to create a script that would allow Misty to lead people from one place to another while navigating around objects, kind of like a seeing-eye dog. As we began to explore how to do this, we ran into some difficulties that made this project impossible to pull off at the hackathon. The most significant setback was that Misty’s SLAM (simultaneous localization and mapping) functionality was still in alpha and couldn’t be persisted from one execution of our code to the next. After talking about what was possible with a couple of the Misty Robotics’ developers, we decided to save that idea for another day and go back to the drawing board. Our next plan was something a little more lighthearted. We decided to teach our robot to dance!</p><p>The main thing that sets Misty apart from other devices is her mobility, so building a series of steps timed to music seemed like a perfect exercise! After very little debate, we decided on The Hustle.</p><p>Our thought was that if you could write a script that made Misty play music and dance to it, you could send her out into your office and have her execute that code at certain times of day, or in response to calendar events and remind everyone to get up and move!</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2F3o6gEf6bTrv3PpaEOA%2Ftwitter%2Fiframe&amp;display_name=Giphy&amp;url=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2F3o6gEf6bTrv3PpaEOA%2Fgiphy.gif&amp;image=https%3A%2F%2Fi.giphy.com%2Fmedia%2F3o6gEf6bTrv3PpaEOA%2Fgiphy.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="435" frameborder="0" scrolling="no"><a href="https://medium.com/media/9961c38a227dbcfd08217984f4c320fe/href">https://medium.com/media/9961c38a227dbcfd08217984f4c320fe/href</a></iframe><h3>The Hustle.</h3><p>The first thing we had to do was break the dance down into steps the robot could execute. This is what we came up with:</p><blockquote><strong>STEP 1:</strong> Play Song</blockquote><blockquote><strong>STEP 2:</strong> Move backwards for 4 counts</blockquote><blockquote><strong>STEP 3:</strong> Move forwards for 4 counts</blockquote><blockquote><strong>STEP 4:</strong> Spin Clockwise for 4 counts</blockquote><blockquote><strong>STEP 5:</strong> Spin Counter-clockwise for 4 counts</blockquote><blockquote><strong>STEP 6:</strong> Turn 90 degrees clockwise and tilt head up</blockquote><blockquote><strong>STEP 7:</strong> Turn 90 degrees counter-clockwise and tilt head down.</blockquote><blockquote><strong>STEP 8: </strong>Spin for 8 counts and land facing 90 degrees counter-clockwise.</blockquote><blockquote>Repeat loop until Misty is facing center again.</blockquote><p>Once we had the basic shape of the dance, we also added some decorations into the steps, like changing Misty’s facial expression or the color of the front LED.</p><p>There was a lot of trial and error involved. Even though the actions we were trying to get her to do were specific and timed to music, things like the texture of the floor and the speed with which commands were executed meant that we had to do a lot of experimentation and adjustment.</p><p>Luckily, the dev team from Misty robotics was sitting right behind us. They were extremely helpful and very eager to talk to us about our experience using Misty, including what kind of things we’d like to see her be able to do in the future. Ultimately, the experience of experimenting with a new piece of gear while having a dialog with her creators, was the most rewarding part of the whole event.</p><p>In the end, it turns out that Misty isn’t much better of a dancer than I am. Although, if I’m being completely fair, it may just be that I wasn’t a great teacher.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FVhg_wLHZ1JM%3Ffeature%3Doembed&amp;url=http%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DVhg_wLHZ1JM&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FVhg_wLHZ1JM%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="640" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/42f35badd6bff99bb936de50937b5077/href">https://medium.com/media/42f35badd6bff99bb936de50937b5077/href</a></iframe><p><a href="https://www.mistyrobotics.com/">Say Hello to Your Next Development Platform | Misty Robotics</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=95ee9993bb97" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Interacting With Dom Elements in React]]></title>
            <link>https://medium.com/codezillas/interacting-with-dom-elements-in-react-e7e409d7874e?source=rss-2a0d8b922932------2</link>
            <guid isPermaLink="false">https://medium.com/p/e7e409d7874e</guid>
            <category><![CDATA[dom]]></category>
            <category><![CDATA[ref]]></category>
            <category><![CDATA[css]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[John Eckert]]></dc:creator>
            <pubDate>Sun, 17 Jun 2018 14:40:19 GMT</pubDate>
            <atom:updated>2018-06-20T23:31:35.568Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/503/1*IbhOrlsAyBJWPZKPtLFC0w.png" /></figure><p>Earlier this week, I was building a React component that used content overflow to contain a bunch of smaller elements. I needed to allow the user to scroll left and right through them. Initially I used content overflow to add a scrollbar to the element</p><pre>overflow-x: scroll;</pre><p>As I was working on it, I decided that I really hated the scrollbar and the fact that it constantly made me double swipe back a page in the browser, while I was trying to navigate my content. It was not a great user experience!</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2FYbth2HC5yVSa4%2Ftwitter%2Fiframe&amp;url=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2FYbth2HC5yVSa4%2Fgiphy.gif&amp;image=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2FYbth2HC5yVSa4%2F200.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="244" frameborder="0" scrolling="no"><a href="https://medium.com/media/56fd885b7f9ab082fce72c1221f52b4b/href">https://medium.com/media/56fd885b7f9ab082fce72c1221f52b4b/href</a></iframe><p>It would be much better to have an arrow button on either side of my element (which I’m going to call <strong>container div</strong>) that allows the user to scroll through the component by clicking and disable the scrollbar completely. Getting rid of the scrollbar is as easy as changing the <strong>CSS</strong> to overflow-x: hidden; but, how could I make a button change the positioning of the content in my <strong>container div</strong>?</p><p>I decided to ask google. At first, I mostly found <strong>React</strong> packages and jQuery snippets for building carousels, but none of them actually did what I wanted. I was after a way to build it myself. Eventually, I found the <strong>Element.scrollLeft </strong>property.</p><p>According to <a href="https://developer.mozilla.org/en-US/docs/Web/API/Element/scrollLeft">MDN</a> :</p><blockquote>The <strong>Element.scrollLeft</strong> property gets or sets the number of pixels that an element&#39;s content is scrolled to the left.</blockquote><p>Exactly what I needed! I could make a button that <strong>onClick </strong>increments or decrements<strong> </strong>the container div’s <strong>scrollLeft</strong> value.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2Fpa37AAGzKXoek%2Ftwitter%2Fiframe&amp;display_name=Giphy&amp;url=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2Fpa37AAGzKXoek%2Fgiphy.gif&amp;image=https%3A%2F%2Fi.giphy.com%2Fmedia%2Fpa37AAGzKXoek%2Fgiphy.gif&amp;key=d04bfffea46d4aeda930ec88cc64b87c&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="328" frameborder="0" scrolling="no"><a href="https://medium.com/media/b482fceb5979f796ed62c2f45677e611/href">https://medium.com/media/b482fceb5979f796ed62c2f45677e611/href</a></iframe><p>Now I had a way to control the <strong>DOM</strong> element, but that was only half the battle. With <strong>React</strong> handling the <strong>DOM</strong>, I wasn’t able to grab it with any of the <strong>getElementBy</strong> functions, and there didn’t seem to be a way to access <strong>scrollLeft</strong> through my <strong>props.</strong></p><p>A little searching in the<strong> React</strong> <a href="https://reactjs.org/docs/refs-and-the-dom.html">docs</a> and I stumbled onto <strong>refs</strong>:</p><blockquote>Refs provide a way to access DOM nodes or React elements created in the render method.</blockquote><p>That sounded like exactly what I needed! I gave my <strong>container </strong>a <strong>prop</strong> of ref=&#39;scroller&#39; and then in my <strong>onClick </strong>function for my button I was able to grab the <strong>container</strong> element with this.refs.scroller. Now I had access to the element, and it’s <strong>scrollLeft </strong>property! My final <strong>onClick</strong> methods (with a little error handling) looked like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*U4XLYPapMzHlFj1fImA8KQ.png" /></figure><p>I now had two operational scroll buttons and could disable that ugly scrollbar and save my users from accidentally swiping back a page on their touchpad. I’m kind of a hero!</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2FO0oQygeklvnX2%2Ftwitter%2Fiframe&amp;url=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2FO0oQygeklvnX2%2Fgiphy.gif&amp;image=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2FO0oQygeklvnX2%2Fgiphy.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="317" frameborder="0" scrolling="no"><a href="https://medium.com/media/2351666fab5c6da8d439b1408c229440/href">https://medium.com/media/2351666fab5c6da8d439b1408c229440/href</a></iframe><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e7e409d7874e" width="1" height="1" alt=""><hr><p><a href="https://medium.com/codezillas/interacting-with-dom-elements-in-react-e7e409d7874e">Interacting With Dom Elements in React</a> was originally published in <a href="https://medium.com/codezillas">Codezillas</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[CSS Variables]]></title>
            <link>https://medium.com/codezillas/css-variables-62eba9e30e97?source=rss-2a0d8b922932------2</link>
            <guid isPermaLink="false">https://medium.com/p/62eba9e30e97</guid>
            <category><![CDATA[html5]]></category>
            <category><![CDATA[css]]></category>
            <category><![CDATA[html]]></category>
            <category><![CDATA[css3]]></category>
            <category><![CDATA[variables]]></category>
            <dc:creator><![CDATA[John Eckert]]></dc:creator>
            <pubDate>Sun, 10 Jun 2018 19:35:54 GMT</pubDate>
            <atom:updated>2018-06-11T14:41:05.775Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/500/1*0pPi1r_RM451J0woNf5BiQ.jpeg" /></figure><p>Software developers hate repetition. Just the idea of seeing some block of code written over and over again when it could be abstracted into a helper function is enough to make our skin crawl and start fights on the internet.</p><p>One place where repetition has historically been unavoidable is in <strong>CSS</strong>,<strong> </strong>but over the past few years that has been changing. A lot of new tools are being introduced that try to improve our ability to write legible, easy to read <strong>CSS</strong>. For example, preprocessors like <strong>SASS</strong> and <strong>Less </strong>allow for the use of functions and logic in <strong>CSS</strong> files, but I want to talk about something even simpler: <strong>variables</strong>.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2F13XW2MJE0XCoM0%2Ftwitter%2Fiframe&amp;url=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2F13XW2MJE0XCoM0%2Fgiphy.gif&amp;image=https%3A%2F%2Fi.giphy.com%2Fmedia%2F13XW2MJE0XCoM0%2Fgiphy.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="326" frameborder="0" scrolling="no"><a href="https://medium.com/media/f691d9747ed33e2bb40f32aafa136524/href">https://medium.com/media/f691d9747ed33e2bb40f32aafa136524/href</a></iframe><p>It’s hard to imagine a more basic step in the simplification of writing and maintaining a <strong>CSS</strong> file than variables. The addition of variables allows us to create short-hand names for shared values and to change those values globally by changing a single line of code.</p><h4>Syntax</h4><p><strong>CSS variables</strong> are easy to use and well supported. I guarantee that they will change your life.</p><ul><li>To define a variable we use:</li></ul><pre>:root {<br>   --variable-name: value;<br>}</pre><ul><li>To use the variable we use:</li></ul><pre>.my-awesome-class {<br>  var(--variable-name)<br>}</pre><h4>CSS Variables and Scope</h4><p>The documentation for <strong>CSS variables </strong>says that they should be defined inside the <strong>CSS selector </strong>that determines their scope. This means you could define a set of variables inside of a class called nav-bar and those variables would only be available inside elements of that class and their children. However, if you want to define variables to be used across your whole document, you can define them in the body selector or using the :root pseudo-selector.</p><h4>Examples</h4><p>In the following example, I have defined four color variables:</p><ul><li><strong>wave</strong> and <strong>aqua</strong> have a global scope because they are defined in :root</li><li><strong>red-orange </strong>is scoped to<strong> </strong>the first-scope<strong> </strong>class.</li><li><strong>mellow-yellow</strong> is scoped to the second-scope class.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*A1UoLVeMXqxcXp-wxUgzQg.png" /><figcaption>blogpost.css</figcaption></figure><p>In the <strong>HTML</strong> document, I have created two divs. The first relates to first-scope and the second relates to second-scope. Inside each div, there is a list which includes three items. The first is styled with a globally scoped variable. The second is styled with a variable scoped to scope-one, and the third is styled with a variable scoped to scope-two.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Fs1UrrLVyIgSyro-LeXijg.png" /><figcaption>index.html</figcaption></figure><p>Looking at the <strong>HTML</strong> page in the browser, we can see clearly how the variables are affected by the scope that they are defined in.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rwaA-qU6BKhQ8b0225KVUQ.png" /><figcaption>Page in browser</figcaption></figure><p>As we’ve seen, <strong>CSS Variables</strong> allow you to maintain a <strong>single source of truth</strong> in your <strong>CSS</strong> documents and to name key values in a logical way that is easy to read. You can even change the values of the variables using javascript!</p><p>I really like using <strong>CSS Variables</strong> for colors, because it allows me to name them in a way that I can reference more easily than tracking down the hex code or RGB statement from somewhere else in my file, but they can handle much more than just colors.</p><p>If you have a value that you are using over and over in a group of items that are related in some way, think about using a<strong> variable</strong>. By using <strong>variables</strong> you are making your code easier to maintain. When future-you goes back into the file and needs to update that padding value on all the purple text boxes, you can do so simply by updating the purple-padding variable you created (so brilliantly) when you were writing the <strong>CSS</strong>. Way to go past-you!</p><p>Another interesting thing to note, is that if you redefine a <strong>variable</strong> within a certain <strong>scope</strong> it is only redefined in that <strong>scope</strong>. We can use this to our advantage, let’s say we want to have a light and dark theme for a specific area on our page. We could create a dark class that redefines the color values of the <strong>variables</strong> and then assign that class to the specific div on a button click. This would cause only that section to change color and leave the rest of the page as it is while still using <strong>variable</strong> names to maintain the relationships of the styles on our page.</p><h4>Browser Compatability</h4><p>Some even better news is that <strong>CSS variables</strong> are <a href="https://caniuse.com/#search=css%20variables">compatible</a> with the current versions of most browsers including <strong>Chrome</strong>, <strong>Firefox</strong>, <strong>Edge</strong>, and <strong>Safari</strong>. Sadly they don’t work with <strong>IE 11</strong>, but then what does!</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2FhxjzOdufrBqJa%2Ftwitter%2Fiframe&amp;url=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2FhxjzOdufrBqJa%2Fgiphy.gif&amp;image=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2FhxjzOdufrBqJa%2Fgiphy.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="241" frameborder="0" scrolling="no"><a href="https://medium.com/media/d192c38a11c52db088470eb0f020f5aa/href">https://medium.com/media/d192c38a11c52db088470eb0f020f5aa/href</a></iframe><p><a href="https://github.com/johneckert/cssVariableBlogPost">johneckert/cssVariableBlogPost</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=62eba9e30e97" width="1" height="1" alt=""><hr><p><a href="https://medium.com/codezillas/css-variables-62eba9e30e97">CSS Variables</a> was originally published in <a href="https://medium.com/codezillas">Codezillas</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Snapshot Testing with Jest. It’s not a Joke!]]></title>
            <link>https://medium.com/codezillas/snapshot-testing-with-jest-its-not-a-joke-b00c6c82f8b3?source=rss-2a0d8b922932------2</link>
            <guid isPermaLink="false">https://medium.com/p/b00c6c82f8b3</guid>
            <category><![CDATA[jest]]></category>
            <category><![CDATA[unit-testing]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[testing]]></category>
            <category><![CDATA[front-end-development]]></category>
            <dc:creator><![CDATA[John Eckert]]></dc:creator>
            <pubDate>Sun, 03 Jun 2018 22:38:35 GMT</pubDate>
            <atom:updated>2018-06-05T13:04:24.033Z</atom:updated>
            <content:encoded><![CDATA[<h4>Getting Started Using Jest To Test Your React App</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/564/1*Z44121QNBnrO-XgNtR6KWQ.jpeg" /></figure><h3>Jest</h3><p>There are tons of different testing libraries out there, but for today I’m going to focus specifically on <a href="https://facebook.github.io/jest/">Jest</a> and React testing.</p><p>Jest is a JavaScript testing platform made by Facebook. It’s excellent for testing React, but it can also be used to test other JavaScript frameworks.</p><p>We’re going to explore how to use Jest by writing tests for a small React app that I wrote as the front end for another <a href="https://medium.com/@johnteckert/building-a-restful-api-with-go-part-1-9e234774b14d">post</a>. Here are the <a href="https://sushigo.herokuapp.com/">app</a> and the <a href="https://github.com/johneckert/sushiGo-frontend">code</a> that we will be testing.</p><h3>What To Test</h3><p>I’ve always had a bit of imposter syndrome surrounding testing. On the one hand, I can easily imagine a scenario in which I don’t write a test for something really important, and even though everything is passing, I end up accidentally breaking my app. On the other hand, I can also see myself writing tons of tests that are so fine-grained they aren’t necessary and take so much time to write that I never actually finish the project. So the first thing I wanted to figure out was, how do I find that sweet spot in the middle?</p><p>After doing some brief research, I found <a href="https://daveceddia.com/what-to-test-in-react-app/">an article</a> which lays out some totally reasonable guidelines about what to test.</p><ol><li>Does it render?</li><li>Is the output correct?</li><li>Test all states (Anything conditional should be tested)</li><li>Test all events</li><li>Test the edge cases (e.g., Are you rendering an array? what if its empty?)</li></ol><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2FB7sfAn7n9xi7u%2Ftwitter%2Fiframe&amp;url=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2FB7sfAn7n9xi7u%2Fgiphy.gif&amp;image=https%3A%2F%2Fi.giphy.com%2Fmedia%2FB7sfAn7n9xi7u%2Fgiphy.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="228" frameborder="0" scrolling="no"><a href="https://medium.com/media/788c845a2b015912d3f8fec8c89ddd50/href">https://medium.com/media/788c845a2b015912d3f8fec8c89ddd50/href</a></iframe><h3>Setting up</h3><p>To get started, we first need to install Jest:</p><pre>yarn add --dev jest</pre><p>Since we are going to want to test components we are also going to need:</p><pre>yarn add --dev react-test-renderer</pre><p>To help test our component that renders image files, we need jest-transform-stub which helps Jest deal with non-JavaScript assets.</p><pre>yarn add --dev jest-transform-stub</pre><p>If you’re using Babel you need babel-jest and babel-core:</p><pre>yarn add --dev babel-jest babel-core</pre><p>Now that we have our dependencies squared away, we need to go into the <strong>package.json</strong> file and change a few things.</p><p>To start, at the top level we need to add a “jest” key like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oRsQS8M9vxv3JfkrYMfPvA.png" /></figure><p>This is where you will put all of your config <a href="https://facebook.github.io/jest/docs/en/configuration.html">options</a>. In our case, we set verbose to <em>true</em> so that we get a display of each test when we run them. We are using moduleNameMapper in conjunction with jest-transform-stub, which we installed earlier, to mock our image files when testing any components that contain images.</p><p>Next, we need to change the value of &quot;test&quot; to &quot;jest&quot; in “scripts”. Mine looks like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2s9ad9EFXt4rDsmFZKsXdg.png" /></figure><p>For reference, my <strong>package.json</strong> file ended up looking like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pYn-U-x2Bdr80ykBqe_nSA.png" /></figure><p>Before I start writing any tests, I’m going to create a __<strong>test__</strong> folder inside <strong>src,</strong> and then I’ll build a separate file for each component that includes all the tests for that component. The name of the folder is important for Jest to function correctly.</p><h3>Writing the Tests</h3><p>The structure of tests in Jest is pretty straightforward. There is a test() method that you call every time you want to test something. It takes two arguments; The first is a string that describes what we are testing — this is for humans and gets printed to the terminal when you run the test. It mainly functions as a label. The second argument is a callback that contains the logic for the actual test.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IIkaMNJ4CMDnRv7A2QUA_w.png" /></figure><p>In the example above, we can get a pretty good idea of how our tests will be written. Inside the callback, we call expect and pass it the thing that we are testing. We chain another function, called a <strong>matcher</strong>, to the expect (in this case toBe()) which takes the desired outcome as it’s argument. There are a lot of different <a href="https://facebook.github.io/jest/docs/en/expect.html"><strong>matchers</strong></a> to choose from, based on the thing you are trying to test.</p><p>There is another syntax we can use which works the same way. We can call describe() just like we were calling test()and pass it arguments with the same structure. Inside of the callback, we can nest it() which also takes the same syntax as test().</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*slnIltx4nIqH4zIQSlCiWQ.png" /></figure><p>The choice between the two seems to be mostly stylistic. Describe allows you to nest and group your tests. However, if the indentation is getting out of control you can just use test().</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2Fd2VNDNckZ1OQWbN6%2Ftwitter%2Fiframe&amp;url=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2Fd2VNDNckZ1OQWbN6%2Fgiphy.gif&amp;image=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2Fd2VNDNckZ1OQWbN6%2Fgiphy.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="331" frameborder="0" scrolling="no"><a href="https://medium.com/media/a9467b3842848a475bed7b2aaf5c15db/href">https://medium.com/media/a9467b3842848a475bed7b2aaf5c15db/href</a></iframe><h3>Snapshot Testing</h3><p>Snapshot testing is exactly what you think it is. The first time the test is run, Jest creates a ‘snapshot file’ that it will compare your code against in the future. On future runs of the test, Jest will compare the output with the previous snapshot. If they match, you pass!</p><p>This does mean that if you change the structure of your component, you will need to update that snapshot file, which you can do with the following command:</p><pre>jest --updateSnapshot</pre><p>To test our React app, we use the react-test-renderer package that we installed earlier. It allows us to render our component and set it equal to a variable that we can then pass to our tests.</p><p>At the top of our test file, we need to import React, the component to be tested and TestRenderer. Let’s start with the CardBack component.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OK2xXGBbAwt2h2mpccQTyA.png" /></figure><p>Since we need to pass CardBack a roll object as a prop, we should also create a fake one.</p><p>Then we use the create() method from react-test-renderer to render the component for testing and set it equal to a variable. Our first test can check that the component renders correctly by using the .toMatchSnapshot() matcher to compare it to the snapshot.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iehcC0FXNzGzirMqiAuqPQ.png" /><figcaption>cardBack.test.js</figcaption></figure><p>If we run our test from the command line using</p><pre>yarn test</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FM5M0OmZivp8pv-Imlrmqg.png" /></figure><p>It passes! So our component is rendering as expected. Since this is a pretty basic component, that’s probably all of the testing it requires for the moment. Since, we already included all of that mumbo-jumbo for mocking images, we can test the CardFront in almost exactly the same way.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VfhenHp2DlO3O-Fk6n7fcw.png" /><figcaption>cardFront.test.js</figcaption></figure><p>Nav is even simpler since it doesn’t require any props.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kCUwAKrw81elvvBAa0eS6g.png" /><figcaption>nav.test.js</figcaption></figure><p>Let’s see how we are doing:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wVO0OrVXUQUCf4lP5601EQ.png" /></figure><p>We’ve gotten our test suite set up and built simple tests for our three basic components. Next time we can tackle the container components and look at how to test components with state and asynchronous functions like fetch requests!</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2F147wM034XXNvSE%2Ftwitter%2Fiframe&amp;url=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2F147wM034XXNvSE%2Fgiphy.gif&amp;image=https%3A%2F%2Fi.giphy.com%2Fmedia%2F147wM034XXNvSE%2Fgiphy.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="297" frameborder="0" scrolling="no"><a href="https://medium.com/media/da0d22c26ff0972872fd4dc8f4ee6f71/href">https://medium.com/media/da0d22c26ff0972872fd4dc8f4ee6f71/href</a></iframe><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b00c6c82f8b3" width="1" height="1" alt=""><hr><p><a href="https://medium.com/codezillas/snapshot-testing-with-jest-its-not-a-joke-b00c6c82f8b3">Snapshot Testing with Jest. It’s not a Joke!</a> was originally published in <a href="https://medium.com/codezillas">Codezillas</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How To Make A Ruby Gem]]></title>
            <link>https://medium.com/codezillas/how-to-make-a-ruby-gem-79938dfeef58?source=rss-2a0d8b922932------2</link>
            <guid isPermaLink="false">https://medium.com/p/79938dfeef58</guid>
            <category><![CDATA[object-oriented]]></category>
            <category><![CDATA[rspec]]></category>
            <category><![CDATA[gem]]></category>
            <category><![CDATA[ruby]]></category>
            <category><![CDATA[rubygems]]></category>
            <dc:creator><![CDATA[John Eckert]]></dc:creator>
            <pubDate>Thu, 24 May 2018 14:52:03 GMT</pubDate>
            <atom:updated>2018-05-30T19:44:09.871Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1023/1*rKaHHbizmV9uLg5jqnxSpw.jpeg" /></figure><p>Ruby Gems are awesome! They allow us to add little bits of functionality to our projects without having to waste time reinventing the wheel. The great thing about them is that anybody can make one… and here’s how!</p><h4>Step 1— The Basics</h4><p>To begin, you will need two things a <a href="http://www.rubygems.org/">RubyGems</a> account and an idea of what you want your gem to do.</p><p>What makes a good gem? A great place to start is to try to think of anything you find yourself repeatedly implementing in multiple projects.</p><p>I decided to make a gem that contained functions for rolling different combinations of dice in the style of tabletop RPGs. It will allow users to phrase the arguments to the dice rolling methods exactly how they would speak them. For example, to roll two six-sided dice, the user will be able to enter &#39;2d6&#39;as the argument to the dice rolling method. My gem is probably not going to change the world, but it seemed like a decent amount of functionality for a trial run.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2FTdyBBKxX139sY%2Ftwitter%2Fiframe&amp;url=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2FTdyBBKxX139sY%2Fgiphy.gif&amp;image=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2FTdyBBKxX139sY%2Fgiphy.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="244" frameborder="0" scrolling="no"><a href="https://medium.com/media/995ac25b6130339e5abcd002e59b4650/href">https://medium.com/media/995ac25b6130339e5abcd002e59b4650/href</a></iframe><h4>Step 2 — Naming</h4><p>You’ll want to consider how users will access the different methods in your gem. This means developing a good naming structure for the gem itself, your files and your classes.</p><p>Gems all have to have unique names, so once you have an idea of what you want to call your gem, it’s a good idea to check <a href="http://www.rubygems.org/">RubyGems</a> and make sure that there isn’t already a gem with that name. In my case there are already a bunch of dice rolling gems, so most of the names involving the word dice were taken. I decided to call my gem <em>Nat20</em>, which is again a reference to table top RPGs, and rolling a 20 on a twenty-sided die<em>.</em></p><h4>Step 3 —Directory &amp; File Structure</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mRoagGe293fot2DwV3tzXQ.png" /><figcaption>Basic File Structure for Ruby Gem</figcaption></figure><p>The picture above is the basic file structure for our gem. All we need to get started is a gemspec file and a lib folder to contain the ruby file (or files) with our code in it.</p><p>In the case of my silly little gem we just have a nat20.rb file which contains a Nat20 class. The class contains two methods that are accessible by the user and a bunch of private methods for pulling relevant information out of the arguments entered by the user.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wFwt-39hpG3oEoTRAH01IA.png" /><figcaption>nat20.rb</figcaption></figure><h4>Step 4 — Gemspec</h4><p>The gemspec file is what defines things like the description of the gem, who made it, the version, and other information that gets packaged with the gem. It communicates directly with <a href="http://www.rubygems.org/">rubygems.org</a>. The gemspec file is written in Ruby, which is great because it means you can insert code into it to automate certain actions, like changing the version number, release date, or anything else you need to do.</p><p>The gemspec also excepts a large variety of attributes. Some of them are required, but many are optional. A full list of attributes is available <a href="https://guides.rubygems.org/specification-reference/">here</a>.</p><p>The required attributes are:</p><ul><li><strong>files</strong></li><li><strong>name</strong></li><li><strong>summary</strong></li><li><strong>version</strong></li></ul><p>There is also a list of recommended attributes. These include:</p><ul><li><strong>author= </strong>or<strong> authors=</strong></li><li><strong>description</strong></li><li><strong>email</strong></li><li><strong>homepage</strong></li><li><strong>license= </strong>or<strong> licenses=</strong></li><li><strong>metadata</strong></li></ul><p>Once you’ve got your gemspec file built, you can create your gem and test it out locally!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kUdl6B52VHk6Ycpwq2LFaQ.png" /><figcaption>nat20.gemspec</figcaption></figure><h4>Step 5 — Building</h4><p>At this point, we have everything we need for working gem. Let’s build it!</p><pre>gem build nat20.gemspec</pre><p>If it all works as planned you should see something like:</p><pre><em>Successfully built RubyGem<br>Name: nat20<br>Version: 0.0.0<br>File: nat20-0.0.0.gem</em></pre><p>You should also see a .gem file in your root directory. Now the gem can be installed locally.</p><pre>gem install ./nat20-0.0.0.gem</pre><pre><em>Successfully installed hola-0.0.0<br>1 gem installed</em></pre><p>With our new gem installed on the local machine, we can start testing.</p><p>The next step is to start <strong>irb </strong>and see if the gem is working.</p><pre>irb<br>&gt; require &#39;nat20&#39;<br><em>=&gt; true<br>&gt; Nat20.roll &#39;2d4+2&#39;<br>=&gt; 8</em></pre><p>Awesome! It seems to be working just fine.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2F3oriNPdeu2W1aelciY%2Ftwitter%2Fiframe&amp;display_name=Giphy&amp;url=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2F3oriNPdeu2W1aelciY%2Fgiphy.gif&amp;image=https%3A%2F%2Fi.giphy.com%2Fmedia%2F3oriNPdeu2W1aelciY%2Fgiphy.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="244" frameborder="0" scrolling="no"><a href="https://medium.com/media/58d8585506877dd5bdacc8c401c1da36/href">https://medium.com/media/58d8585506877dd5bdacc8c401c1da36/href</a></iframe><h4>Step 6-Testing</h4><p>Testing is essential for gems. Not only does it ensure that our gem is working correctly and that it continues to do so, but it let’s other developers know that our gem does what it says it does. So in short, if you want other people to use your gem — <strong>Write Tests!!</strong></p><p>I decided to use <strong>RSpec</strong> to write tests for my gem, so I needed to add a few things to get it working.</p><ol><li>We need to add the <strong>Rspec</strong> gem as a dependency. We do that by adding the following line to the gemfile.</li></ol><pre>s.add_development_dependency &#39;rspec&#39;, &#39;~&gt; 3.7&#39;</pre><p>2. Next, we need to create a <strong>Rakefile </strong>to do that we can create a new file called Rakefile and put the following code in it, which tells <strong>RSpec</strong> where to look for the tests:</p><pre>require &#39;rspec/core/rake_task&#39;<br>require &#39;bundler/gem_tasks&#39;</pre><pre># Default directory to look in is `/spec`<br>RSpec::Core::RakeTask.new(:spec)</pre><pre>task :default =&gt; :spec</pre><p>3. We should also add a Gemfile that specifies our <strong>RSpec</strong> dependency which should contain the following:</p><pre># frozen_string_literal: true</pre><pre>source &quot;<a href="https://rubygems.org/">https://rubygems.org</a>&quot;</pre><pre>git_source(:github) {|repo_name| &quot;<a href="https://github.com/#{repo_name">https://github.com/#{repo_name</a>}&quot; }</pre><pre># gem &quot;rails&quot;<br>gem &#39;rspec&#39;, :require =&gt; &#39;spec&#39;</pre><p>4. Now, all we need to do is create a spec folder in the root directory of our project and create a test file inside of it. Now we can run bundle install, and our file structure should look like this.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_c4W3AgQJVpo6Kgt28CWFQ.png" /></figure><p>After writing the tests and making sure everything works as expected, we can rebuild our gem using the gem build command like we did previously and get ready to publish it!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dc8ntAdJhEGLzkNYq0kc1g.png" /><figcaption>nat20_spec.rb</figcaption></figure><h4>Step 7-Uploading</h4><p>Now that we have a fully functional gem, it’s time to upload it! To upload the gem to RubyGems, we can use the push command in the terminal.</p><pre>gem push nat20-0.0.0.gem</pre><p>You’ll be prompted for your email and password, and once you do that your gem will be registered, and everyone will be able to use your code!</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2F72MpAs1yuYRxK%2Ftwitter%2Fiframe&amp;url=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2F72MpAs1yuYRxK%2Fgiphy.gif&amp;image=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2F72MpAs1yuYRxK%2Fgiphy.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="326" frameborder="0" scrolling="no"><a href="https://medium.com/media/499eb8662f9ddcd76a32e4b9e82aa8ec/href">https://medium.com/media/499eb8662f9ddcd76a32e4b9e82aa8ec/href</a></iframe><ul><li><a href="https://rubygems.org/">RubyGems.org | your community gem host</a></li><li><a href="https://rubygems.org/gems/nat20">nat20 | RubyGems.org | your community gem host</a></li><li><a href="https://github.com/johneckert/nat20">johneckert/nat20</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=79938dfeef58" width="1" height="1" alt=""><hr><p><a href="https://medium.com/codezillas/how-to-make-a-ruby-gem-79938dfeef58">How To Make A Ruby Gem</a> was originally published in <a href="https://medium.com/codezillas">Codezillas</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Closures]]></title>
            <link>https://medium.com/@johnteckert/closures-43aeb6287897?source=rss-2a0d8b922932------2</link>
            <guid isPermaLink="false">https://medium.com/p/43aeb6287897</guid>
            <category><![CDATA[closure]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[functional-programming]]></category>
            <category><![CDATA[computer-science]]></category>
            <category><![CDATA[object-oriented]]></category>
            <dc:creator><![CDATA[John Eckert]]></dc:creator>
            <pubDate>Fri, 18 May 2018 13:50:03 GMT</pubDate>
            <atom:updated>2018-05-18T13:50:03.960Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dZCKWQCZcI7ZXym3PmYr_A.jpeg" /></figure><p>Closures are an essential part of JavaScript that, for me at least, are easy to understand but tricky to explain well. Unfortunately, they come up a lot in job interviews, so I thought it was time to take a deeper dive into what closures are and why they are important.</p><h4>What Are They?</h4><p>According to <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Closures">MDN</a>, a <em>closure</em> is the combination of a function and the lexical environment within which that function was declared.</p><p>What does that mean? When you declare a function inside of another function, the inner function has access to its own scope, as well as the scope of the outer function. In other words, the inner function will still have access to any local variables that were in-scope at the time of creation, even though those variables may not be in scope when that function is called.</p><h4>How Do You Use Them?</h4><p>To use a closure, all you have to do is define a function within another function and then return it, or pass it as an argument to another function so that it can be used outside of the context it where it was defined.</p><h4>What Are They Good For?</h4><p>Closures allow us to do a lot of handy things. Here are a few examples:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6rR2iyiW8CeinZkbRO3rsQ.png" /><figcaption>Data Privacy</figcaption></figure><p><strong>Data Privacy. </strong>Closures are one of the primary ways to make data private in JavaScript. When you use a closure to wrap a variable, that variable is only accessible inside the outer function. The only way to access that data from somewhere else in your code is by creating a function inside the outer function that has access.</p><p>Because myData is created inside a closure, it can’t be manipulated from outside of outerFunction(). The only way it is accessible is through the inner function.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wyeDnrunjB99AwF9ueRhCQ.png" /><figcaption>State</figcaption></figure><p><strong>State.</strong> Closures are essential for creating objects that have state. Just like in the private data example above, if we create a variable in the outer function we can manipulate it with inner functions and use it to keep track of the state of an object.</p><p>In the example above, we create a simple counter that uses a variable called state to keep track of what number we are on. In this case the outer function returns an object with three functions in it that allow us to manipulate the state of our counter in different ways.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yEA4Ql3ehy_dive1Ll8Fdw.png" /><figcaption>Factory Functions</figcaption></figure><p><strong>Factory Functions. </strong>Another useful aspect of closures is how they can be used to create factory functions. A factory function is a function that returns other functions.</p><p>In this case, we’ve used a closure to create a function that outputs a bunch of new functions with variations based on the argument we pass to the factory function. This allows us to create a bunch of functions dynamically with just a few lines of code.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2FUyZX0WLJW8ola%2Ftwitter%2Fiframe&amp;url=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2FUyZX0WLJW8ola%2Fgiphy.gif&amp;image=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2FUyZX0WLJW8ola%2Fgiphy.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="243" frameborder="0" scrolling="no"><a href="https://medium.com/media/55a160d768a9345ef4b628e057464567/href">https://medium.com/media/55a160d768a9345ef4b628e057464567/href</a></iframe><p>So closures can be pretty magical and it turns out…. Understanding them allows you to do some extremely powerful things.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=43aeb6287897" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>