<?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 Matthew Sedlacek on Medium]]></title>
        <description><![CDATA[Stories by Matthew Sedlacek on Medium]]></description>
        <link>https://medium.com/@sedlacek1991?source=rss-d4a2efb0f7fe------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*YrKv7xvrCXCgaF7t8mHFKg.jpeg</url>
            <title>Stories by Matthew Sedlacek on Medium</title>
            <link>https://medium.com/@sedlacek1991?source=rss-d4a2efb0f7fe------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 21 Nov 2026 05:15:30 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@sedlacek1991/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[Go: Primitives]]></title>
            <link>https://towardsdev.com/go-primitives-560c069d98ad?source=rss-d4a2efb0f7fe------2</link>
            <guid isPermaLink="false">https://medium.com/p/560c069d98ad</guid>
            <category><![CDATA[primitive-data-types]]></category>
            <category><![CDATA[golang]]></category>
            <category><![CDATA[golang-development]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[go]]></category>
            <dc:creator><![CDATA[Matthew Sedlacek]]></dc:creator>
            <pubDate>Thu, 07 Jan 2021 17:10:15 GMT</pubDate>
            <atom:updated>2021-03-31T22:07:34.274Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*-dq3Yw5wM8hnvOJQ" /><figcaption>Photo by <a href="https://unsplash.com/@kai_wenzel?utm_source=medium&amp;utm_medium=referral">Kai Wenzel</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>In my previous blog, we discussed <a href="https://sedlacek1991.medium.com/go-variables-9390144e25d2">variables</a> in Go. Here we will discuss the basic data types in Go; boolean, numeric, and text. These data types are also known collectively as primitives and are built into Go’s compiler.</p><p><em>**Some examples and overall structure of this blog come from Free Code Camp’s “Learn Go Programming — Golang Tutorial for Beginners” course on </em><a href="https://www.youtube.com/watch?v=YS4e4q9oBaU&amp;t=2147s"><em>YouTube</em></a><em>. **</em></p><h4>Boolean</h4><p>Booleans are common in programming languages and represent a value of either true or false. Booleans can be written a few different ways in Go. Below we can see an example of where we can create a variable with the boolean data type.</p><pre>package main</pre><pre>import (</pre><pre>     &quot;fmt&quot;</pre><pre>)</pre><pre>func main() {</pre><pre><strong>     var a bool = true</strong></pre><pre><strong>     var b bool = false</strong></pre><pre>// Variables in Go are assigned 0 values unless you explicitly set them like above. The 0 value for a boolean is false</pre><pre><strong>     var c bool </strong></pre><pre>     fmt.Printf(&quot;%v, %T\n&quot;, a, a)</pre><pre>     fmt.Printf(&quot;%v, %T\n&quot;, b, b)</pre><pre>     fmt.Printf(&quot;%v, %T\n&quot;, c, c)</pre><pre>}</pre><pre>Output: </pre><pre>true, bool<br>false, bool<br>false, bool</pre><p>Booleans are also used in logic tests. In the example below, we set variable a equal to 7 =7, which is true, and set variable b equal to 4 = 7, which is false.</p><pre>package main</pre><pre>import (</pre><pre>     &quot;fmt&quot;</pre><pre>)</pre><pre>func main() {</pre><pre>     a := 7 == 7</pre><pre>     b := 4 == 7</pre><pre>     fmt.Printf(&quot;%v, %T\n&quot;, a, a)</pre><pre>     fmt.Printf(&quot;%v, %T\n&quot;, b, b)</pre><pre>}</pre><pre>Output:</pre><pre>true, bool<br>false, bool</pre><h4>Numeric</h4><p>There are various types to represent numbers in Go. However, we can group them into the following major categories:</p><ol><li>Integers</li><li>Floating point</li><li>Complex Numbers</li></ol><p><strong>Integers</strong></p><p>If you remember back to math class, integers are whole numbers that do not include a decimal. The same is true for integers in Go. In my previous blog regarding <a href="https://sedlacek1991.medium.com/go-variables-9390144e25d2">variables</a>, I demonstrated a few ways to create integer variables, like the example shown below.</p><pre>package main</pre><pre>import (</pre><pre>     &quot;fmt&quot;</pre><pre>)</pre><pre>func main() {</pre><pre>     var i int = 16</pre><pre>     fmt.Printf(&quot;%v, %T\n&quot;, i, i)</pre><pre>}</pre><pre>16, int</pre><p>Integers in Go can be broken down further into two types; signed and unsigned. The int above is a signed integer, which means that it can have positive and negative values. Unsigned integers differ in that they can only be positive numbers or 0. There are many different signed and unsigned integer types and what separates them is the number ranges they can handle. See below for a summary table of all the different types.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_pivWa6TIHDOSkh9fWhR7A.png" /><figcaption>Value ranges are approximate and provided by “Learn Go Programming — Golang Tutorial for Beginners”</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YrqtcK04CRahACGO5o4zoQ.png" /><figcaption>Value ranges are approximate and provided by “Learn Go Programming — Golang Tutorial for Beginners”</figcaption></figure><p>**Note: If your value is outside the number range, you will receive a “constant overflows” error message**</p><p><strong>Floating Point</strong></p><p>Unlike Integers, floating point numbers include decimals. There are two types of floating point numbers, float32 and float64, and similar to the int types are used depending on the size/level of precision your application requires. Please note, the default value for numbers with a decimal in Go will initialize as a float64 .</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/608/1*N7KtP_fgXXPkQckfmXtWHw.png" /><figcaption>Value ranges provided by “Learn Go Programming — Golang Tutorial for Beginners”</figcaption></figure><p>See below for examples of working with integers and floating point numbers in Go.</p><pre>package main</pre><pre>import (</pre><pre>     &quot;fmt&quot;</pre><pre>)</pre><pre>func main() {</pre><pre>// <strong>Integers:</strong> Example below shows type conversion</pre><pre>     var a int = 10</pre><pre>     var b int8 = 3</pre><pre>     fmt.Println(a + int(b))</pre><pre><strong>     // Operations available to Integers</strong></pre><pre><strong>        // Arithmetic</strong></pre><pre>          e := 7</pre><pre>          f := 4</pre><pre>          fmt.Println(e + f)</pre><pre>          fmt.Println(e - f)</pre><pre>          fmt.Println(e * f)</pre><pre>          fmt.Println(e / f)</pre><pre>          fmt.Println(e % f) // % is the modulo operator and shows<br>          the remainder of integer division</pre><pre><strong>       // Bit Operators (watch video for further explanation -<br>       </strong><a href="https://www.youtube.com/watch?v=YS4e4q9oBaU"><strong>https://www.youtube.com/watch?v=YS4e4q9oBaU</strong></a><strong>) - ~ 1 hour mark</strong></pre><pre>          fmt.Println(e &amp; f)</pre><pre>          fmt.Println(e | f)</pre><pre>          fmt.Println(e ^ f)</pre><pre>          fmt.Println(e &amp;^ f)</pre><pre><strong>       // Bit Shifting Operators (watch video for further<br>       explanation - </strong><a href="https://www.youtube.com/watch?v=YS4e4q9oBaU"><strong>https://www.youtube.com/watch?v=YS4e4q9oBaU</strong></a><strong>) - <br>       ~ 1 hour mark</strong></pre><pre>          fmt.Println(e &lt;&lt; 4)</pre><pre>          fmt.Println(e &gt;&gt; 4)</pre><pre>// <strong>Floating point:</strong> In the below example n = 13.7e72 is too large for a float32</pre><pre>     var n float64 = 3.14</pre><pre>     n = 13.7e72</pre><pre>     n = 2.1e14</pre><pre>     fmt.Printf(&quot;%v, %T\n&quot;, n, n)</pre><pre><strong>     // Operations available to Floating Point</strong></pre><pre><strong>       // Arithmetic </strong></pre><pre>          c := 9.7</pre><pre>          d := 4.8</pre><pre>          fmt.Println(c + d)</pre><pre>          fmt.Println(c - d)</pre><pre>          fmt.Println(c * d)</pre><pre>          fmt.Println(c / d)</pre><pre>}</pre><pre>Output:</pre><pre><strong>// Integer Type Conversion</strong><br>13</pre><pre><strong>// Integer Arithmetic</strong><br>11<br>3<br>28<br>1<br>3</pre><pre><strong>// Integer Bit Operators</strong><br>4<br>7<br>3<br>3</pre><pre><strong>// Integer Bit Shifting</strong><br>112<br>0</pre><pre><strong>// Floating Point</strong><br>2.1e+14, float64</pre><pre><strong>// Floating Point Arithmetic</strong> <br>14.5<br>4.8999999999999995<br>46.559999999999995<br>2.0208333333333335</pre><p><strong>Complex Numbers</strong></p><p>The last number category we will discuss is complex numbers. Complex Numbers are defined as “… any number that can be written as a+bi, where i is the imaginary unit and a and b are real numbers” (Khan Academy). There are two types of complex numbers we can use in Go complex64 and complex128 . You may be asking yourself why 64 and 128? The reason is that in a complex64, we are adding together real and imaginary numbers that have a type offloat32 , 32 + 32 = 64, and in complex128, we are adding together real and imaginary numbers that have a type offloat64 , 64+64 =128. See below for of few examples of how we can use complex numbers.</p><pre>package main</pre><pre>import (</pre><pre>     &quot;fmt&quot;</pre><pre>)</pre><pre>func main() {</pre><pre><strong>// Simple Example</strong></pre><pre>     var n complex64 = 4i</pre><pre>     fmt.Printf(&quot;%v, %T\n&quot;, n, n)</pre><pre><strong>// Arithmetic Operations</strong></pre><pre>     a := 4 + 2i</pre><pre>     b := 7 + 1.9i</pre><pre>     fmt.Println(a + b)</pre><pre>     fmt.Println(a - b)</pre><pre>     fmt.Println(a * b)</pre><pre>     fmt.Println(a / b)</pre><pre><strong>// Splitting apart Real and Imaginary Parts using built-in functions</strong></pre><pre>     var c complex64 = 2 + 4i</pre><pre>     fmt.Printf(&quot;%v, %T\n&quot;, real(c), real(c))</pre><pre>     fmt.Printf(&quot;%v, %T\n&quot;, imag(c), imag(c))</pre><pre><strong>// Make a complex number using complex function. First input in complex function is the real number and the second is the imaginary</strong></pre><pre>     var m complex128 = complex(2, 4)</pre><pre>     fmt.Printf(&quot;%v, %T\n&quot;, m, m)</pre><pre>}</pre><pre>Output:</pre><pre><strong>// Simple Example</strong><br>(0+4i), complex64</pre><pre><strong>// Arithmetic Operations</strong><br>(11+3.9i)<br>(-3+0.10000000000000009i)<br>(24.2+21.6i)<br>(0.6044478236076791+0.12164987644934423i)</pre><pre><strong>// Splitting apart Real and Imaginary Parts</strong><br>2, float32<br>4, float32</pre><pre><strong>// Using Complex function to make a complex number</strong><br>(2+4i), complex128</pre><h4>Text</h4><p>The built-in data type for text in Go is strings. Moreover, Go defines strings as “any UTF-8 character”(freecodecamp.org). For a complete list of UTF-8 characters, see <a href="https://www.fileformat.info/info/charset/UTF-8/list.htm">here</a>. We saw strings in my <a href="https://sedlacek1991.medium.com/go-variables-9390144e25d2">last blog</a> when discussing block variables. However, let’s make it a little simpler, here we’ll create a variable str, set it equal to “Hello, Medium!”, and print its value and type.</p><pre>package main</pre><pre>import (</pre><pre>     &quot;fmt&quot;</pre><pre>)<br></pre><pre>func main() {</pre><pre>     str := &quot;Hello, Medium!&quot;</pre><pre>     fmt.Printf(&quot;%v, %T\n&quot;, str, str)</pre><pre>}</pre><pre>Output:</pre><pre>Hello, Medium!, string</pre><p>When working with strings, you may need to find the value of a certain letter in a string or combine string variables.</p><p>Let’s first take a look at finding the value of a certain letter in a string. In Go, each character in a string has an index with the first character starting at 0 and includes spaces. In our “Hello, Medium!” example, to print the letter “o” we could change our print statement above to fmt.Printf(&quot;%v\n&quot;, str[4]). However, this doesn’t give us exactly what we need. In Go, strings are aliases for bytes, and the print statement above will give us the unicode value for “o” which is 111. So, to output “o” we need to change our print statement to include a string conversion fmt.Printf(&quot;%v\n&quot;, string(s[4])) .</p><p>To combine strings, we can use what is called concatenation. Which is simply using the addition operator to add the strings together. See below for an example.</p><pre>package main</pre><pre>import (</pre><pre>     &quot;fmt&quot;</pre><pre>)</pre><pre>func main() {</pre><pre>     str1 := &quot;This is a&quot;</pre><pre>     str2 := &quot; &quot;</pre><pre>     str3 := &quot;string&quot;</pre><pre>     fmt.Printf(&quot;%v\n&quot;, str1+str2+str3)</pre><pre>}</pre><pre>Output:</pre><pre>This is a string</pre><p>Thank you for taking the time to learn more about the primitive data types in Go. Keep an eye out for upcoming Go blogs, where we will continue our exploration of this incredible programming language.</p><h4>Resources</h4><p>“Learn Go Programming — Golang Tutorial for Beginners.” <em>YouTube</em>, <a href="http://https//Www.freecodecamp.org/,">freecodecamp.org,</a> 20 June 2019, <a href="http://www.youtube.com/watch?v=YS4e4q9oBaU.">www.youtube.com/watch?v=YS4e4q9oBaU.</a></p><p>Doxsey, Caleb. <em>An Introduction to Programming in Go</em>. CreateSpace, 2012.</p><p>“Intro to Complex Numbers (Article).” <em>Khan Academy</em>, Khan Academy, <a href="http://www.khanacademy.org/math/algebra2/x2ec2f6f830c9fb89:complex/x2ec2f6f830c9fb89:complex-num/a/intro-to-complex-numbers.">www.khanacademy.org/math/algebra2/x2ec2f6f830c9fb89:complex/x2ec2f6f830c9fb89:complex-num/a/intro-to-complex-numbers.</a></p><p>“Go Type System Overview.” <em>Go Type System Overview — Go 101: an Online Go Programming Book + Knowledge Base</em>, go101.org/article/type-system-overview.html.</p><p>“Primitive Data Type.” <em>Wikipedia</em>, Wikimedia Foundation, 3 Jan. 2021, en.wikipedia.org/wiki/Primitive_data_type.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=560c069d98ad" width="1" height="1" alt=""><hr><p><a href="https://towardsdev.com/go-primitives-560c069d98ad">Go: Primitives</a> was originally published in <a href="https://towardsdev.com/">Towards Dev</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Go: Variables]]></title>
            <link>https://sedlacek1991.medium.com/go-variables-9390144e25d2?source=rss-d4a2efb0f7fe------2</link>
            <guid isPermaLink="false">https://medium.com/p/9390144e25d2</guid>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[golang]]></category>
            <category><![CDATA[go]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[web-development]]></category>
            <dc:creator><![CDATA[Matthew Sedlacek]]></dc:creator>
            <pubDate>Mon, 04 Jan 2021 01:08:06 GMT</pubDate>
            <atom:updated>2021-01-27T05:49:01.735Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*yO971OwgLrIbBgrz" /><figcaption>Photo by <a href="https://unsplash.com/@mitchel3uo?utm_source=medium&amp;utm_medium=referral">Mitchell Luo</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h4>Overview of Go</h4><p>Go was created in 2009 by Robert Griesemer, Rob Pike, and Ken Thompson at Google. Go is an open-source, statically typed, compiled language and is commonly referred to as Golang. Some of Go’s key benefits include “…memory safety, garbage collection, structural typing, and CSP-style concurrency” (Built In).</p><p>This blog is designed to show how to work with variables in Go and will cover the following topics:</p><ol><li>Declaring variables</li><li>Redeclaring variables</li><li>Shadowing</li><li>Naming variables</li><li>Scope</li><li>Converting data types</li><li>Constants</li></ol><p><em>**Some examples and overall structure of this blog come from Free Code Camp’s “Learn Go Programming — Golang Tutorial for Beginners” course on </em><a href="https://www.youtube.com/watch?v=YS4e4q9oBaU&amp;t=2147s"><em>YouTube</em></a><em>. **</em></p><h4>Declaring Variables</h4><p>If we wanted to declare a variable called i that has integer as its type, we could write the following.</p><pre>package main</pre><pre>import (</pre><pre>     &quot;fmt&quot;</pre><pre>)</pre><pre>func main() {</pre><pre><strong>     var i int</strong></pre><pre>}</pre><p>Next, to assign this variable to an integer of 16 and print that variable to the console, we could write the below variable declaration. We’ll call declaring variables like this the multi-line approach.</p><pre>package main</pre><pre>import (</pre><pre>     &quot;fmt&quot;</pre><pre>)</pre><pre>func main() {</pre><pre>     var i int<strong><br>     i = 16<br>     fmt.Println(i)</strong></pre><pre>}</pre><pre>// Terminal command to run this program is go run main.go</pre><pre>Output: 16</pre><h4>Other Ways to Declare Variables</h4><p>Another way to write the above variable declaration would be to put everything on a single line. We’ll call declaring variables like this the single-line approach.</p><pre>package main</pre><pre>import (</pre><pre>     &quot;fmt&quot;</pre><pre>)</pre><pre>func main() {</pre><pre><strong>     var i int = 16</strong></pre><pre>     fmt.Println(i)</pre><pre>}</pre><pre>// Terminal command to run this program is go run main.go</pre><pre>Output: 16</pre><p>Lastly, Go’s compiler is able to determine i’s data type based on the value we are setting i equal to with “:=”. In the example below, i will have a data type of integer. We’ll call declaring variables like this the colon-equals approach.</p><pre>package main</pre><pre>import (</pre><pre>&quot;fmt&quot;</pre><pre>)</pre><pre>func main() {</pre><pre><strong>     i := 16</strong></pre><pre>     fmt.Println(i)</pre><pre>}</pre><pre>// Terminal command to run this program is go run main.go</pre><pre>Output: 16</pre><h4>When to use each type of variable declaration</h4><p>Now that we know that there are multiple ways to declare variables; multi-line, single-line, and colon-equals approaches. We should discuss when to use each type.</p><p>The multi-line approach is useful when you want to declare a variable but don’t want to initialize it. For example, the value of the variable is being assigned in a for loop later in the function, and making it equal to something outside the loop is unnecessary.</p><p>The single-line approach should be used when Go doesn’t have enough information to assign your desired data type. For example, say that we want our i variable from before to be a float32 instead of an integer. We could simply change our variable declaration to var i float32 = 16 . Declaring variables in this way provides us with more control. It is also worth noting that if we are declaring variables at the package level we need to use this type of syntax because the colon-equals approach is not allowed by Go for package level variables.</p><p>The colon-equals approach is the least verbose approach and should be used within our functions when Go’s compiler is able to determine the correct data type of the variable.</p><pre>package main</pre><pre>import (</pre><pre>      &quot;fmt&quot;</pre><pre>)</pre><pre>func main() {</pre><pre><strong>// multi-line approach: useful for for loops</strong></pre><pre>     var i int</pre><pre>     i = 14</pre><pre><strong>// single-line: useful for when you need control over the data type</strong></pre><pre>     var j float32 = 15</pre><pre><strong>// colon-equals: least verbose, use when Go&#39;s compiler is able to determine data type</strong></pre><pre>     k := 16</pre><pre>     fmt.Println(i)</pre><pre>// print statements for displaying value and type</pre><pre>     fmt.Printf(&quot;%v, %T&quot;, j, j)</pre><pre>     fmt.Printf(&quot;%v, %T&quot;, k, k)</pre><pre>}</pre><pre>Output: </pre><pre>14<br>15, float32<br>16, int</pre><h4>Block Variables</h4><p>At the package level, we can also assign multiple variables together in a block. Notice how in the block, we don’t need to type the var keyword in front of each variable name. We can also assign multiple blocks at the package level. Creating block variables is useful when we want to show that certain variables are related to each other. See below for an example.</p><pre>package main</pre><pre>import &quot;fmt&quot;</pre><pre>var (</pre><pre>     playerName    string  = &quot;Andre Agassi&quot;</pre><pre>     sponsor       string  = &quot;Head&quot;</pre><pre>     worldRanking  int     = 1</pre><pre>     stringTension float32 = 65.5</pre><pre>)</pre><pre>var (</pre><pre>     matchesPlayed int  = 0</pre><pre>)</pre><pre>func main() {</pre><pre>     fmt.Println(playerName, sponsor, worldRanking, stringTension, <br>     matchesPlayed)</pre><pre>}</pre><pre>Output:</pre><pre>Andre Agassi Head 1 65.5 0</pre><h4>Redeclaring Variables and Shadowing</h4><p>Take a look at the code below. What do you think the console will output?</p><ol><li>27</li><li>42</li><li>13</li><li>An Error</li></ol><pre>package main</pre><pre>import &quot;fmt&quot;</pre><pre><br>var i int = 27</pre><pre>func main() {</pre><pre>     var i int = 42</pre><pre>     i := 13</pre><pre>     fmt.Println(i)</pre><pre>}</pre><p>If you guessed that this would produce an error, great job. The reason that this code creates an error is that we cannot declare the same variable twice in the same scope. In this instance, i := is trying to declare and initialize a new variable called i. However, we declared i already in our main function and set it equal to 42.</p><p>To get the console to output to 13 we simply would need to replace := with just = . This reassigns the value of i to 13 rather than making a new variable and setting that variable equal to 13.</p><p>In order for the above to output 42. We would need to remove the i := 13 or i = 13 , if we fixed the error. Even though we already declared i in the package level our second i declaration is in a different scope. Go will output the variable with the inner most scope, which in our case is 42. The technical term for this in Go is shadowing. Moreover, the package level i is still available but being hidden by the variable declaration in the main function.</p><p>To output 27 we would need to print i before we declare i equal to 42 in the main function. See below for how this would look.</p><pre>package main</pre><pre>import &quot;fmt&quot;</pre><pre>var i int = 27</pre><pre>func main() {</pre><pre>     fmt.Println(i)<br>  <br>     var i int = 42</pre><pre>     fmt.Println(i)</pre><pre>}</pre><pre>Output: </pre><pre>27<br>42</pre><p>**Special Note: Go requires that we use all the variables we declare in our application functions. If we don’t use a variable, the application will produce a compile-time error. This is useful as it forces developers to remove unused code and keep applications clean. **</p><p><strong>Naming Convention Determines Visibility</strong></p><p>The naming convention of our variables is important because it determines the variables visibility within the application. The three naming conventions for variables are:</p><ol><li>Lowercase</li><li>Uppercase</li><li>Block</li></ol><p>Lowercase variable names are scoped to the package. This means that the variable is only accessible in the package in which it’s declared and unavailable for use in any other package.</p><p>Uppercase variables are globally visible, which means that they can be used within the package in which they are declared and other packages within our application. This is because uppercase variables are exported from the package when compiled.</p><p>Block scope can be found when we declare variables within functions. This scope is only visible within the function and not the package or other packages.</p><p>See below for an example of all naming conventions types</p><pre>package main</pre><pre>import &quot;fmt&quot;</pre><pre><strong>//uppercase: globally visible</strong></pre><pre>var I int = 27</pre><pre><strong>// lowercase: visible to the package only</strong></pre><pre>var (</pre><pre>     playerName    string  = &quot;Andre Agassi&quot;</pre><pre>     sponsor       string  = &quot;Head&quot;</pre><pre>     worldRanking  int     = 1</pre><pre>     stringTension float32 = 65.5</pre><pre>)</pre><pre>func main() {</pre><pre><strong>// block: only visible within the main function</strong></pre><pre>     var i int = 42</pre><pre>     fmt.Println(i)</pre><pre>     fmt.Println(I)</pre><pre>     fmt.Println(playerName, sponsor, worldRanking, stringTension)</pre><pre>}</pre><pre>Output:</pre><pre>42<br>27<br>Andre Agassi Head 1 65.5</pre><h4>Converting Data Types</h4><p>Next we will discuss how to convert data types in Go. More specifically, we will cover converting integers to floats and converting integers to strings, which require different approaches.</p><p><strong>Integers to Floats</strong></p><p>To convert an integer to a float in Go you need to use a conversion operator. Go requires that you explicitly convert data types because it does not want to risk losing data through a conversion. In our example below, we will use float32 as a function to convert variable i to a float called j.</p><pre>package main</pre><pre>import &quot;fmt&quot;</pre><pre>func main() {</pre><pre>     var i int = 42</pre><pre>     fmt.Printf(&quot;%v, %T\n&quot;, i, i)</pre><pre>     var j float32</pre><pre><strong>     // conversion operator</strong></pre><pre>     j = float32(i)</pre><pre>     fmt.Printf(&quot;%v, %T\n&quot;, j, j)</pre><pre>}</pre><pre>Output:</pre><pre>42, int<br>42, float32</pre><p>** Note: Converting from a float to an integer can result in data loss**</p><p><strong>Integers to Strings</strong></p><p>To convert an integer to a string in Go we need to add a package called “strconv”; found <a href="https://golang.org/pkg/strconv/">here</a>. If we tried to use the conversion operator from before, we would get a unicode character. See bold items below for how to import the package and convert our integer to a string.</p><pre>package main</pre><pre>import (</pre><pre>&quot;fmt&quot;</pre><pre><strong>&quot;strconv&quot;</strong></pre><pre>)</pre><pre>func main() {</pre><pre>     var i int = 42</pre><pre>     fmt.Printf(&quot;%v, %T\n&quot;, i, i)</pre><pre>     var j string</pre><pre><strong>     // use strconv package&#39;s str converter function to change from<br>     an integer to a string</strong></pre><pre>     j = strconv.Itoa(i)</pre><pre>     fmt.Printf(&quot;%v, %T\n&quot;, j, j)</pre><pre>}</pre><pre>Output:</pre><pre>42, int<br>42, string</pre><h4>Constants</h4><p>Similar to other programming languages, Go allows for constant variables. Constant variables or constants are variables whose values are fixed and cannot be changed.</p><p>It’s important to note that constants use the same camel-case naming convention as normal variables. As you may remember with normal variables, the naming convention is important because it determines the variables visibility within the application. The same rules apply for constant variables.</p><p>To create a constant variable we need to use the const keyword rather than var we have been using. Let’s create one now!</p><pre>package main</pre><pre>import &quot;fmt&quot;<br></pre><pre>func main() {</pre><pre>    <strong> const </strong>firstConst int = 1</pre><pre>     fmt.Printf(&quot;%v, %T\n&quot;, firstConst, firstConst)</pre><pre>}</pre><pre>Output:</pre><pre>1, int</pre><p>In the above main function we are creating a constant called firstConst with a type of integer. In addition to integers, constants can use any of the primitive types in Go which include boolean, numeric, and text. More information on primitives can be found <a href="https://sedlacek1991.medium.com/go-primitives-560c069d98ad">here</a>. Constants cannot use what are called the collection types; Arrays, Slices, Maps, Structs.</p><p>Another characteristic of constants is that their values must be assignable at compile time. What this means is that we cannot have our values equal to functions that will be calculated at run time. For example, const newestConst float64 = math.Sin(1.98)would produce an error.</p><p>Similar to regular variables, constant variables also have the same behaviors regarding shadowing and types being inferred. However, what’s unique about constants that you cannot do with variables is implicit conversions like the example below. This topic is discussed further in my <a href="https://sedlacek1991.medium.com/go-primitives-560c069d98ad">primitives</a> blog.</p><pre>package main</pre><pre>import (</pre><pre>     &quot;fmt&quot;</pre><pre>)</pre><pre>func main() {</pre><pre>     const m = 10</pre><pre>     var n int16 = 25</pre><pre>     fmt.Printf(&quot;%v, %T\n&quot;, m+n, m+n)</pre><pre>}</pre><pre>Output:</pre><pre>35, int16</pre><p>The last topic we will discuss is constant variable blocks. Constant variable blocks are similar to regular variable blocks in overall structure. They differ in that they use the const keyword as well as a few other ways we will discuss below.</p><pre>package main</pre><pre>import (</pre><pre>     &quot;fmt&quot;</pre><pre>)</pre><pre>const (</pre><pre><strong>     _ = iota</strong></pre><pre>     doctor</pre><pre>     lawyer</pre><pre>     developer</pre><pre>     dogSitter</pre><pre>     accountant</pre><pre>)</pre><pre>func main() {</pre><pre>     var occupationType int = lawyer</pre><pre>     fmt.Printf(&quot;%v\n&quot;, occupationType == lawyer)</pre><pre>     fmt.Printf(&quot;%v\n&quot;, lawyer)</pre><pre>}</pre><pre>Output:</pre><pre>True<br>2</pre><p>You may have thought that the first line in the constant variable block looks a little strange. The Go programming language has one right only variable which is the blank identifier and is displayed with an underscore. Having a blank identifier is beneficial because its saves memory in our program. Moreover, in the above example, by using a blank identifier, we are telling our program to ignore the first value. The other side of the equal sign may have been equally as confusing. Iota can be thought of as a counter and is scoped to the constant block. The value of iota on its own is 0. What’s unique about iota is that it assigns incrementing values to the other variables in the block. As you can see above, lawyer is the second variable after iota and therefore has a a value of 2. It’s also worth noting that you can use addition, subtraction, multiplication, division, remainder, bitwise, and bit-shifting operators with iota to create a fixed offset.</p><p>I hope this blog has kickstarted your journey as a Go Developer. Be on the lookout for future blogs, where I will deep dive into Go’s data types. I have also included some resources and learning materials for further exploration.</p><h4>Learning Materials</h4><p><a href="https://play.golang.org/">Go Playground</a>: Alternative for downloading Go on your local machine. Great resource for quick practice.</p><p><a href="https://golang.org/pkg/">Go Packages</a>: List of packages in Go</p><h4><strong>Resources</strong></h4><p>“Learn Go Programming — Golang Tutorial for Beginners.” <em>YouTube</em>, <a href="http://https//Www.freecodecamp.org/,">freecodecamp.org,</a> 20 June 2019, <a href="http://www.youtube.com/watch?v=YS4e4q9oBaU.">www.youtube.com/watch?v=YS4e4q9oBaU.</a></p><p>“Why Go? 8 Engineers Discuss Golang’s Advantages &amp; How They Use It.” <em>Built In</em>, 15 Oct. 2019, builtin.com/software-engineering-perspectives/golang-advantages.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9390144e25d2" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Build a WebSocket Chat Application]]></title>
            <link>https://javascript.plainenglish.io/how-to-build-a-websocket-chat-application-819399d55800?source=rss-d4a2efb0f7fe------2</link>
            <guid isPermaLink="false">https://medium.com/p/819399d55800</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[socketio]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[nodejs]]></category>
            <dc:creator><![CDATA[Matthew Sedlacek]]></dc:creator>
            <pubDate>Sun, 27 Dec 2020 19:19:58 GMT</pubDate>
            <atom:updated>2020-12-28T22:18:19.542Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*yqJGEvW2Q8r9efXQ" /><figcaption>Photo by <a href="https://unsplash.com/@yogasdesign?utm_source=medium&amp;utm_medium=referral">Yogas Design</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Before diving into this blog, I recommend taking a look at my previous blog, where I introduce <a href="http://Introduction to WebSockets">WebSocket APIs</a>. From the article, you will find a high-level overview of how WebSockets APIs work and the main components of a WebSocket API. This blog will focus on the technologies and steps I used to create a WebSocket Chat Application that meets the following guidelines:</p><ul><li>Logs messages as they happen and shares those messages with everyone connected to the app immediately.</li><li>Results remain between sessions and only the last ten messages are displayed in descending from most recent to oldest.</li></ul><h4>Technologies</h4><p><strong>Backend</strong>: CRUD WebSocket API: Node.js, Express.js, Socket.io, and PostgreSQL</p><p><strong>Frontend</strong>: React and Socket.io</p><p><strong>Deployment</strong>: Heroku and Netlify</p><h4>Backend</h4><p><strong>Overview: </strong>Our backend will consist of a CRUD WebSocket API using a Node.js environment running on an Express.js server that utilizes Socket.io and a PostgreSQL database. Now, that was a lot of vocabulary and technologies listed at once. So, let’s define each piece before we start coding.</p><ul><li><strong>CRUD </strong>— CRUD stands for (Create, Read, Update, and Delete) and are the four key functionalities for an API. Our Chat Application will utilize Create and Read only.</li><li><strong>API (Application Programming Interface)</strong> — “…is a set of programming code that enables data transmission between one software product and another. It also contains the terms of this data exchange” (Altexsoft).</li><li><strong>WebSocket API</strong> — “ …an advanced technology that makes it possible to open a two-way interactive communication session between the user’s browser and a server.” (Mozilla). More information <a href="https://sedlacek1991.medium.com/introduction-to-websockets-8583403d401d">here</a>.</li><li><strong>Node.js </strong>— “An open-source, cross-platform, back-end, JavaScript runtime environment that executes JavaScript code outside a web browser” (Wikipedia).</li><li><strong>Express.js</strong> — “…a minimal and flexible Node.js web application framework that provides a robust set of features for web and mobile applications” (Express).</li><li><strong>PostgreSQL (Postgres)</strong> — “…a powerful, open source object-relational database system with over 30 years of active development that has earned it a strong reputation for reliability, feature robustness, and performance” (Postgresql.org).</li><li><strong>Socket.io </strong>— “Socket.IO is a library that enables real-time, bidirectional and event-based communication between the browser and the server. It consists of a Node.js server and a Javascript client library for the browser” (Socket.io).</li></ul><p>Now let’s get to coding by creating our Postgres database.</p><p><strong>Database Creation</strong></p><p>Instructions require that Homebrew is installed on your local machine. For setup instructions see <a href="https://brew.sh/">link</a>.</p><ol><li>If you have not done so already, install PostgreSQL. For Mac users, type brew install postgresql in the terminal.</li><li>Connect to the default postgres database by typing in your terminal psql postgres</li><li>Create a user with name me and password of password CREATE ROLE me WITH LOGIN PASSWORD &#39;password&#39;;</li><li>Give me the ability to create a database ALTER ROLE me CREATEDB;</li><li>Exit default postgres using \q</li><li>Connect postgres with me psql -d postgres -U me</li><li>Create a database CREATE DATABASE api;</li><li>Connect to new api database \c api</li><li>Create a Table in the api database using the below SQL command. This SQL command creates columns in our Postgres table for an ID, text, username, and a created_at timestamp. Feel free to edit based on the needs of your application.</li></ol><pre>CREATE TABLE messages (<br>  ID SERIAL PRIMARY KEY,<br>  text varchar(255) NOT NULL,<br>  username varchar(255) NOT NULL,<br>  created_at TIMESTAMP NOT NULL DEFAULT now()<br>);</pre><p>10. Set the Time Zone to UTC. SET TIMEZONE=&#39;UTC&#39;; . This step is not required but will allow you to convert UTC timestamps to a users local time using Moment.js in the frontend. To learn more, read my blog <a href="https://levelup.gitconnected.com/seize-the-moment-js-43b3210a27a5">here</a>.</p><p>11. Seed the messages table with the below SQL command. (Make sure the column names are consistent with the table you created in Step 9)</p><pre>INSERT INTO messages (text, username)<br>  VALUES (&#39;1+1=2&#39;, &#39;matthew&#39;), (&#39;2+2=4&#39;, &#39;blake&#39;), (&#39;3+3=6&#39;, &#39;julie&#39;), (&#39;4+4=8&#39;, &#39;courtney&#39;), (&#39;5+5=10&#39;, &#39;brian&#39;), (&#39;6+6=12&#39;, &#39;michael&#39;), (&#39;7+7=14&#39;, &#39;edward&#39;), (&#39;1+1=2&#39;, &#39;matthew&#39;), (&#39;2+2=4&#39;, &#39;blake&#39;), (&#39;3+3=6&#39;, &#39;julie&#39;);</pre><p>12. Database is now set up, and you can leave psql with \q in your terminal.</p><p><strong>Express.js Server Setup</strong></p><p>Now, that we have our seeded Postgres database, we need to create our server.</p><ol><li>In GitHub, create a blank repository and clone it down to the folder of your choice</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/651/1*uRQj3zk67e8T0xTYdivKEw.png" /><figcaption>I recommend initializing your GitHub Repo with a README and .gitignore</figcaption></figure><p>2. Enter your cloned repository usingcd</p><p>3. To create our package.json file type npm init -y</p><p>4. Open your directory in the code editor of your choice</p><pre>// Your package.json file should look similar to this</pre><pre>{<br>  &quot;name&quot;: &quot;node-api-postgres&quot;,<br>  &quot;version&quot;: &quot;1.0.0&quot;,<br>  &quot;description&quot;: &quot;index.js&quot;,<br>  &quot;main&quot;: &quot;&quot;,<br>  &quot;license&quot;: &quot;ISC&quot;<br>}</pre><p>5. Install Express.js for our server npm install express --save</p><p>6. Connect to postgres using node -postgres npm install pg</p><p>Our server now has the required dependencies in the node_modules and package.json files. I recommend committing your work to GitHub and creating a local branch at this point git checkout -b local</p><p><strong>Creating Express.js Server Entry Point</strong></p><p>The entry point for our server will be index.js</p><ol><li>Create index.js file in your code editor</li><li>Input the following code into the index.js file</li></ol><pre>const express = require(&#39;express&#39;)<br>const bodyParser = require(&#39;body-parser&#39;)<br>const app = express()<br>const port = 3000<br><br>app.use(bodyParser.json())<br>app.use(<br>  bodyParser.urlencoded({<br>    extended: true,<br>  })<br>)</pre><pre>app.get(&#39;/&#39;, (request, response) =&gt; {<br>  response.json({ info: &#39;Our app is up and running&#39; })<br>})</pre><pre>app.listen(port, () =&gt; {<br>  console.log(`App running on ${port}.`)<br>})</pre><p>In the above, we need to require express and a built-in express middleware called body-parser. NPM explains that Body-parse, “Parse[s] incoming request bodies in a middleware before your handlers, available under the req.body property”(NPM).</p><p>The first app.get is the home route for our application and will show the info message when we run the server node index.jsin localhost:3000.</p><p>The app.listen tells us what port our app is running on in the terminal.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/454/1*vATfOVzAnBhPc9KjdFu8IQ.png" /><figcaption>Localhost: 3000</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WY7S7APw_57U44bWo4hNSQ.png" /><figcaption>Terminal</figcaption></figure><p>Our Express.js server is running; now we need to connect to the Postgres database we created earlier.</p><p><strong>Postgres database Connection</strong></p><p>As mentioned earlier, we installed node-postgres to allow for our Postgres database to connect to our Node.js/Express.js server. Now let’s create the connection.</p><ol><li>Create queries.js file</li><li>Input the following code to setup our connection to the postgres database. In our example, we are using node-postgres’s built-in connection pooling. We use pooling because our application will be making queries frequently. Also, using a pool architecture “… ensures ‘closed’ connections are not really closed, but returned to a pool, and ‘opening’ a new connection returns the same ‘physical connection’ back, reducing the actual forking on the PostgreSQL side” (ScaleGrid).</li></ol><pre>// Please note that if you changed the user, database, or password in the database creation section you will need to update the respective line items below.</pre><pre>const Pool = require(&quot;pg&quot;).Pool;</pre><pre>const pool = new Pool({</pre><pre>     user: &quot;me&quot;,</pre><pre>     host: &quot;localhost&quot;,</pre><pre>     database: &quot;api&quot;,</pre><pre>     password: &quot;password&quot;,</pre><pre>     port: 5432,</pre><pre>});</pre><p>Now that we have connected to our database, we will create our CRUD operations and route.</p><p><strong>CRUD Operations &amp; Route</strong></p><p>This app will only use the Create and Read functionalities and therefore needs only a single endpoint /messages. While creating our CRUD actions, we will need to make changes in both our index.js and queries.js files. Let’s start with queries.js.</p><ul><li>Remember that our application requires that we only display the last ten messages descending from most recent to oldest. We can now take care of this requirement by creating a GET request (The Read in CRUD) called getMessages.</li></ul><pre>// queries.js</pre><pre>const getMessages = (request, response) =&gt; {</pre><pre>   pool.query(</pre><pre>      &quot;SELECT * FROM messages ORDER BY id DESC LIMIT 10&quot;,</pre><pre>      (error, results) =&gt; {</pre><pre>         if (error) {</pre><pre>            throw error;</pre><pre>         }</pre><pre>         response.status(200).json(results.rows);</pre><pre>      }</pre><pre>   );</pre><pre>};</pre><p>Using pooling enables us to enter raw SQL that will pull from our Postgres database. The raw SQL is key to meeting our project requirements. In plain English, the SQL statement selects everything from the messages table and orders rows from oldest to newest, and limits the selection to only ten messages.</p><ul><li>Our users also need to be able to create messages. This requires a POST request to our endpoint (The Create in CRUD). Let’s make this functionality now.</li></ul><pre>const createMessage = (request, response) =&gt; {</pre><pre>   const { text, username } = request.body;</pre><pre>   pool.query(</pre><pre>   &quot;INSERT INTO messages (text, username) VALUES ($1, $2) RETURNING <br>   text, username, created_at&quot;,</pre><pre>      [text, username],</pre><pre>      (error, results) =&gt; {</pre><pre>         if (error) {</pre><pre>            throw error;</pre><pre>         }</pre><pre>         response.status(201).send(results.rows);</pre><pre>         }</pre><pre>   );</pre><pre>};</pre><p>Here, we are using pooling again to enter raw SQL that will add our users’ messages into our Postgres database. In plain English, the SQL statement puts into the messages table an entry where our application will provide the values for text and username. We also are telling our query to return the created_at timestamp in addition to the text and username.</p><p>The last step we need to do in queries.js is to make the methods accessible to index.js. We can do this by adding module.exports to the bottom of our file.</p><pre>module.exports = {</pre><pre>   getMessages,</pre><pre>   createMessage,</pre><pre>};</pre><p>Now in index.js all we need to do to utilize these methods is add the following.</p><pre>// Add to the top of the index.js file with the other requires<br>const db = require(&#39;./queries&#39;)<br></pre><pre>// Add to the bottom<br>app.get(&quot;/messages&quot;, db.getMessages);</pre><pre>app.post(&quot;/messages&quot;, db.createMessage);</pre><p>Now, if we run node index.js we can go to <a href="http://localhost:3000/messages">http://localhost:3000/messages</a> and see our messages. You should see something similar to the below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/378/1*rJHaTfpVteE9MAHG9tS7bw.png" /><figcaption>Example of current output</figcaption></figure><p>Now, this is where we could stop if we were implementing a RESTful API. However, our app requires a WebSocket API. I would recommend pushing up this branch to GitHub and then creating a branch called Socketio.</p><p><strong>Socket.io Implementation (Local)</strong></p><p>As mentioned previously, Socket.io is a “ …long polling/WebSocket based third party transfer protocol for <a href="https://nodejs.org/">Node.js</a>” (Mozilla). In this section, we will install Socket.io and the other required dependencies to turn our API from a RESTful API to a WebSocket API.</p><ol><li>Rename index.js to app.js to follow Socket.io convention</li><li>In package.json rename main value from index.js to app.js</li></ol><pre>&quot;main&quot;: &quot;app.js&quot;,</pre><p>3. Install Socket.io with terminal command npm install socket.io</p><p>4. Install CORS using the terminal command npm i cors . Mozilla defines CORS or Cross-Origin Resource Sharing as, “…an HTTP-header based mechanism that allows a server to indicate any other origins (domain, scheme, or port) than its own from which a browser should permit loading of resources” (Mozilla). Without CORS, our frontend would not be able to send requests to our backend.</p><p>5. Using the documentation provided by Socket.io we need to add/update the bolded contents in our app.js to allow Socket.io and CORS implementation</p><pre>// app.js</pre><pre>const express = require(&quot;express&quot;);</pre><pre>const bodyParser = require(&quot;body-parser&quot;);</pre><pre><strong>const cors = require(&quot;cors&quot;);</strong></pre><pre>const app = express();</pre><pre>const port = 3000;</pre><pre><strong>const socketPort = 8000;</strong></pre><pre>const db = require(&quot;./queries&quot;);</pre><pre><strong>const { emit } = require(&quot;process&quot;);</strong></pre><pre><strong>const server = require(&quot;http&quot;).createServer(app);</strong></pre><pre><strong>const io = require(&quot;socket.io&quot;)(server, {</strong></pre><pre><strong>   cors: {</strong></pre><pre><strong>      origin: &quot;http://localhost:3001&quot;,</strong></pre><pre><strong>      methods: [&quot;GET&quot;, &quot;POST&quot;],</strong></pre><pre><strong>   },</strong></pre><pre><strong>});</strong></pre><pre><strong>app.use(cors());</strong></pre><pre>// parses requests for fetch</pre><pre>app.use(bodyParser.json());</pre><pre>app.use(</pre><pre><strong>   bodyParser.urlencoded({</strong></pre><pre><strong>      extended: true,</strong></pre><pre><strong>   })</strong></pre><pre>);</pre><pre>app.listen(port, () =&gt; {</pre><pre>   console.log(`App running on port ${port}.`);</pre><pre>});</pre><pre>app.get(&quot;/messages&quot;, db.getMessages);</pre><pre>app.post(&quot;/messages&quot;, db.createMessage);</pre><p>6. Now that we are using a WebSocket API, we need to add new GET and POST requests in our queries.js file. See the RESTful API section for specifics regarding what these SQL queries do.</p><pre>// queries.js</pre><pre>/* SOCKET DB */</pre><pre>const getSocketMessages = () =&gt; {</pre><pre>   return new Promise((resolve) =&gt; {</pre><pre>      pool.query(</pre><pre>         &quot;SELECT * FROM messages ORDER BY id DESC LIMIT 10&quot;,</pre><pre>         (error, results) =&gt; {</pre><pre>            if (error) {</pre><pre>               throw error;</pre><pre>            }</pre><pre>            resolve(results.rows);</pre><pre>          }</pre><pre>      );</pre><pre>   });</pre><pre>};</pre><pre>const createSocketMessage = (message) =&gt; {</pre><pre>   return new Promise((resolve) =&gt; {</pre><pre>      pool.query(</pre><pre>         &quot;INSERT INTO messages (text, username) VALUES ($1, $2) <br>         RETURNING text, username, created_at&quot;,</pre><pre>         [message.text, message.username],</pre><pre>         (error, results) =&gt; {</pre><pre>            if (error) {</pre><pre>               throw error;</pre><pre>            }</pre><pre>            resolve(results.rows);</pre><pre>         }</pre><pre>      );</pre><pre>   });</pre><pre>};</pre><p>7. To make these methods accessible to app.js we need to add them to our module.exports</p><pre>// queries.js</pre><pre>module.exports = {</pre><pre>   getMessages,</pre><pre>   createMessage,</pre><pre><strong>   getSocketMessages,</strong></pre><pre><strong>   createSocketMessage,</strong></pre><pre>};</pre><p>8. Lastly, we need to add our Socket.io methods to app.js</p><pre>// app.js<br></pre><pre>// sends out the 10 most recent messages from recent to old</pre><pre>const emitMostRecentMessges = () =&gt; {</pre><pre>   db.getSocketMessages()</pre><pre>      .then((result) =&gt; io.emit(&quot;chat message&quot;, result))</pre><pre>      .catch(console.log);</pre><pre>};</pre><pre>// connects, creates message, and emits top 10 messages</pre><pre>io.on(&quot;connection&quot;, (socket) =&gt; {</pre><pre>   console.log(&quot;a user connected&quot;);</pre><pre>   socket.on(&quot;chat message&quot;, (msg) =&gt; {</pre><pre>      db.createSocketMessage(JSON.parse(msg))</pre><pre>         .then((_) =&gt; {</pre><pre>            emitMostRecentMessges();</pre><pre>         })</pre><pre>         .catch((err) =&gt; io.emit(err));<br>});</pre><pre><br>// close event when user disconnects from app</pre><pre>   socket.on(&quot;disconnect&quot;, () =&gt; {</pre><pre>      console.log(&quot;user disconnected&quot;);<br>   });</pre><pre>});</pre><pre><br>// Displays in terminal which port the socketPort is running on</pre><pre>server.listen(socketPort, () =&gt; {</pre><pre>   console.log(`listening on *:${socketPort}`);</pre><pre>});</pre><p>9. To test our application, we can create an index.html file. Copy and paste the below source code for a quick example, or feel free to create your own. To run, you need to have two terminals; one for the server and the other to open the index.html file. The terminal commands to do this are node app.js and open index.html</p><pre>&lt;!doctype html&gt;</pre><pre>&lt;html&gt;</pre><pre>   &lt;head&gt;</pre><pre>      &lt;title&gt;Socket.IO chat&lt;/title&gt;</pre><pre>      &lt;style&gt;</pre><pre>         * { margin: 0; padding: 0; box-sizing: border-box; }</pre><pre>         body { font: 13px Helvetica, Arial; }</pre><pre>         form { background: #000; padding: 3px; position: fixed;   <br>         bottom: 0; width: 100%; }</pre><pre>         form input { border: 0; padding: 10px; width: 90%; <br>         margin-right: 0.5%; }</pre><pre>         form button { width: 9%; background: rgb(130, 224, 255);<br>         border: none; padding: 10px; }</pre><pre>         #messages { list-style-type: none; margin: 0; padding: 0; }</pre><pre>         #messages li { padding: 5px 10px; }</pre><pre>         #messages li:nth-child(odd) { background: #eee; }</pre><pre>      &lt;/style&gt;</pre><pre>   &lt;/head&gt;</pre><pre>   &lt;body&gt;</pre><pre>      &lt;ul id=&quot;messages&quot;&gt;&lt;/ul&gt;</pre><pre>      &lt;form action=&quot;&quot;&gt;</pre><pre>         &lt;input id=&quot;username&quot; autocomplete=&quot;off&quot; <br>          placeholder=&quot;username&quot;/&gt;</pre><pre>         &lt;input id=&quot;m&quot; autocomplete=&quot;off&quot; placeholder=&quot;equation&quot;/&gt;</pre><pre>         &lt;button&gt;Send&lt;/button&gt;<br>      &lt;/form&gt;</pre><pre>      &lt;script src=&quot;http://localhost:8000/socket.io/socket.io.js&quot;&gt;.<br>      &lt;/script&gt;</pre><pre>      &lt;script&gt;</pre><pre>         const socket = io(&quot;http://localhost:8000&quot;);</pre><pre>         const form = document.querySelector(&#39;form&#39;);</pre><pre>         const messages = document.querySelector(&#39;#messages&#39;);</pre><pre>   function createMessage(msg) {</pre><pre>      const li = document.createElement(&#39;li&#39;);</pre><pre>     li.textContent =`${msg.text},${msg.username},${msg.created_at}`</pre><pre>      messages.append(li);<br>   }</pre><pre>   function createMessages(msgs) {</pre><pre>      msgs.forEach(createMessage);<br>   }</pre><pre><br>   fetch(&quot;http://localhost:3000/messages&quot;)</pre><pre>   .then(res =&gt; res.json())</pre><pre>   .then(createMessages);</pre><pre>   <br>   form.addEventListener(&quot;submit&quot;, (e) =&gt; {<br>      e.preventDefault();<br>      socket.emit(&#39;chat message&#39;, JSON.stringify({<br>      text: document.querySelector(&#39;#m&#39;).value,<br>      username: document.querySelector(&#39;#username&#39;).value<br>     }));</pre><pre>      e.target.reset();<br>   });</pre><pre>   socket.on(&#39;chat message&#39;, function (msgs) {<br>      console.log(msgs)<br>      messages.innerHTML = &quot;&quot;;<br>      createMessages(msgs);<br>   });</pre><pre>         &lt;/script&gt;</pre><pre>   &lt;/body&gt;</pre><pre>&lt;/html&gt;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3IBMLBco3g5m7DKQDdCoVQ.png" /><figcaption>Index.html file after opening</figcaption></figure><p>Our WebSocket API is now complete and our Read and Create actions are working as expected. The last step now is to modify our API for deployment on Heroku.</p><p><strong>Preparing Backend Server to be deployed on Heroku</strong></p><p>At this point, I recommend pushing your socketio branch to GitHub and creating a new branch called deployment. Our deployment branch will be used to deploy our backend to Heroku.</p><ol><li>Create a blank .env file for our app.js and queries.js files to reference in deployment</li><li>Heroku requires that we only have one port variable. See bold areas for changes</li><li>CORS origin will need to be updated to the netlify URL where our React frontend will be hosted</li><li>Need to remove redundant code app.listen(port, () =&gt; {console.log(`App running on port ${port}.`);});</li></ol><p>The final app.js file should resemble the code below:</p><pre>// app.js</pre><pre>const express = require(&quot;express&quot;);</pre><pre>const bodyParser = require(&quot;body-parser&quot;);</pre><pre>const cors = require(&quot;cors&quot;);</pre><pre>const app = express();</pre><pre><strong>const PORT = process.env.PORT || 8000;</strong></pre><pre>const db = require(&quot;./queries&quot;);</pre><pre>const { emit } = require(&quot;process&quot;);</pre><pre>const server = require(&quot;http&quot;).createServer(app);</pre><pre>const io = require(&quot;socket.io&quot;)(server, {</pre><pre>   cors: {</pre><pre><strong>      origin: &quot;{will need to input netlify url here}&quot;,</strong></pre><pre>      methods: [&quot;GET&quot;, &quot;POST&quot;],</pre><pre>   },</pre><pre>});</pre><pre>app.use(cors());<br></pre><pre>// parses requests for fetch</pre><pre>app.use(bodyParser.json());</pre><pre>app.use(</pre><pre>   bodyParser.urlencoded({</pre><pre>      extended: true,</pre><pre>   })</pre><pre>);</pre><pre>app.get(&quot;/messages&quot;, db.getMessages);<br>app.post(&quot;/messages&quot;, db.createMessage);</pre><pre>// sends out the 10 most recent messages from recent to oldest</pre><pre>const emitMostRecentMessges = () =&gt; {</pre><pre>   db.getSocketMessages()</pre><pre>      .then((result) =&gt; io.emit(&quot;chat message&quot;, result))</pre><pre>      .catch(console.log);</pre><pre>};<br></pre><pre>// connects, creates message, and emits top 10 messages</pre><pre>io.on(&quot;connection&quot;, (socket) =&gt; {</pre><pre>   console.log(&quot;a user connected&quot;);</pre><pre>   socket.on(&quot;chat message&quot;, (msg) =&gt; {</pre><pre>      db.createSocketMessage(JSON.parse(msg))</pre><pre>      .then((_) =&gt; {</pre><pre>         emitMostRecentMessges();</pre><pre>      })</pre><pre>         .catch((err) =&gt; io.emit(err));</pre><pre>   });</pre><pre>// close event when user disconnects from app</pre><pre>   socket.on(&quot;disconnect&quot;, () =&gt; {</pre><pre>      console.log(&quot;user disconnected&quot;);</pre><pre>   });</pre><pre>});</pre><pre>server.listen(<strong>PORT</strong>, () =&gt; {</pre><pre>   console.log(`listening on *:${<strong>PORT</strong>}`);</pre><pre>});</pre><p>3. Update the connection pooling in the queries.js file to use the .env’s DATABASE_URL provided by Heroku.</p><p>The final queries.js file should resemble the code below:</p><pre>// queries.js</pre><pre>const Pool = require(&quot;pg&quot;).Pool;</pre><pre>const pool = new Pool({</pre><pre><strong>   connectionString: process.env.DATABASE_URL,</strong></pre><pre><strong>   ssl: {</strong></pre><pre><strong>      rejectUnauthorized: false,</strong></pre><pre><strong>   },</strong></pre><pre>});</pre><pre>/* Local DB */</pre><pre>const getMessages = (request, response) =&gt; {</pre><pre>   pool.query(</pre><pre>      &quot;SELECT * FROM messages ORDER BY id DESC LIMIT 10&quot;,</pre><pre>      (error, results) =&gt; {</pre><pre>         if (error) {</pre><pre>            throw error;</pre><pre>         }</pre><pre>         response.status(200).json(results.rows);</pre><pre>         }</pre><pre>      );</pre><pre>   };</pre><pre>const createMessage = (request, response) =&gt; {</pre><pre>   const { text, username } = request.body;</pre><pre>   pool.query(</pre><pre>      &quot;INSERT INTO messages (text, username) VALUES ($1, $2)<br>      RETURNING text, username, created_at&quot;,</pre><pre>      [text, username],</pre><pre>      (error, results) =&gt; {</pre><pre>         if (error) {</pre><pre>            throw error;</pre><pre>         }</pre><pre>         response.status(201).send(results.rows);</pre><pre>      }</pre><pre>   );</pre><pre>};</pre><pre>/* SOCKET DB */</pre><pre>const getSocketMessages = () =&gt; {</pre><pre>   return new Promise((resolve) =&gt; {</pre><pre>      pool.query(</pre><pre>         &quot;SELECT * FROM messages ORDER BY id DESC LIMIT 10&quot;,</pre><pre>         (error, results) =&gt; {</pre><pre>            if (error) {</pre><pre>               throw error;</pre><pre>            }</pre><pre>            resolve(results.rows);</pre><pre>            }</pre><pre>         );</pre><pre>     });</pre><pre>};</pre><pre>const createSocketMessage = (message) =&gt; {</pre><pre>   return new Promise((resolve) =&gt; {</pre><pre>      pool.query(</pre><pre>         &quot;INSERT INTO messages (text, username) VALUES ($1, $2)  <br>         RETURNING text, username, created_at&quot;,</pre><pre>         [message.text, message.username],</pre><pre>         (error, results) =&gt; {</pre><pre>            if (error) {</pre><pre>               throw error;</pre><pre>            }</pre><pre>            resolve(results.rows);</pre><pre>          }</pre><pre>      );</pre><pre>   });</pre><pre>};</pre><pre>module.exports = {</pre><pre>   getMessages,</pre><pre>   createMessage,</pre><pre>   getSocketMessages,</pre><pre>   createSocketMessage,</pre><pre>};</pre><p>4. Add engines and start script to package.json file (See bold sections).</p><p>The final package.json file should resemble the code below:</p><pre>{</pre><pre>&quot;name&quot;: &quot;node-api-postgres&quot;,</pre><pre>&quot;version&quot;: &quot;1.0.0&quot;,</pre><pre>&quot;description&quot;: &quot;&quot;,</pre><pre><strong>&quot;engines&quot;: {</strong></pre><pre><strong>   &quot;node&quot;: &quot;12.18.4&quot;</strong></pre><pre><strong>},</strong></pre><pre>&quot;main&quot;: &quot;app.js&quot;,</pre><pre>&quot;scripts&quot;: {</pre><pre><strong>   &quot;start&quot;: &quot;node app.js&quot;,</strong></pre><pre>   &quot;test&quot;: &quot;echo \&quot;Error: no test specified\&quot; &amp;&amp; exit 1&quot;</pre><pre>},</pre><pre>&quot;repository&quot;: {</pre><pre>   &quot;type&quot;: &quot;git&quot;,</pre><pre>   &quot;url&quot;: &quot;git+https://github.com/matthewsedlacek/node-api<br>   -postgres.git&quot;</pre><pre>},</pre><pre>&quot;keywords&quot;: [],</pre><pre>&quot;author&quot;: &quot;&quot;,</pre><pre>&quot;license&quot;: &quot;ISC&quot;,</pre><pre>&quot;bugs&quot;: {</pre><pre>&quot;url&quot;: &quot;https://github.com/matthewsedlacek/node-api-postgres/issues&quot;</pre><pre>},</pre><pre>&quot;homepage&quot;: &quot;https://github.com/matthewsedlacek/node-api postgres#readme&quot;,</pre><pre>&quot;dependencies&quot;: {</pre><pre>   &quot;cors&quot;: &quot;^2.8.5&quot;,</pre><pre>   &quot;express&quot;: &quot;^4.17.1&quot;,</pre><pre>   &quot;pg&quot;: &quot;^8.5.1&quot;,</pre><pre>   &quot;socket.io&quot;: &quot;^3.0.4&quot;</pre><pre>}</pre><pre>}</pre><p>5. Create a Procfile with the following code. If you are unfamiliar with Procfile, it is a way to declare commands that are run by our application’s dynos on Heroku.</p><pre>web: node app.js</pre><p>Now are file is ready to be deployed on Heroku.</p><p><strong>Deploying to Heroku</strong></p><p>These instructions are adopted from my previous blog regarding <a href="https://medium.com/swlh/launching-your-first-website-rails-react-42a6af1ab481">deployment</a>.</p><p>Before starting, you will need to download and install the <a href="https://devcenter.heroku.com/articles/heroku-cli">Heroku CLI</a>. After you’ve created an account and logged in, you are ready to begin the process to host your backend on Heroku. In your terminal, type the following command.</p><pre>heroku create</pre><p>This command will create a new app on Heroku. If you would like to name your backend, include it in the line above; otherwise, Heroku will generate a name for you.</p><pre>git push heroku main</pre><p>The git push command will push your repository up to the Heroku app you created in the previous terminal command. You do not need to specify the name given to your app in the previous step because ‘heroku create’ builds a git remote called ‘heroku’ that points to the application you just created.</p><pre>heroku addons:create heroku-postgresql:hobby-dev</pre><p>The above command adds Postgres to our Heroku app.</p><pre>heroku pg:reset</pre><pre>heroku pg:push name-of-local-database DATABASE_URL --app name-of-Heroku-app</pre><p>Next, we need to reset our default Postgres and push up our local database. In our Create Database section we named our local database api. So, the name-of-local-database is api. DATABASE_URL should remain as is above along with — app. The name-of-Heroku-app can be found by scrolling up in your terminal and looking to see the name generated by the heroku create terminal command.</p><p>You now have a deployed backend hosted on Heroku. You can view your app by typing heroku open then adding a /messages to the URL.</p><p>*Please note that to avoid your Dyno’s from falling asleep, you will need to go into your Heroku account and upgrade the Dyno from Free to Hobby. This will keep your WebSocket API awake and will prevent undesired behavior with our WebSocket Chat Application.*</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cN5rwTzDA8_PP26baFzDrg.png" /><figcaption>Change Dyno Type in the Resources Tab in Heroku</figcaption></figure><h4>Frontend</h4><p>This section, won’t focus on how to build a frontend, but more how Socket.io fits into our React frontend. The methods we will write will be in two separate components; one functional and one class component.</p><p>To get started, we need to install the socket.io client. To install, type the following command in the terminal:</p><pre>npm i socket.io-client</pre><p>In our functional component, we first need to import the Socket.io client. Then we need to create variables for our Socket Endpoint, Fetch Endpoint, and the WebSocket (See bold). In this functional component, we are using react hooks to set the initial HTTP handshake (see first bolded useEffect). Then we are using useEffect again to see if the client and server can continue over WebSockets. If so, our list of messages will update every time a user submits a message, and our WebSocket will be running in its desired manner.</p><pre>import React from &quot;react&quot;;</pre><pre>import { useEffect, useState } from &quot;react&quot;;</pre><pre>import MessagesArea from &quot;./MessagesArea&quot;;</pre><pre><strong>import socketIOClient from &quot;socket.io-client&quot;;</strong></pre><pre><strong>const socketEndpoint = &quot;https://serene-crag-73795.herokuapp.com&quot;;</strong></pre><pre><strong>const fetchEndpoint = `${socketEndpoint}/messages`;</strong></pre><pre><strong>const socket = socketIOClient(socketEndpoint);</strong></pre><pre>function ConversationsList(props) {</pre><pre>   const [messages, setMessages] = useState([]);</pre><pre><strong>   useEffect(() =&gt; {<br>      fetch(fetchEndpoint)<br>      .then((res) =&gt; res.json())<br>      .then(setMessages)<br>      .catch(console.log);<br>   }, []);</strong></pre><pre><strong>   useEffect(() =&gt; {<br>      if (socket) {<br>         socket.on(&quot;chat message&quot;, (msgs) =&gt; {<br>            setMessages(msgs);<br>         });<br>      }<br>   }, []);</strong><br></pre><pre>return (<br>   &lt;React.Fragment&gt;<br>      {messages.length &gt; 0 ? (<br>         &lt;MessagesArea<br>            <strong>messages={messages}</strong><br>            username={props.username}<br>            userId={props.uid}<br>         /&gt;<br>      ) : null}<br>   &lt;/React.Fragment&gt;</pre><pre> );</pre><pre>}</pre><pre>export default ConversationsList;</pre><p>The class component will handle sending new messages to the client. Similar to the functional component, we need to import Socket.io and create variables for our Socket Endpoint and the WebSocket (See bold). Note, we are not using fetch in this component as we are only sending new messages over the WebSocket. To send the new messages, we use an emit event (See bold). It’s also worth mentioning that the emit events we created <em>socket.on</em> and <em>socket.emit</em> have corresponding listeners in the app.js file in our backend.</p><pre>import React, { Component } from &quot;react&quot;;</pre><pre>import CalculatorDisplay from &quot;../components/calculator/CalculatorDisplay&quot;;</pre><pre>import Keypad from &quot;../components/calculator/Keypad&quot;;</pre><pre>import Card from &quot;react-bootstrap/Card&quot;;</pre><pre><strong>import socketIOClient from &quot;socket.io-client&quot;;</strong></pre><pre><strong>const socketEndpoint = &quot;https://serene-crag-73795.herokuapp.com&quot;;</strong></pre><pre><strong>const socket = socketIOClient(socketEndpoint);</strong></pre><pre>class Calculator extends Component {</pre><pre>   state = {</pre><pre>   result: &quot;&quot;,</pre><pre>   errorMessage: 0,</pre><pre>   resultPost: &quot;&quot;,</pre><pre>   };<br></pre><pre>   onClick = (button) =&gt; {</pre><pre>      if (button === &quot;=&quot;) {</pre><pre>         this.calculate();</pre><pre>      } else if (button === &quot;C&quot;) {</pre><pre>         this.reset();</pre><pre>      } else if (button === &quot;←&quot;) {</pre><pre>         this.backspace();</pre><pre>      } else {</pre><pre>         this.setState({</pre><pre>            result: this.state.result + button,</pre><pre>         });</pre><pre>      }</pre><pre>    };</pre><pre>   calculate = () =&gt; {</pre><pre>      try {</pre><pre>         this.handleSubmit();</pre><pre>      } catch (e) {</pre><pre>        this.setState({</pre><pre>          result: &quot;error&quot;,</pre><pre>         });</pre><pre>      }</pre><pre>    };</pre><pre><strong>   handleSubmit = (e) =&gt; {<br>      socket.emit(<br>         &quot;chat message&quot;,<br>         JSON.stringify({<br>            text: this.state.result + &quot; = &quot; +<br>            (eval(this.state.result) || 0) + &quot;&quot;,<br>            username: this.props.username,<br>         })<br>      );<br>      this.setState({ result: &quot;&quot; });<br>   };</strong></pre><pre>   reset = () =&gt; {<br>      this.setState({<br>         result: &quot;&quot;,<br>         resultPost: &quot;&quot;,<br>      });<br>   };</pre><pre>   backspace = () =&gt; {<br>      this.setState({<br>         result: this.state.result.slice(0, -1),<br>      });<br>   };</pre><pre>   render() {<br>      return [&quot;Primary&quot;].map((variant, idx) =&gt; (<br>      &lt;Card className=&quot;calculatorContainer&quot; <br>      bg={variant.toLowerCase()}&gt;<br>         &lt;Card.Body&gt;<br>             &lt;Card.Text&gt;<br>                &lt;CalculatorDisplay result={this.state.result} /&gt;<br>             &lt;/Card.Text&gt;<br>             &lt;Card.Text&gt;<br>                 &lt;Keypad<br>                    onClick={this.onClick}<br>                    resultPost={this.state.resultPost}<br>                    conversation_id={this.props.conversation_id}<br>                    username={this.props.username}<br>                 /&gt;<br>            &lt;/Card.Text&gt;<br>         &lt;/Card.Body&gt;<br>      &lt;/Card&gt;<br>   ));<br>  }<br>}</pre><pre>export default Calculator;</pre><p>Now our frontend is using the WebSocket protocol to communicate with our backend.</p><p><strong>Deploying Frontend on Netlify</strong></p><p>These instructions are adopted from my previous blog regarding <a href="https://medium.com/swlh/launching-your-first-website-rails-react-42a6af1ab481">deployment</a>.</p><p>After creating an account with <a href="https://www.netlify.com/">Netlify</a>, select the “New site from Git” option.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*mGpCs0Aumkj7kp-_.png" /></figure><p>Next select your Git Provider.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*zhL9B-IMtSnjcWSQ.png" /></figure><p>Your Git provider will then ask you to authorize Netlify. After doing so, you will see a list of your repositories to choose from.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*v6hZoaUAsoZyOh1G.png" /></figure><p>After you have selected your frontend repository, the below options will populate. Click the ‘Deploy site’ button.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*IkrqF4nHtRLrORoB.png" /></figure><p>Following clicking the “Deploy site” button, you will be redirected to your new site dashboard, as seen below. The main area to pay attention to is the production deploys area that now says “Building.” Here you will be shown any errors, or if there aren’t any, you will see that your site was published.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*MMgB5tZf-owraaZc.png" /></figure><p>If you do encounter errors, the logs provide details on the error and how to fix them. There is also a live chat feature with individuals who can help. After fixing your errors, you can go to the deploys tab and click “Trigger deploy” to try again.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*HGqcwVecslIxXn0b.png" /></figure><p>When all errors are fixed, you will see a Published message similar to the one below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/832/0*lMCQft6tzNMpAMhz.png" /></figure><p>Now our frontend is deployed, but we need to update CORS in our app.js file in the backend to complete our application. Then we need to push these changes up to heroku git push heroku main .</p><pre>const io = require(&quot;socket.io&quot;)(server, {</pre><pre>   cors: {</pre><pre><strong>      origin: &quot;https://calculator-chat.netlify.app&quot;,</strong></pre><pre>      methods: [&quot;GET&quot;, &quot;POST&quot;],</pre><pre>   },</pre><pre>});</pre><p>Thank you for taking the time to learn how to create a Chat Application using WebSockets. I hope this blog will be a good reference for you to refer back to whenever you need to create a WebSocket Chat feature for future projects.</p><h4>Resources:</h4><p>Rascia, Tania. <em>Node.js, Express.js, and PostgreSQL: CRUD REST API Example</em>, 31 Oct. 2018, blog.logrocket.com/nodejs-expressjs-postgresql-crud-rest-api-example/.</p><p>“Node.js.” <em>Wikipedia</em>, Wikimedia Foundation, 27 Dec. 2020, en.wikipedia.org/wiki/Node.js.</p><p>“Rails Intro To Rest.” <em>Learn</em>, learn.co/tracks/web-development-immersive-2–0-module-two/rails/intro-to-rest/intro-to-rest.</p><p>“WebSocket vs REST: Learn The 8 Important Differences.” <em>EDUCBA</em>, 23 Apr. 2020, <a href="http://www.educba.com/websocket-vs-rest/">www.educba.com/websocket-vs-rest/.</a></p><p>Editor. “What Is API: Definition, Types, Specifications, Documentation.” <em>AltexSoft</em>, AltexSoft, 11 Feb. 2020, <a href="http://www.altexsoft.com/blog/engineering/what-is-api-definition-types-specifications-documentation/">www.altexsoft.com/blog/engineering/what-is-api-definition-types-specifications-documentation/.</a></p><p>“Web Technology for Developers.” <em>Web APIs | MDN</em>, Mozilla, developer.mozilla.org/en-US/docs/Web/API/WebSockets_API.</p><p>“Node.js Web Application Framework.” <em>Express</em>, expressjs.com/.</p><p>Group, PostgreSQL Global Development. <em>PostgreSQL</em>, 27 Dec. 2020, <a href="http://www.postgresql.org/">www.postgresql.org/.</a></p><p>Arrachequesne, Damien. “Introduction.” <em>Socket.IO</em>, 27 Nov. 2020, socket.io/docs/v3.</p><p>Srushtika. “Everything You Ever Wanted to Know about WebSockets, Literally!” <em>Hacker Noon</em>, 30 Nov. 2020, hackernoon.com/everything-you-ever-wanted-to-know-about-websockets-literally-a05f36432999.</p><p>“Body-Parser.” <em>Npm</em>, <a href="http://www.npmjs.com/package/body-parser.">www.npmjs.com/package/body-parser.</a></p><p>“Pooling.” <em>Node</em>, node-postgres.com/features/pooling.</p><p>Raychaudhury, Aparajita. “PostgreSQL Connection Pooling: Part 1 — Pros &amp; Cons.” <em>ScaleGrid Blog — Fully Managed Cloud Databases Tips</em>, ScaleGrid, 19 Oct. 2020, scalegrid.io/blog/postgresql-connection-pooling-part-1-pros-and-cons/.</p><p>“Web Technology for Developers.” <em>HTTP | MDN</em>, developer.mozilla.org/en-US/docs/Web/HTTP/CORS.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=819399d55800" width="1" height="1" alt=""><hr><p><a href="https://javascript.plainenglish.io/how-to-build-a-websocket-chat-application-819399d55800">How to Build a WebSocket Chat Application</a> was originally published in <a href="https://javascript.plainenglish.io/">JavaScript in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Introduction to WebSockets]]></title>
            <link>https://medium.com/swlh/introduction-to-websockets-8583403d401d?source=rss-d4a2efb0f7fe------2</link>
            <guid isPermaLink="false">https://medium.com/p/8583403d401d</guid>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[https]]></category>
            <category><![CDATA[websocket]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[coding]]></category>
            <dc:creator><![CDATA[Matthew Sedlacek]]></dc:creator>
            <pubDate>Sat, 19 Dec 2020 04:13:12 GMT</pubDate>
            <atom:updated>2020-12-24T22:20:10.472Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*99oseacf2voRuSDa" /><figcaption>Photo by <a href="https://unsplash.com/@austindistel?utm_source=medium&amp;utm_medium=referral">Austin Distel</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>In a recent code challenge, I was tasked with creating an application that logs messages as they happen and shares those messages with everyone connected to the app. As a Full Stack Developer, I’m very familiar with working with RESTful API’s and utilizing HTTP requests between a client and server. However, to complete the task at hand, I needed to create a special type of API, a WebSocket.</p><h4>What is a WebSocket?</h4><p>WebSockets are a fairly new technology; the first WebSocket protocol was designed by Michael Carter in 2008 for HTML 5 (Topio Networks). MDN Web Docs describes a WebSocket API as “… an advanced technology that makes it possible to open a two-way interactive communication session between the user’s browser and a server. With this API, you can send messages to a server and receive event-driven responses without having to poll the server for a reply” (Mozilla).</p><h4>WebSocket Interfaces</h4><p>Communication with a WebSocket API initially starts as an HTTP handshake. However, if the client and server are able, the connection will continue over WebSockets. When this occurs, we can say that we have a full-duplex (Hackernoon). Meaning that we have a persistent connection or said another way, one that remains open for the complete duration of the session. Moreover, the connection will only end with what is called a CloseEvent.</p><p>WebSockets are comprised of three main components; <strong>WebSocket</strong>, <strong>CloseEvent</strong>, and <strong>MessageEvent</strong>.</p><p>The WebSocket is the primary interface for establishing a connection to the WebSocket Server and also responsible for “… sending and receiving data on the connection” (Mozilla).</p><p>A CloseEvent is simply when the connection between the client and the WebSocket Server closes (Mozilla). Examples of different close events can be found <a href="https://developer.mozilla.org/en-US/docs/Web/API/CloseEvent">here</a>.</p><p>A MessageEvent is “ The event sent by the WebSocket object when a message is received from the server” (Mozilla). Additional information regarding MessageEvents can be found <a href="https://developer.mozilla.org/en-US/docs/Web/API/MessageEvent">here</a>.</p><p>The combination of the WebSocket and the MessageEvent gives “…the server a way to initiate any communication and send off data to pre-subscribed clients, so they don’t have to keep sending in requests inquiring about the availability of new data” (Hackernoon).</p><p>For more visual learners, I’ve included a visual provided by Hackernoon.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*G9QZOffS0nHIBxV07KLoJg.png" /><figcaption>WebSocket Interfaces by Hackernoon</figcaption></figure><p>Thank you for taking the time to learn about WebSockets. I hope this blog has inspired you to try implementing them in an upcoming project. In my next blog, I will show how I solved the code challenge mentioned previously using React, Node.js, Express, and Socket.io. If you are in immediate need, I have included a recommended tools list provided by Mozilla.</p><h4>Tools for Building WebSockets</h4><ul><li><a href="https://hacks.mozilla.org/2017/06/introducing-humblenet-a-cross-platform-networking-library-that-works-in-the-browser/">HumbleNet</a>: A cross-platform networking library that works in the browser. It consists of a C wrapper around WebSockets and WebRTC that abstracts away cross-browser differences, facilitating the creation of multi-user networking functionality for games and other apps.</li><li><a href="https://github.com/uWebSockets/uWebSockets">µWebSockets</a>: Highly scalable WebSocket server and client implementation for <a href="https://isocpp.org/">C++11</a> and <a href="https://nodejs.org/">Node.js</a>.</li><li><a href="https://github.com/ClusterWS/ClusterWS">ClusterWS</a>: Lightweight, fast and powerful framework for building scalable WebSocket applications in <a href="https://nodejs.org/">Node.js</a>.</li><li><a href="https://github.com/ClusterWS/cWS">CWS</a>: Fast C++ WebSocket implementation for Node.js (uWebSockets v0.14 fork)</li><li><a href="https://socket.io/">Socket.IO</a>: A long polling/WebSocket based third party transfer protocol for <a href="https://nodejs.org/">Node.js</a>.</li><li><a href="http://socketcluster.io/">SocketCluster</a>: A pub/sub WebSocket framework for <a href="https://nodejs.org/">Node.js</a> with a focus on scalability.</li><li><a href="https://github.com/Worlize/WebSocket-Node">WebSocket-Node</a>: A WebSocket server API implementation for <a href="https://nodejs.org/">Node.js</a>.</li><li><a href="http://www.totaljs.com/">Total.js</a>: Web application framework for <a href="https://www.nodejs.org/">Node.js</a> (Example: <a href="https://github.com/totaljs/examples/tree/master/websocket">WebSocket chat</a>)</li><li><a href="https://www.npmjs.com/package/faye-websocket">Faye</a>: A <a href="https://developer.mozilla.org/en-US/docs/Web/API/WebSockets_API">WebSocket</a> (two-ways connections) and <a href="https://developer.mozilla.org/en-US/docs/Web/API/EventSource/">EventSource</a> (one-way connections) for <a href="https://nodejs.org/">Node.js</a> Server and Client.</li><li><a href="http://signalr.net/">SignalR</a>: SignalR will use WebSockets under the covers when it’s available, and gracefully fallback to other techniques and technologies when it isn’t, while your application code stays the same.</li><li><a href="https://caddyserver.com/docs/websocket">Caddy</a>: A web server capable of proxying arbitrary commands (stdin/stdout) as a websocket.</li><li><a href="https://github.com/websockets/ws">ws</a>: a popular WebSocket client &amp; server library for <a href="https://nodejs.org/">Node.js</a>.</li><li><a href="https://github.com/bigstepinc/jsonrpc-bidirectional">jsonrpc-bidirectional</a>: Asynchronous RPC which, on a single connection, may have functions exported on the server and, and the same time, on the client (client may call server, server may also call client).</li><li><a href="https://github.com/ninenines/cowboy">cowboy</a>: Cowboy is a small, fast and modern HTTP server for Erlang/OTP with WebSocket support.</li><li><a href="https://websocketking.com/">WebSocket King</a>: A client tool to help develop, test and work with WebSocket servers.</li></ul><p><strong>Resources</strong></p><p>“Michael Carter, Founder and CEO, Game Closure.” <a href="http://www.topionetworks.com,/"><em>Www.topionetworks.com</em>,</a> <a href="http://www.topionetworks.com/people/michael-carter-5799ac941433a1d9df00004f.">www.topionetworks.com/people/michael-carter-5799ac941433a1d9df00004f.</a></p><p>Srushtika. “Everything You Ever Wanted to Know about WebSockets, Literally!” <em>Hacker Noon</em>, 30 Nov. 2020, hackernoon.com/everything-you-ever-wanted-to-know-about-websockets-literally-a05f36432999.</p><p>“Web Technology for Developers.” <em>Web APIs | MDN</em>, Mozilla, developer.mozilla.org/en-US/docs/Web/API/WebSockets_API.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8583403d401d" width="1" height="1" alt=""><hr><p><a href="https://medium.com/swlh/introduction-to-websockets-8583403d401d">Introduction to WebSockets</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[Creating Bash Profile Aliases for Quick Folder Access]]></title>
            <link>https://codeburst.io/creating-bash-profile-aliases-for-quick-folder-access-84fbc325c924?source=rss-d4a2efb0f7fe------2</link>
            <guid isPermaLink="false">https://medium.com/p/84fbc325c924</guid>
            <category><![CDATA[command-line]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[bash]]></category>
            <dc:creator><![CDATA[Matthew Sedlacek]]></dc:creator>
            <pubDate>Mon, 14 Dec 2020 07:50:47 GMT</pubDate>
            <atom:updated>2020-12-17T16:01:21.555Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*RkW59SfEJePK3LhG" /><figcaption>Photo by <a href="https://unsplash.com/@codestorm?utm_source=medium&amp;utm_medium=referral">Safar Safarov</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>As a Software Engineer, I have many files and folders on my computer filled with my various coding projects. Therefore, having to navigate through the many different folders to get to the project I’m looking for in the terminal can take more than a few lines of code. Luckily, there is a better way to navigate to folders and projects. Enter Bash Profile Aliases.</p><p>Before discussing Bash Profile Aliases, let’s take a step back and review some terminology. Software engineers wanting to use the Command-Line Interface (CLI), need to open what’s called the terminal; short for terminal emulator. When the terminal is opened it, “…will immediately start a program called a shell program. The shell program is what actually prompts you for input and returns the output. The shell most computers default to using is known as bash”(Flatiron School).</p><p>Bash contains a Bash Profile where users are able to make customizations. To see where your bash profile and other hidden files/folders are on your computer you can type la -a in your terminal. To open your Bash profile and view it in your code editor type the following.</p><pre>code ~/.zprofile</pre><p>If you have not used your Bash Profile before it will be fairly empty. However, that will quickly change once you start adding your aliases. So, let’s walk through an example. Let’s say I want to add an alias for my projects folder. The first folder in the projects file path is Development, the next folder after development is code, and then the projects folder follows after that. So, to create the alias for projects I would add the following to my Bash Profile.</p><pre>alias projects=&quot;cd ~/Development/code/Projects&quot;</pre><p>Now, in the terminal, I just need to type projects and I’m taken directly to the folder</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/436/1*eRTwmIRsHuGICm_JI9zp4A.png" /><figcaption>Projects alias used in Terminal</figcaption></figure><h3>Conclusion</h3><p>Thank you for taking the time to learn about Bash Profile Aliases. I hope this blog will help save you time and keystrokes.</p><h4><strong>Resources</strong></h4><p>“Cli Essentials Bash Intro.” <em>Learn</em>, learn.co/tracks/module-1-web-development-immersive-3–0/fswd-prework-2–0/cli-essentials/bash-introduction.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=84fbc325c924" width="1" height="1" alt=""><hr><p><a href="https://codeburst.io/creating-bash-profile-aliases-for-quick-folder-access-84fbc325c924">Creating Bash Profile Aliases for Quick Folder Access</a> was originally published in <a href="https://codeburst.io/">codeburst</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Algorithm Solving Strategies]]></title>
            <link>https://medium.datadriveninvestor.com/algorithm-solving-strategies-89ce5248cb03?source=rss-d4a2efb0f7fe------2</link>
            <guid isPermaLink="false">https://medium.com/p/89ce5248cb03</guid>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[interview-tips]]></category>
            <category><![CDATA[algorithms]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Matthew Sedlacek]]></dc:creator>
            <pubDate>Mon, 07 Dec 2020 01:06:17 GMT</pubDate>
            <atom:updated>2020-12-13T11:28:17.131Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Zk95CvUgW6GjcEcn" /><figcaption>Photo by <a href="https://unsplash.com/@wocintechchat?utm_source=medium&amp;utm_medium=referral">Christina @ wocintechchat.com</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>If you read my previous blog regarding <a href="https://medium.com/swlh/big-o-notation-128b7b8051c9">Big O Notation</a>, you may remember that an algorithm is defined as “a finite sequence of well-defined, computer-implementable instructions, typically to solve a class of problems or to perform a computation ” (<a href="https://en.wikipedia.org/wiki/Algorithm">Wikipedia</a>). Algorithms are important for all software engineers to study as they can help us solve problems we may encounter in the work place.</p><p>You may be reading this blog post because you are currently in your job search. If that is the case, <a href="https://leetcode.com/">LeetCode</a> and <a href="https://www.hackerrank.com/">HackerRank</a> both have hundreds of practice algorithm problems for job seekers to leverage. The purpose of this blog is to arm you with a few strategies to help tackle these types of problems and those you may encounter in an interview and on the job.</p><p>The three strategies to be discussed in this blog include the following:</p><ol><li><strong>Frequency Counter</strong></li><li><strong>Multiple Pointers</strong></li><li><strong>Sliding Window</strong></li></ol><p><em>These strategies come from Colt Steele’s JavaScript Algorithms and Data Structures Masterclass Udemy course, which I highly recommend. The examples primarily come from LeetCode.</em></p><h4>Frequency Counter</h4><p>The frequency counter approach can be applied to algorithms where you need to collect values or check the number of occurrences of a value. This strategy utilizes objects or sets and avoids the need for nested loops (Steele). Moreover, frequency counters improve our solutions’ time complexity from O(n²), if using a nested loops, to O(n).</p><p>Now to show the frequency counter strategy in practice, let’s look at an example from Leetcode.</p><pre><strong>Source</strong>: <a href="https://leetcode.com/problems/valid-anagram/">https://leetcode.com/problems/valid-anagram/</a></pre><pre><strong>Problem</strong>:</pre><pre>Given two strings <em>s</em> and <em>t </em>, write a function to determine if <em>t</em> is an anagram of <em>s</em>.</pre><pre>  Test Case #1</pre><pre><strong>     Input:</strong> <em>s</em> = &quot;tennis&quot;, <em>t</em> = &quot;entsno&quot;<br>     <strong>Output: </strong>false</pre><pre>  Test Case #2</pre><pre><strong>     Input:</strong> <em>s</em> = &quot;tan&quot;, <em>t</em> = &quot;nat&quot;<br>     <strong>Output: </strong>true</pre><p>In this example, we will use the frequency counter method to check if each string has all the same letters and those letters appear the same number of times. If both of these checks are true, we know that s and t are anagrams.</p><pre><strong>Solution:</strong></pre><pre><strong>var</strong> isAnagram = function(s, t) {<br>  // if string lengths are different, it&#39;s impossible for string t <br>    // to be an anagram<br>  <strong>if</strong> (s.length !== t.length) {<br>    <strong>return</strong> false;<br>  }</pre><pre>  <strong>const</strong> lookup = {};</pre><pre>  <strong>for</strong> (let i = 0; i &lt; s.length; i++) {<br>    <strong>let</strong> letter = s[i];<br>    // if letter exists, increment by 1, otherwise set to 1<br>    lookup[letter] ? lookup[letter] += 1 : lookup[letter] = 1;<br>  }<br>  <br>  <strong>console.log</strong>(lookup)</pre><pre>   <strong>for</strong> (let i = 0; i &lt; t.length; i++) {<br>    <strong>let</strong> letter = t[i];<br>    // if letter not found or letter value is zero then string t is<br>      // not an anagram of string s<br>    <strong>if</strong> (!lookup[letter]) {<br>      <strong>return</strong> false;<br>    } <strong>else</strong> {<br>      lookup[letter] -= 1;<br>    }<br>    <strong>console.log</strong>(lookup)<br>   }</pre><pre>   <strong>return</strong> true;<br>};</pre><pre>isAnagram(&quot;tennis&quot;, &quot;entsno&quot;)<br>isAnagram(&quot;tan&quot;, &quot;nat&quot;)</pre><pre><strong>Test Case #1 Output</strong>: </pre><pre>// lookup object after looping over s string<br>{ t: 1, e: 1, n: 2, i: 1, s: 1 }</pre><pre>// lookup object decrementing by matching letters in t string <br>  //  after each loop<br>{ t: 1, e: 0, n: 2, i: 1, s: 1 }<br>{ t: 1, e: 0, n: 1, i: 1, s: 1 }<br>{ t: 0, e: 0, n: 1, i: 1, s: 1 }<br>{ t: 0, e: 0, n: 1, i: 1, s: 0 }<br>{ t: 0, e: 0, n: 0, i: 1, s: 0 }</pre><pre>false</pre><pre><strong>Test Case #2 Output</strong>:</pre><pre>// lookup object after looping over s string<br>{ t: 1, a: 1, n: 1 }</pre><pre>// lookup object decrementing by matching letters in t string <br>  //  after each loop<br>{ t: 1, a: 1, n: 0 }<br>{ t: 1, a: 0, n: 0 }<br>{ t: 0, a: 0, n: 0 }</pre><pre>true</pre><p>In the solution above, we first check to see that the strings are the same length. We have this check because if the strings are different lengths, we know they cannot be an anagram and therefore don’t need to work through any additional code. The first loop in the solution creates a summary of all the letters and their frequencies in string s into an object called lookup. The second loop checks that the letter in string t is present in lookup and the value is greater than 0. If these conditions are both true, then the frequency of the letter in lookup is decremented by 1; if not, we know string t is not an anagram of string s. If the second loop iterates through the final letter in string t, then we return true as the frequencies, and all letters in lookup will be 0.</p><h4>Multiple Pointers</h4><p>The multiple pointers strategy is typically used on linear structures (i.e., arrays, strings, and linked lists). The types of problems where multiple pointers are useful are when you need to search for a value or a pair of values that meet a certain condition. Colt Steele describes the process of how this works as follows, “Creating pointers or values that correspond to an index or position and move towards the beginning, end or middle based on a certain condition” (Steele). Steele also goes on to mention that multiple pointer solutions have efficient time complexities O(n) and minimal space complexity O(1).</p><p>Now to show the multiple pointers strategy in practice, let’s look at an example.</p><pre><strong>Source</strong>: <a href="https://leetcode.com/problems/valid-anagram/">C</a>olt Steele&#39;s JavaScript Algorithms and Data Structures Masterclass Course on Udemy</pre><pre><strong>Problem</strong>:</pre><pre>Write a function called sumZero which accepts a <strong>sorted array</strong> of integers.The function should find the first pair where the sum is 0. Return an array that includes both values that sum to zero or undefined if a pair does not exist.</pre><pre>Test Case #1<br>     <br>     <strong>Input</strong> = [-3, -2, -1, 0, 1, 2, 3]<br>     <strong>Output</strong> = [-3, 3]</pre><pre>Test Case #2<br>     <br>     <strong>Input</strong> = [-2, 0, 1, 3]<br>     <strong>Output</strong> = undefined</pre><pre>Test Case #3<br>     <br>     <strong>Input</strong> = [1, 2, 3]<br>     <strong>Output</strong> = undefined</pre><p>In this example, we will use the multiple pointers strategy to see if an array contains two values that when added together equal 0. Since our array is sorted, we can place one pointer at the beginning and one at the end of the array. Then return the values at the two pointers if they sum to 0.</p><pre><strong>Solution:</strong></pre><pre><strong>var</strong> sumZero = function(arr) {<br>     <strong>let</strong> pointer1 = 0<br>     <strong>let</strong> pointer2 = arr.length - 1;<br>     // Needs to be less than instead of less than or equal to<br>        // to prevent a single 0 creating a false positive.<br>      <strong>while</strong>(pointer1 &lt; pointer2) {<br>         <strong>let</strong> sum = arr[pointer1] + arr[pointer2];<br>         <strong>console.log</strong>(sum, arr[pointer1], arr[pointer2])     <br>         <strong>if</strong>(sum === 0) {<br>              return [arr[pointer1], arr[pointer2]];<br>         } <strong>else if</strong>(sum &gt; 0) {<br>              pointer2--;<br>         } <strong>else</strong> {<br>              pointer1++;<br>         }<br>      }<br>};</pre><pre>sumZero([-3, -2, -1, 0, 1, 2, 3])<br>sumZero([-2, 0, 1, 3])<br>sumZero([1, 2, 3])</pre><pre><strong>Test Case #1 Output</strong>:</pre><pre>// console.log of sum, value at pointer1, and value at pointer2<br>0 -3 3</pre><pre>// result<br>[ -3, 3 ]</pre><pre><strong>Test Case #2 Output</strong>:</pre><pre>// console.log of sum, value at pointer1, and value at pointer2<br>1 -2 3<br>-1 -2 1<br>1 0 1</pre><pre>// result<br>undefined</pre><pre><strong>Test Case #3 Output</strong>:</pre><pre>// console.log of sum, value at pointer1, and value at pointer2<br>4 1 3<br>3 1 2</pre><pre>// result<br>undefined</pre><p>In the solution above, we first set the position of pointer1 to the beginning of the array and pointer2 to the end of the array. Then we see what the sum of the values at pointer1 and pointer2 are equal to. If the sum is negative, we need to move pointer1 one value to the right. If the sum is positive, we need to move pointer2 one value to the left. If the sum is 0, then we have found the pair we were looking for and return the values. We continue this pattern until we have either found a pair that sums to 0 or reach the final iteration of the while loop where pointer1’s position is less than the position of pointer2 and return undefined.</p><p><strong>Additional Examples:</strong></p><pre><strong>Source</strong>: <a href="https://leetcode.com/explore/interview/card/top-interview-questions-easy/92/array/727/">https://leetcode.com/explore/interview/card/top-interview-questions-easy/92/array/727/</a></pre><pre><strong>Problem</strong>: </pre><pre>Given a sorted array nums, remove the duplicates <a href="https://en.wikipedia.org/wiki/In-place_algorithm">in-place</a> such that each element appears only once and returns the new length.</pre><pre>Do not allocate extra space for another array, you must do this by modifying the input array <a href="https://en.wikipedia.org/wiki/In-place_algorithm">in-place</a> with O(1) extra memory.</pre><pre><strong>     Input:</strong> nums = [0,0,1,1,1,2,2,3,3,4]<br>     <strong>Output:</strong> 5, nums = [0,1,2,3,4]</pre><pre><strong><br>Solution:</strong></pre><pre><strong>var</strong> removeDuplicates = function(nums) {<br>    <strong>if</strong> (nums.length === 0) {<br>        <strong>return</strong> 0<br>    }<br>    <br>    <strong>let</strong> pointer1 = 0</pre><pre><strong>for</strong> (let pointer2 = 1; pointer2 &lt; nums.length; pointer2++) {<br>        <strong>if</strong> (nums[pointer1] !== nums[pointer2]) {<br>            pointer1++;<br>            nums[pointer1] = nums[pointer2]<br>        }<br>    }<br>    <br>    <strong>return</strong> pointer1 + 1<br>    <br>    <br>};</pre><pre><strong>Source</strong>: <a href="https://leetcode.com/explore/interview/card/top-interview-questions-easy/92/array/567/">https://leetcode.com/explore/interview/card/top-interview-questions-easy/92/array/567/</a></pre><pre><strong>Problem</strong>: </pre><pre>Given an array nums, write a function to move all 0&#39;s to the end of it while maintaining the relative order of the non-zero elements.</pre><pre><strong>     Input:</strong> [0,1,0,3,12]<br>     <strong>Output:</strong> [1,3,12,0,0]</pre><pre><strong>Solution</strong>:</pre><pre><strong>var</strong> moveZeroes = <strong>function</strong>(nums) {</pre><pre><strong>   let</strong> pointer1 = 0<br>    <br>       <strong>for</strong>(<strong>let</strong> pointer2 = 0; pointer2 &lt; nums.length; pointer2++) {<br>           <strong>if</strong>(nums[pointer2] !== 0) {<br>               <strong>let</strong> temp = nums[pointer1]<br>               nums[pointer1] = nums[pointer2]<br>               nums[pointer2] = temp<br>               pointer1++<br>           }<br>       }<br>       <strong>return</strong> nums<br>};</pre><pre>moveZeroes([0,1,0,3,12])</pre><pre><strong>Video Explanation: </strong><a href="https://www.youtube.com/watch?v=0rPuILjoVsg">https://www.youtube.com/watch?v=0rPuILjoVsg</a></pre><h4>Sliding Window</h4><p>The last strategy that we will discuss in this blog is the sliding window. Similar to the multiple pointers strategy, sliding window is typically used on linear structures (i.e., arrays and strings). The types of problems where a sliding window is useful are when you need to find/keep track of a subset of the input that follows some pattern. Colt Steele describes the process of how this works as follows, “This pattern involves creating a window which can either be an array or number from one position to another. Depending on a certain condition, the window either increases or closes (and a new window is created)” (Steele). Also, using a sliding window is preferable as it has an O(n) time complexity.</p><p>Now to show the sliding window strategy in practice, let’s look at an example.</p><pre><strong>Source</strong>: <a href="https://leetcode.com/problems/valid-anagram/">C</a>olt Steele&#39;s JavaScript Algorithms and Data Structures Masterclass Course on Udemy</pre><pre><strong>Problem</strong>:</pre><pre>Write a function called maxSubarraySum which accepts an array of integers and a number called n. the function should calculate the maximum sum of n consecutive elements in the array.</pre><pre>Test Case #1<br>     <br>     <strong>Input</strong> = [1,2,5,2,8,1,5], n = 2<br>     <strong>Output</strong> = 10</pre><pre>Test Case #2<br>     <br>     <strong>Input</strong> = [1,2,5,2,8,1,5], n = 4<br>     <strong>Output</strong> = 17</pre><p>In this example, we will use the sliding window strategy to find the largest sum from a subset of the data. We will do this by creating a window, the size of which is determined by n. Next, we slide the window 1 position to the right and determine if this sum is larger than the previous sums. Then once the final window is summed, we will will return the largest sum.</p><pre><strong>Solution:</strong></pre><pre><strong>function</strong> maxSubarraySum(arr, n){<br>  <strong>let</strong> maxSum = 0;<br>  <strong>let</strong> tempSum = 0;<br>  <strong>if</strong> (arr.length &lt; n) return null;<br>  <strong>for</strong> (let i = 0; i &lt; n; i++) {<br>    maxSum += arr[i];<br>  }<br>  tempSum = maxSum;<br>  <strong>for</strong> (let i = n; i &lt; arr.length; i++) {<br>    tempSum = tempSum - arr[i - n] + arr[i];<br>    maxSum = Math.max(maxSum, tempSum);<br>  }<br>  <strong>return</strong> maxSum;<br>}</pre><pre>maxSubarraySum([1,2,5,2,8,1,5],2)<br>maxSubarraySum([1,2,5,2,8,1,5],4)</pre><pre><strong>Test Case #1 Output</strong>:</pre><pre>// the initial maxSum<br>3</pre><pre>// sliding window, tempSum on left and previous maxSum on right<br>7 3<br>7 7<br>10 7<br>9 10<br>6 10</pre><pre>// result<br>10</pre><pre><strong>Test Case #2 Output</strong>:</pre><pre>// the initial maxSum<br>10</pre><pre>// sliding window, tempSum on left and previous maxSum on right<br>17 10<br>16 17<br>16 17</pre><pre>// result<br>17</pre><p>In the solution above, we first declare two variables, maxSum and tempSum, and set them equal to 0. Then we set an edge case to return null if n, the size of the window, is greater than the array. Next, we find the summation of the first window by looping over only the specified number of n numbers and adding each number to the maxSum variable. Then we set our tempSum variable to the value of maxSum; the temp sum will be our sliding window. Then in our second loop, we find the value of the next window by subtracting the first value from our initial window (arr[0]) and adding the next value in the array that was not in our initial window (i.e., arr[3] if the first window contained arr[0],arr[1],arr[2]) and setting this value to the value of tempSum. Then we use set the value of maxSum equal to the larger of tempSum and the previous maxSum. We continue this process until we reach the end of the array and return maxSum</p><p>Thank you for taking the time to learn more about algorithm solving strategies. I hope this blog has equipped you with a few strategies to help you in your job search and/or workplace.</p><p><strong>Resources</strong></p><p>Steele, C. (n.d.). <em>JavaScript Algorithms and Data Structures Masterclass</em>. Online Course.</p><p>Algorithm. (2020, October 07). Retrieved October 10, 2020, from <a href="https://en.wikipedia.org/wiki/Algorithm">https://en.wikipedia.org/wiki/Algorithm</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=89ce5248cb03" width="1" height="1" alt=""><hr><p><a href="https://medium.datadriveninvestor.com/algorithm-solving-strategies-89ce5248cb03">Algorithm Solving Strategies</a> was originally published in <a href="https://medium.datadriveninvestor.com/">DataDrivenInvestor</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 Add Social Sharing to Your Website]]></title>
            <link>https://medium.com/swlh/how-to-add-social-sharing-to-a-website-18faca91cb64?source=rss-d4a2efb0f7fe------2</link>
            <guid isPermaLink="false">https://medium.com/p/18faca91cb64</guid>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[social-media]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[html]]></category>
            <category><![CDATA[linkedin]]></category>
            <dc:creator><![CDATA[Matthew Sedlacek]]></dc:creator>
            <pubDate>Thu, 26 Nov 2020 22:04:18 GMT</pubDate>
            <atom:updated>2020-11-28T19:15:41.070Z</atom:updated>
            <content:encoded><![CDATA[<h4>LinkedIn, Facebook, Text Messaging, Twitter</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*lzP_0cx6AiBuMqaQ" /><figcaption>Photo by <a href="https://unsplash.com/@helloimnik?utm_source=medium&amp;utm_medium=referral">Hello I&#39;m Nik 🎞</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>I recently created a portfolio website to share with my future employers. One thing that I did not take into consideration, though, is how sharing the link to my website would look on social media sites like LinkedIn, Facebook, etc. So, when I went to add my new portfolio website to my featured section on LinkedIn, LinkedIn provided the following image and text for my post.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/766/1*kxluXR9iMPpBRa--MfDtnw.png" /><figcaption>LinkedIn without Social Sharing</figcaption></figure><p>This is not at all what I wanted. There was no image and no description of the website. To fix this issue, I learned that I needed to add meta tags to the head of my index.html file (see below for the source code).</p><pre>&lt;head&gt;</pre><pre>&lt;!-- Social Sharing --&gt;</pre><pre>   &lt;meta property=&quot;og:image&quot; content=&quot;https://d33wubrfki0l68.cloudfr<br>   ont.net/5fbc10f514319a00073fcbfb/screenshot.png&quot;&gt;</pre><pre>   &lt;meta property=&quot;og:image:type&quot; content=&quot;image/png&quot;&gt;</pre><pre>   &lt;meta property=&quot;og:image:width&quot; content=&quot;1024&quot;&gt;</pre><pre>   &lt;meta property=&quot;og:image:height&quot; content=&quot;1024&quot;&gt;</pre><pre>   &lt;meta property=&quot;og:type&quot; content=&quot;website&quot; /&gt;</pre><pre>   &lt;meta property=&quot;og:url&quot;content=&quot;https://www.matthewsedlacek.com/&quot;<br>   /&gt;</pre><pre>   &lt;meta property=&quot;og:title&quot; content=&quot;Portfolio&quot; /&gt;</pre><pre>   &lt;meta property=&quot;og:description&quot; content=&quot;Visit my portfolio page<br>   to view my contact info, resume, and work samples&quot; /&gt;</pre><pre>&lt;/head&gt;</pre><p>Meta tags define the metadata within an HTML document. Moreover, metadata, “… is used by browsers (how to display content or reload page), search engines (keywords), and other web services” (w3schools.com). Therefore, meta tags allow developers to control how their webpages are viewed by users outside their website.</p><p>In the above example, there are eight different meta tags. All of which I will walk you through. Please note that you do not need all of these types if you are only concerned with posting to LinkedIn (see official documentation <a href="https://www.linkedin.com/help/linkedin/answer/46687/making-your-website-shareable-on-linkedin?lang=en">here</a>).</p><p><strong>1)og:image</strong></p><p>The og:image is the image you would like to be shown in the preview for your website. The image I chose I took from Netlify as they generate a preview image of your website after a successful deployment. You can also take your own screenshot, add it to your repo, and then reference the relative path instead.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5ofGKkYM0LLUQYmHf2Dwew.png" /><figcaption>Netlify Screenshot Image</figcaption></figure><p><strong>2) og:image:type</strong></p><p>The og:image is the type of image you used for og:image. Typically jpg and png are supported.</p><p><strong>3) og:image:width</strong></p><p>The og:image:width is customizable, but LinkedIn allows a maximum 1200-pixel width.</p><p><strong>4) og:image:height</strong></p><p>The og:image:height is customizable, but LinkedIn allows a maximum 627-pixel height.</p><p><strong>5) og:type</strong></p><p>The og:type is often optional but the meta tag details what type of object you are sharing; a website in our case.</p><p><strong>6) og:url</strong></p><p>The og:url is the URL of your website. When your post is clicked on it will take users to your website. This URL is also often used as an ID by the site you are sharing on.</p><p><strong>7) og:title</strong></p><p>The og:title is the display name of the website you are posting. This does not have to be the name of the website. It can be something else entirely.</p><p><strong>8) og:description</strong></p><p>The og:description is a short description of your website and is useful to users as it gives them an idea of what they will see on your website.</p><p><strong>** Important** </strong>If you have tried to add your site to LinkedIn already, you need to clear LinkedIn’s cache. Otherwise, you will need to wait seven days for LinkedIn’s cache to clear automatically. To clear LinkedIn’s cache, go to the following <a href="https://www.linkedin.com/post-inspector/inspect/">website</a> and input your url.</p><p>Now that we have added our meta tags, let’s see what LinkedIn provides us with now.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/765/1*INd1P1NjJPI3qc4Le3cn7A.png" /></figure><p>This is exactly what we wanted! An image preview of our site, the title for our post, and a short description of the website. Let’s see the finished product in LinkedIn and other social applications.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/814/1*rWb2uMEiE_hD4DrttSU93g.png" /><figcaption>LinkedIn Featured Section</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/688/1*JzzrHxHU7K7z9ilR2H2vgA.png" /><figcaption>Facebook</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/669/1*jSk0i2NzNag1nZj6hRXcRg.png" /><figcaption>Text Messaging</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/606/1*Ml1wRJZ0f4KEZ_vDohIfpg.png" /><figcaption>Twitter</figcaption></figure><p>Thank you for taking the time to learn more about Social Sharing. I hope this blog will help you with sharing your future applications across multiple forms of social media.</p><p><strong>Resources</strong></p><p>“Best Practices for Facebook Sharing.” <em>Sharing — Documentation — Facebook for Developers</em>, developers.facebook.com/docs/sharing/best-practices.</p><p>Higgs, James. “How to Add Thumbnail Images to the ‘Featured’ Section of Your LinkedIn Profile (for Web Apps/Sites).” <em>Medium</em>, Medium, 8 May 2020, medium.com/@jamesyhiggs/how-to-add-thumbnail-images-to-the-featured-section-of-your-linkedin-profile-for-web-apps-sites-917346235932.</p><p>“HTML Tag.” <em>HTML Meta Tag</em>, <a href="http://www.w3schools.com/tags/tag_meta.asp.">www.w3schools.com/tags/tag_meta.asp.</a></p><p>“Open Graph Protocol.” <em>The Open Graph Protocol</em>, ogp.me/.</p><p><em>Post Inspector</em>, <a href="http://www.linkedin.com/post-inspector/inspect/">www.linkedin.com/post-inspector/inspect/.</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=18faca91cb64" width="1" height="1" alt=""><hr><p><a href="https://medium.com/swlh/how-to-add-social-sharing-to-a-website-18faca91cb64">How to Add Social Sharing to Your Website</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[Netlify: Custom Domains]]></title>
            <link>https://levelup.gitconnected.com/netlify-custom-domains-8b4cc5fddb5d?source=rss-d4a2efb0f7fe------2</link>
            <guid isPermaLink="false">https://medium.com/p/8b4cc5fddb5d</guid>
            <category><![CDATA[deployment]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[custom-domain]]></category>
            <category><![CDATA[godaddy]]></category>
            <category><![CDATA[netlify]]></category>
            <dc:creator><![CDATA[Matthew Sedlacek]]></dc:creator>
            <pubDate>Mon, 23 Nov 2020 01:26:57 GMT</pubDate>
            <atom:updated>2020-12-22T15:00:28.051Z</atom:updated>
            <content:encoded><![CDATA[<h3>Netlify: Custom Domains with GoDaddy</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*So2oTiGEY51uhCY2" /><figcaption>Photo by <a href="https://unsplash.com/@nasa?utm_source=medium&amp;utm_medium=referral">NASA</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>If you have deployed your app on Netlify but would prefer to use a domain you purchased on GoDaddy, this is the blog for you.</p><p>This guide will walk you through the necessary steps to use your custom GoDaddy domain while continuing to use Netlify and all of its useful deployment features.</p><p><strong>Prework</strong></p><p>This blog assumes that you have already created a Netlify account and purchased a GoDaddy domain. If you have not done so, you can Sign-up/purchase here (<a href="https://app.netlify.com/signup?_ga=2.39371296.2083118729.1605908234-1975371472.1597791247">Netlify</a> &amp; <a href="https://www.godaddy.com/">GoDaddy</a>).</p><p>** <a href="https://www.netlify.com/blog/2018/06/19/buy-and-secure-a-custom-domain-through-netlify/">Please note that Netlify now allows users to purchase domains direct</a> **</p><p>For a tutorial on how to deploy a GitHub Repository to Netlify, please see my blog posted <a href="https://medium.com/swlh/launching-your-first-website-rails-react-42a6af1ab481">here</a>.</p><p><strong>Netlify: Getting Started</strong></p><p>To get started, we first want to identify our default subdomain. We will need to provide GoDaddy with this information later on. To find the default subdomain click on the Domain settings button in the Site overview tab of your Netlify Site.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/860/1*76u73eMuPtCMEPGC5Z7N9w.png" /><figcaption>Site Overview Tab Netlify</figcaption></figure><p>Your default subdomain will be the first item in the Custom domains section.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/611/1*OzjF8OZEubOAGEA_Q-SQbA.png" /><figcaption>Default Subdomain from Netlify</figcaption></figure><p><strong>GoDaddy: DNS Management</strong></p><p>Login to your GoDaddy account and select All Domains from the Domains dropdown.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/555/1*OOXZOQTkMWoYyjmAb0NAZg.png" /><figcaption>GoDaddy Landing Page</figcaption></figure><p>Click on the custom domain you would like to use for your Netlify Site.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Fiz04PvDfGdIFsNnqNf0_Q.png" /><figcaption>List of Domains from GoDaddy</figcaption></figure><p>Scroll down to additional settings and click on Manage DNS. This will populate the custom domains Records.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cCN_Z6cQcfvgUuwuNA-HLg.png" /></figure><p>The records should be pre-populated with all the required fields you need. The only two fields that you need to update are the value fields for Type A and CName. Type A is the IP Address for the Netlify servers and will be the same for all domains and users, 104.198.14.52. The CName is the Netlify default subdomain we identified earlier. Updating this field allows GoDaddy to send the custom domain to the correct Netlify subdomain.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1011/1*CGdFN3eBnk3r9N0J5MiIMA.png" /><figcaption>GoDaddy DNS Management Records</figcaption></figure><p><strong>Netlify: Custom Domain Verification</strong></p><p>Now back in Netlify, we are able to add our custom domain. Click on the Add custom domain button.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/613/1*WC65IMIJ5Ltj0AYALq7qHg.png" /><figcaption>Add Custom Domain</figcaption></figure><p>Next, type in your custom domain, starting with “www.” and click verify.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/525/1*iZmMJ6dspX-fK8MTvOVm2A.png" /></figure><p>If your verification is successful, you should see something similar to what is shown below. Your custom domains should include a default subdomain, primary domain (i.e., <a href="https://www.matthewsedlacek.com/">www.matthewsedlacek.com</a>), and redirect for when users don’t type www (i.e., <a href="https://matthewsedlacek.com/">matthewsedlacek.com</a>).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/610/1*tuvCnfq8hfhRRls0vPWZ2w.png" /></figure><p>Now it’s time to celebrate; you can now share your custom domain with the world!</p><p><strong>Resources</strong></p><p>TopTechNow. “How to connect Netlify to Godaddy (Custom Domain).”<em>YouTube</em>, uploaded by TopTechNow, 18 January 2018, <a href="https://www.youtube.com/watch?v=qbChXHDAK4s">https://www.youtube.com/watch?v=qbChXHDAK4s</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8b4cc5fddb5d" width="1" height="1" alt=""><hr><p><a href="https://levelup.gitconnected.com/netlify-custom-domains-8b4cc5fddb5d">Netlify: Custom Domains</a> was originally published in <a href="https://levelup.gitconnected.com/">Level Up Coding</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Seize the Moment.js]]></title>
            <link>https://levelup.gitconnected.com/seize-the-moment-js-43b3210a27a5?source=rss-d4a2efb0f7fe------2</link>
            <guid isPermaLink="false">https://medium.com/p/43b3210a27a5</guid>
            <category><![CDATA[ruby]]></category>
            <category><![CDATA[ruby-on-rails]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[web-development]]></category>
            <dc:creator><![CDATA[Matthew Sedlacek]]></dc:creator>
            <pubDate>Sun, 15 Nov 2020 18:43:18 GMT</pubDate>
            <atom:updated>2020-11-29T13:24:57.084Z</atom:updated>
            <content:encoded><![CDATA[<h4>Converting Ruby Strings to Local Time in React</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*WdDLybS53W0L3WdG" /><figcaption>Photo by <a href="https://unsplash.com/@fabrizioverrecchia?utm_source=medium&amp;utm_medium=referral">Fabrizio Verrecchia</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>In a recent coding challenge, I was tasked with building a chat application. One of the requirements was to show the time the message was posted. My first thought was to use the Ruby created_at string provided by my fetch. However, that string looks like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/441/1*isUupHPFdCdxLztIutLIaw.png" /><figcaption>Created_at string from Ruby on Rails Backend</figcaption></figure><p>My next thought was to convert the date in my backend rails model, but this also proved problematic as the times that came through were in UTC.</p><pre># app/models/application_record.rb</pre><pre><strong>class</strong> ApplicationRecord &lt; ActiveRecord::Base<br>   self.abstract_class = true</pre><pre>   <strong>def</strong> created_at<br>      attributes[&#39;created_at&#39;].strftime(&quot;%Y-%m-%d %H:%M %Z&quot;)<br>   <strong>end</strong></pre><pre><strong>end</strong>  </pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/241/1*lThGjLxuLHrLTgmeZjwqaw.png" /><figcaption>Rendering in Chat Application</figcaption></figure><p>In addition, the time zone I was living in was different from the time zone of the company I was applying to.</p><p>My solution to this problem came in the form of Moment.js. Moment is a JavaScript date and time library specifically built to deal with these kinds of issues. You can see their helpful docs <a href="https://momentjs.com/">here</a> or some examples down below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/804/1*Kjuwz7iZfC6-bfTiZNDvPA.png" /><figcaption>Moment.js examples from <a href="https://momentjs.com/">https://momentjs.com/</a></figcaption></figure><p>In my chat application, another requirement was to display only the most recent ten messages, with the most recent being on the top and the least recent on the bottom. My app needed to allow for many users to post at once, and I, therefore, needed to be very precise with how I sorted my posts. Thus, I sorted the Ruby strings I mentioned before and did not use Moment.js till the lowest possible component. The component I used was a function component. See below for the source code.</p><pre>// src/components/chatbox/MessageCard.js</pre><pre><strong>import</strong> React from &quot;react&quot;;<br><strong>import</strong> Grid from &quot;@material-ui/core/Grid&quot;;<br><strong>import</strong> ListItem from &quot;@material-ui/core/ListItem&quot;;<br><strong>import</strong> ListItemText from &quot;@material-ui/core/ListItemText&quot;;</pre><pre><strong>const</strong> moment = require(&quot;moment&quot;);</pre><pre><strong>const</strong> MessageCard = (props) =&gt; {</pre><pre><strong>   let</strong> dateString = props.timestamp;</pre><pre><strong>   let</strong> dateObj = new Date(dateString);</pre><pre><strong>   let</strong> momentObj = moment(dateObj);</pre><pre><strong>   let</strong> momentString = momentObj.format(&quot;MMMM Do YYYY, h:mm:ss a&quot;);</pre><pre><strong>   return</strong> (</pre><pre>       &lt;ListItem&gt;</pre><pre>         &lt;Grid item xs={12}&gt;</pre><pre>           &lt;ListItemText align=&quot;left&quot; secondary={momentString}&gt;<br>           &lt;/ListItemText&gt;</pre><pre>         &lt;/Grid&gt;</pre><pre>       &lt;/ListItem&gt;</pre><pre>   );</pre><pre>};</pre><pre><strong>export</strong> default MessageCard;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/512/1*hbi17mRn-uixIRA49UaYAQ.png" /><figcaption>Final Rendering in Chat Application</figcaption></figure><p>I hope this blog will help you with formatting dates and times in future applications. In an upcoming blog, I will discuss WebSockets, which enabled me to log messages as they occurred and share those messages with everyone connected to the app.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=43b3210a27a5" width="1" height="1" alt=""><hr><p><a href="https://levelup.gitconnected.com/seize-the-moment-js-43b3210a27a5">Seize the Moment.js</a> was originally published in <a href="https://levelup.gitconnected.com/">Level Up Coding</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Recursion]]></title>
            <link>https://medium.com/swlh/recursion-overview-example-c3d9780f118c?source=rss-d4a2efb0f7fe------2</link>
            <guid isPermaLink="false">https://medium.com/p/c3d9780f118c</guid>
            <category><![CDATA[algorithms]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[recursion]]></category>
            <dc:creator><![CDATA[Matthew Sedlacek]]></dc:creator>
            <pubDate>Mon, 09 Nov 2020 00:16:09 GMT</pubDate>
            <atom:updated>2020-11-09T20:18:25.141Z</atom:updated>
            <content:encoded><![CDATA[<h4>Overview &amp; Example</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*zU98xqGHgm5-p2FK" /><figcaption>Photo by <a href="https://unsplash.com/@ptrikutam?utm_source=medium&amp;utm_medium=referral">Pavan Trikutam</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p><strong>What is Recursion?</strong></p><p>A recursive function is a function that calls itself. It’s important to learn recursion because it’s used in common built-in JavaScript methods such as JSON.parse, JSON.stringify, and document.getElementById (Steele). Also, recursion is essential to understanding Tree and Graph traversal algorithms, which we will discuss in future blogs.</p><p><strong>What is the Call Stack?</strong></p><p>Before diving any deeper into our discussion of recursion, it’s helpful to discuss the call stack. A call stack is used in most programming languages. It is a, “… built in data structure that manages what happens when functions are invoked” (Steele).</p><p>When functions are invoked, they are placed on the top of a call stack. To help visualize this, think of stacking boxes. In order to get to the first box, you need to take off the boxes stacked on top of it.</p><p>How this relates to recursion is that “When we write recursive functions, we keep pushing new functions onto the call stack!” (Steele). Or, more precisely, we are pushing the same function onto the call stack over and over again. Now, you may be thinking this sounds like it would produce an infinite loop. However, as we will see in the next section, there are two key parts of a recursive function, one of which prevents an infinite loop from happening and another that pushes functions onto the call stack.</p><p><strong>Essential Parts of a Recursive Function</strong></p><p>The two essential parts of a recursive function are the recursive call and the base case. The recursive call is in the body of our function and where the function is calling itself and pushing the function onto the call stack. The base case is also in the body of our function and is the stopping point for our recursive calls (Learn). If there were no base case, the function would be in an infinite loop and run forever. Moreover, this is referred to as a stack overflow because too many functions are being put on the call stack (Steele).</p><p><strong>Recursion in Code</strong></p><p>Now that we know the essential parts of a recursive function and its impact on the call stack let’s see it in code.</p><p>To demonstrate recursion, we will write a function that mimics a factorial. For those who may have forgotten their 7th grade math class, a factorial is, “…the product of all positive integers less than or equal to n” (Wikipedia). The factorial of 5 for example is 5! = 5 x 4 x 3 x 2 *1 = 120.</p><pre><strong>function</strong> factorial(num) {<br>// This line represents the base case. We want our recursive function to stop when num = 1 because if we multiply by 0 our output becomes 0 and factorials only include positive integers. Also, if we don&#39;t stop our recursive function we will have a stack overflow/infinite loop as we continue past 1 and onto 0 and negative numbers.  <br>   <strong>if</strong> (num === 1) <strong>return</strong> 1;<br>// This line represents our recursive call and num is decrementing by 1 each time until the base case condition is met, 1 in our case. See image below to see how the recursive calls are stacked on top of each other in the call stack.<br>   <strong>return</strong> num * <strong>factorial</strong>(num -1)<br>}</pre><pre><strong>factorial</strong>(5)</pre><pre><strong>Output</strong>: 120<br></pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fn42pOtkgdQ1P4V8JmOELg.png" /><figcaption>Call Stack Image provided by lecture material presented in Colt Steele’s Udemy Course</figcaption></figure><p>The image above uses Google Chrome’s dev tools and demonstrates how our recursive function stacks our factorial function in the call stack and does not begin evaluating until we reach our base case. In the above example, the first item off of our call stack is the base case return 1. The next action to take place is multiple 1 by 2, then multiply 2 by 3, then 6 by 4, and lastly multiply 24 by 5 to reach out result of 120. The key thing to notice here is that multiplying by 5 is last to be evaluated, but the first added to the call stack. Conversely, the base case is last to be added to the call stack but the first to be evaluated. Remember back to the comparison between recursive functions and stacking boxes from earlier.</p><p>Thank you for taking the time to learn more about recursion. I hope you now understand the importance of recursion and apply it as you write and interpret code.</p><p><strong>Resources</strong></p><p>Steele, C. (n.d.). <em>JavaScript Algorithms and Data Structures Masterclass</em>. Online Course.</p><p>Recursion. (n.d.). Retrieved November 11, 2020, from <a href="https://learn.co/lessons/recursion-readme">https://learn.co/lessons/recursion-readme</a></p><p>Factorial. (2020, November 11). Retrieved November 11, 2020, from <a href="https://en.wikipedia.org/wiki/Factorial">https://en.wikipedia.org/wiki/Factorial</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c3d9780f118c" width="1" height="1" alt=""><hr><p><a href="https://medium.com/swlh/recursion-overview-example-c3d9780f118c">Recursion</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>