<?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 Jorge Moller on Medium]]></title>
        <description><![CDATA[Stories by Jorge Moller on Medium]]></description>
        <link>https://medium.com/@_jmoller?source=rss-329d486a68ca------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*EKT9Epyi1Wr4OZ3vZnZp4A.jpeg</url>
            <title>Stories by Jorge Moller on Medium</title>
            <link>https://medium.com/@_jmoller?source=rss-329d486a68ca------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 17 Nov 2026 15:02:44 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@_jmoller/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[How to add authentication to your Next JS app with Clerk]]></title>
            <link>https://medium.com/@_jmoller/how-to-add-authentication-to-your-next-js-app-with-clerk-40554f2eabf6?source=rss-329d486a68ca------2</link>
            <guid isPermaLink="false">https://medium.com/p/40554f2eabf6</guid>
            <category><![CDATA[authentication]]></category>
            <category><![CDATA[nextjs]]></category>
            <dc:creator><![CDATA[Jorge Moller]]></dc:creator>
            <pubDate>Sat, 03 Apr 2021 00:10:39 GMT</pubDate>
            <atom:updated>2021-04-03T14:58:07.324Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BcixE0Q7rmQRpUS-K32sYg.png" /></figure><p>This is a quick tutorial on how to easily add authentication and user management to your Next JS app using <a href="https://www.clerk.dev/">Clerk.dev</a></p><h4>Create the Next JS application</h4><p>Run the following command to create a Next JS application from your terminal:</p><pre>$ create-next-app clerk-playground</pre><p>Let’s install clerk (from your application’s root directory):</p><pre>$ cd clerk-playground</pre><pre>$ npm install @clerk/clerk-react</pre><pre># or</pre><pre>$ yarn add @clerk/clerk-react</pre><h4>Create a Clerk account and application</h4><p>Go to <a href="https://accounts.clerk.dev/sign-up">https://accounts.clerk.dev/sign-up</a> and signup for a new account. Once you do that, sign in and you will be redirected to clerk’s dashboard, something like this 👇</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nXn34IufiZlM0FR_NSMMkQ.png" /></figure><p>Create a new application by clicking Create Application. You can either choose from quick start with Next JS and Vercel or choose a standard (more flexible) setup. For this tutorial I’ll choose Standard Setup.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BfHLTkd5k8j8c-OJOtdkxA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qQ9D6aTR2tYWdD1s6yT43Q.png" /></figure><p>This will create a new clerk application with two instances: one for production and one for development. We will be using the development instance.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*y6N2BYMH976t5IbCIxZAdw.png" /></figure><p>Click on the development instance</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6xLUBdYy6Q-5Sab_htBczw.png" /></figure><p>Copy and paste the Frontend API and Sign in URL in your clipboard as we are going to be using those next.</p><h4>Add clerk to our Next JS app</h4><p>Create a .env.local file in the root of the clerk-playground application.</p><pre>$ touch .env.local</pre><p>Add the following environment variables and set their values to the Frontend API and Sign in url, the ones shown in the screenshot above.</p><pre>NEXT_PUBLIC_CLERK_FRONTEND_API=XXXXXXXXXXXXXXXXXXXXXXXXX</pre><pre>NEXT_PUBLIC_CLERK_SIGN_IN=XXXXXXXXXXXXXXXXXXXXXXXXX</pre><p>Replace your pages/_app.js with this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e4bf465c118b2580d5a76429d817d73c/href">https://medium.com/media/e4bf465c118b2580d5a76429d817d73c/href</a></iframe><p>A couple of things going on there:</p><ol><li>The ClerkProvider component wraps your React application to provide active session and user context to Clerk’s hooks and other components.</li><li>The SignedIn and SignedOut components are used to control rendering depending on whether or not a visitor is signed in.</li><li>publicRoutes is an array of routes that can be accessed by an unauthenticated user. e.g. <a href="http://www.yourapp.com/contact-us">www.yourapp.com/contact-us</a></li></ol><h4>Let’s create some routes!</h4><p>Replace the pages/index.js file with this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f2e3a91d6d45042ba729095ee6379f41/href">https://medium.com/media/f2e3a91d6d45042ba729095ee6379f41/href</a></iframe><p>The UserButton component implements the de facto standard for allowing a user to manage their account, switch accounts, sign out.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/460/1*lvCDy3_2WZUgkQyLMJiuhg.png" /></figure><p>Lets create a new file under the pages folder called pages/contact-us.js and add this code to it:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/239677473180d5b14014d38d0443ebee/href">https://medium.com/media/239677473180d5b14014d38d0443ebee/href</a></iframe><p>Add this new route to the array of public routes in the _app.js like so:</p><pre>const publicPages = [&#39;/contact-us&#39;]</pre><p>Let’s fire up the server by running:</p><pre>$ yarn run dev</pre><pre># or</pre><pre>$ npm run dev</pre><p>You should see something like this 👇</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nmqJaJ-fN-KaSxWsib0CkQ.png" /></figure><p>By default Next JS is going to pull up the index.js file, which is a protected/authenticated route (because we didn’t add it to the array of public routes), therefore we are going to be asked to either sign in or signup in order to view that route.</p><p>If you signin/signup you should be redirected to localhost:3000/ which holds the index.js route.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/566/1*XjY98d-Lnygx0CtiqdPpyA.png" /></figure><p>If you change the url to localhost:3000/contact-us You should see 👇</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/754/1*IIe_qMWjJ4z0HsfWM4k-uQ.png" /></figure><p>You are all set now!, you can start managing your users from the Users screen in Clerk 👇</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*p86qtWU608th5tcn7PP7KA.png" /></figure><p>Follow me on twitter for more content like this ;) <a href="https://twitter.com/_jmoller">https://twitter.com/_jmoller</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=40554f2eabf6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[JS Design Patterns: Part 2]]></title>
            <link>https://medium.com/@_jmoller/js-design-patterns-part-2-538c2bc06aca?source=rss-329d486a68ca------2</link>
            <guid isPermaLink="false">https://medium.com/p/538c2bc06aca</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[strategy-pattern]]></category>
            <category><![CDATA[mediator-pattern]]></category>
            <category><![CDATA[observer-pattern]]></category>
            <category><![CDATA[design-patterns]]></category>
            <dc:creator><![CDATA[Jorge Moller]]></dc:creator>
            <pubDate>Fri, 22 Mar 2019 00:03:49 GMT</pubDate>
            <atom:updated>2019-03-22T00:03:49.629Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UNs0gqbEfsMJ9QrLSNhw2Q.png" /></figure><h4>Strategy</h4><h4>Intent</h4><p>This pattern enables you to select algorithms at runtime. Define a family of algorithms, encapsulate each one, and make them interchangeable.</p><h4>Motivation</h4><p>Imagine we have a form, and we have to do some kind of form validation. We can create one validator object with a <strong>validate()</strong> method. This is the method that will be called regardless of the concrete type of the form, and will always return the same result, in our case, a list of data that didn’t validate and error messages associated to them.</p><p>Depending on the concrete form and the data to be validated, the consumers of our validator may choose different types of checks. Our validator picks the best <em>strategy</em> to handle the task and delegates the concrete data checks to the appropriate algorithm.</p><h4>Structure</h4><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*uC_nkcZIc1eNq_YJqV3I_Q.jpeg" /></figure><h4>Implementation</h4><p>Let’s assume we have the following data coming from a particular form in our application:</p><pre>var data = {<br>        name: &#39;John&#39;,<br>        lastName: &#39;Doe&#39;,<br>        age: &quot;twenty eight&quot;,<br>        username: &#39;john_doe&#39;<br>    }</pre><p>For our validator object to know which is the best strategy to follow in this concrete example, we need to configure the validator first and set some rules of what we consider to be valid.</p><p>This is how our validation rules look like:</p><ol><li>Name: is required, only string values are valid.</li><li>Last name: not required</li><li>Age: not required, only numeric values are valid.</li><li>Username: is required, letters and numbers only, no special characters are allowed.</li></ol><pre>validator.config = {<br>    name: [&#39;isNonEmpty&#39;, &#39;isString&#39;],<br>    age: [&#39;isNumber&#39;],<br>    username: [&#39;isAlphaNum&#39;]<br>};</pre><p>This is how we would use our validator to validate the data:</p><pre>validator.validate(data);<br>    if (validator.hasErrors()) {<br>        console.log(validator.messages.join(&#39;\n&#39;));<br>    }<br><br>    // In our case it should output the following<br>    Invalid value for age, the value can only be a valid number.<br>    Invalid value for username, the value can only contain characters and numbers, no special characters are allowed</pre><p>Let’s take a look at how the validator is implemented. The algorithms for the validations are objects with a predefined interface, they provide a <strong>validate()</strong> method and an <strong>instructions</strong> property that holds helpful information to show to the user.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a30ec373523baf01baf16cdd8fc27776/href">https://medium.com/media/a30ec373523baf01baf16cdd8fc27776/href</a></iframe><h4>Facade</h4><h4>Intent</h4><p>To provide an alternative interface to a set of interfaces in a subsystem. Facade defines a higher-level interface that makes the subsystem easier to use.</p><h4>Motivation</h4><p>When we split up a system into multiple subsystems we reduce code complexity. A best practice when programming is to minimize the communication and dependencies between subsystems. A nice way to achieve this is by introducing a <strong>facade</strong> object that provides a single and unified interface to the subsystems.</p><h4>Structure</h4><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*aVvOtxhGxXeqvuczB4ZbbQ.jpeg" /></figure><p>It’s a nice practice in programming, in general, for a function or method to only have one responsibility or job. Sometimes two or more of these functions may commonly be called together, and in this case, it makes sense to create another function that wraps the repeating two methods.</p><p>Let’s think of the following browser events: 1. <strong>stopPropagation()</strong>: it traps the event and prevent subsequent calls to the parent nodes. 2. <strong>preventDefault</strong>: it prevents the browser from doing its default function. (For example: when submitting a form)</p><p>Although this are two separate methods with different purposes, they are usually called together. So instead of calling the two methods every time we need to use them through-out our application, we can create a <strong>facade</strong> method that calls both of them:</p><pre>    var myEvent = {<br>        //...<br>        stop: function(e) {<br>            e.preventDefault();<br>            e.stopPropagation();<br>        }<br>        //...<br>    }</pre><p>In this example, we are providing a higher level interface for our functions to use. Whenever we need to use it we just call <em>myEvent.stop(e)</em></p><p>Although this is a very simple example of how to apply the facade pattern, it captures the essence very well. Just think of implementing this pattern when you need to provide a higher level API or interface to subsystems.</p><p>The facade pattern is highly used when redesigning and refactoring code. When you want to replace an object with a different implementation, and this has to be done over a period of time because its a complex object, but at the same time new code is being written that uses this object. We can start by thinking of the new object’s API and then we can create a facade in front of the old object that uses the new API.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8b972fbe9343be7a2fe51eca370b2a0b/href">https://medium.com/media/8b972fbe9343be7a2fe51eca370b2a0b/href</a></iframe><h4>Proxy</h4><h4>Intent</h4><p>To provide an object that acts as an interface to another object. The difference with the facade pattern is that the facade provides convenience methods that wrap other methods calls. The proxy pattern lives between the client of an object and the object itself. It offers a way of protecting access to that object.</p><h4>Motivation</h4><p>Imagine that we need to initialize a web page, and it contains certain objects (such as images or videos) that are expensive to initialize, by initialize I mean, the object to be visible to the client. A good approach here would be to use <em>lazy initialization</em> or in simpler terms, just show those objects on demand.</p><p>In this example, the proxy pattern can be helpful by acting as the interface between the client and the object to be initialized. The proxy will receive the initialization request but it will never pass it down to the object (image, video) until the client requests for that object to be shown.</p><h4>Structure</h4><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*Tx_zL-CdwBRk3rsxuSTl7g.jpeg" /></figure><p>This pattern is useful when the object does something expensive, if we think about web applications, one of the most expensive operations is a network request, so it makes sense to combine HTTP requests as much as possible.</p><p>Let’s say we are working on a web app that plays videos of a selected artist. We have a list of videos titles on a page, and when the user clicks a video title, the area below the title expands to show more information about the video and also a video player to start playing it. This information and the url of the video need to be retrieved from the server by making a web service call. The web service can accept multiple video IDs, so that we can speed up the application by maker fewer HTTP requests.</p><h4>Implementation without Proxy</h4><pre>var videos = {<br>    getInfo = function(id) {<br>        if (id) {<br>            http.makeRequest([id]).then(<br>                (res) =&gt; res.data.info,<br>                (err) =&gt; throw new Error(err.message)<br>            )<br>        }<br>    }<br>}</pre><p>In this implementation, the video object communicates directly with the http object. Every time the user clicks on a title, we are calling the <strong>videos.getInfo(id)</strong> method with the id of that particular video. (For simplification purposes let’s assume we have the id of a video in the HTML element that displays the title of that video). In this scenario, we are making a request to the server every time a click occurs in the title of a video. This can be improved.</p><p>Let’s add a proxy object that takes over the communication between the videos and the http objects. It will try to combine requests using a 100ms buffer. In this scenario, the videos object doesn’t call the HTTP service directly but call the proxy instead. The proxy then waits 100ms and groups any subsequent clicks, so that we can make only one request. This way we will handle a smaller number of requests.</p><p>Here is how the code for the proxy looks like:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/95c74c2d8b4b0186088de09a2e37775c/href">https://medium.com/media/95c74c2d8b4b0186088de09a2e37775c/href</a></iframe><p>By adding the proxy we know can combine multiple web service requests into only one.</p><h4>Mediator</h4><h4>Intent</h4><p>An object that encapsulates how a set of objects interact. The mediator pattern promotes <em>loose coupling</em> by keeping objects from referring to each other explicitly.</p><h4>Motivation</h4><p>Applications are made of objects, and these objects need a way to communicate with each other in a manner that doesn’t hurt maintenance and the ability to change a part of the application without breaking the rest of it. As the application grows, new objects are introduced, and old objects are removed and rearranged. When objects know too much about each other and communicate directly, for example by calling each others methods, this leads to <em>tight coupling</em>. When objects are closely coupled, it makes changes and maintainability difficult.</p><p>In this pattern, the objects don’t communicate directly to each other, but through a <em>mediator</em> object. When one of the objects changes its state, it notifies the mediator, and the mediator communicates the change to other objects that should know about this.</p><h4>Structure</h4><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*k7XuBvDa82IDMT4_sCnozg.jpeg" /></figure><p>Let’s showcase this pattern through an application that will be a game where two players are given half a minute to compete for who will press a button more times than the other. Player 1 competes by pressing 1, and player 2 presses 0.</p><p>The objects involved are:</p><ol><li>Player 1</li><li>Player 2</li><li>Scoreboard</li><li>Mediator</li></ol><p>The mediator object is the only one that knows about all other objects. It communicates with the input device, in our case the keyboard, handles keyboard events, determines which player has a turn and notifies it. The player plays and notifies the mediator when it’s done. The mediator then provides the updated score to the scoreboard.</p><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*w2AOEMTPhpcnp6jdlOVzmQ.jpeg" /></figure><p>Let’s look at the implementation of the game.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fb4e7b533c0e0a78b273d68811bf6ad8/href">https://medium.com/media/fb4e7b533c0e0a78b273d68811bf6ad8/href</a></iframe><h4>Observer</h4><h4>Intent</h4><p>The Observer pattern is one of the most used patterns in client-side JavaScript programming. All the browser events such are using this pattern under the hood. The intent of this pattern is to define a one-to-many dependency between objects so that when one object changes state, all its dependents are notified and updated automatically.</p><h4>Motivation</h4><p>The main motivation behind this pattern is to promote <em>loose coupling</em>. Instead of an object calling another object&#39;s method to notify that it has changed, an object subscribes to another object’s specific activity and gets notified when this other object has changed.</p><p>There are two main actors in this pattern, the subscriber (observer) and the publisher (the observed object). The publisher notifies all the subscribers when an event occurs.</p><h4>Structure</h4><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*d9PJQe5DyQ111JaPRCj0Rw.jpeg" /></figure><p>Let’s see this pattern in action with an example. We are going to create a <strong>paper</strong> application, that publishes a daily newspaper and a monthly magazine. A subscriber John, will be notified whenever that happens.</p><p>The <strong>paper</strong> object is our publisher in this scenario and John the subscriber. Our <strong>paper</strong> needs to have a property <strong>subscribers</strong> that is an array that holds all the subscribers. When an event occurs, our paper object will loop through the array of subscribers and notify them. The notification means calling a method of the subscriber object, therefore when subscribing to the paper object, the subscriber provides one of its methods to the paper’s subscribe() method.</p><p>The paper can also have an <strong>unsubscribe()</strong> method that removes a subscriber from the list. Our last method of paper is <strong>publish()</strong>, this is the method that triggers the notification to the subscribers, in other words, will call the subscribers’ methods.</p><p>To summarize, a publisher object needs the following methods:</p><ol><li>Subscribers: Array</li><li>subscribe(): Add to the array of subscribers</li><li>unsubscribe(): remove from the subscriber&#39;s array</li><li>publish(): loop through subscribers and call the methods they provided when they signed up.</li></ol><p>All these methods need a type parameter because a publisher may fire several events (either publish a newspaper or a magazine) and subscribers may choose to subscribe to one, but not the other one.</p><p>Let’s look at the implementation:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/aec52b933f89e01d4406eddf9dc3d85d/href">https://medium.com/media/aec52b933f89e01d4406eddf9dc3d85d/href</a></iframe><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=538c2bc06aca" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[JS Design Patterns]]></title>
            <link>https://medium.com/@_jmoller/js-design-patterns-12de08e06edb?source=rss-329d486a68ca------2</link>
            <guid isPermaLink="false">https://medium.com/p/12de08e06edb</guid>
            <category><![CDATA[singleton-pattern]]></category>
            <category><![CDATA[factory-pattern]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[design-patterns]]></category>
            <category><![CDATA[decorator-pattern]]></category>
            <dc:creator><![CDATA[Jorge Moller]]></dc:creator>
            <pubDate>Sun, 10 Mar 2019 21:17:40 GMT</pubDate>
            <atom:updated>2019-07-24T19:34:48.275Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*h6swwrILUaktxPmXByw3Tg.png" /></figure><h3>Singleton</h3><h4>Intent</h4><p>Ensure a class only has one instance, and provide a global point of access to it.</p><h4>Motivation</h4><p>It’s important for some classes to have exactly one instance. For example, think of an e-commerce application where we have a ShoppingCart class. We need one and only one instance of that class throughout the application. There is no need to have multiple carts for a single user.</p><h4>Structure</h4><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*NIqBAc_fNtLTM8pc8csxoA.png" /></figure><p>How can we apply this idea to JavaScript? Let’s first see what the expected behavior of this pattern looks like:</p><pre>    var person = new Person();<br>    var person2 = new Person();<br>    person === person2 // true</pre><p>In this example the person is created only the first time the constructor is called, for subsequent calls to the constructor, it returns the person that was created the first time.</p><p>We need a way of caching in the Person constructor, the <strong><em>this</em></strong> instance so that we can return it in subsequent calls.</p><p>There are different ways we can achieve this:</p><ol><li>We can use global variables to store the instance, but aren’t globals a bad practice? Yes, they are. So let’s see other possible solutions.</li><li>Caching the instance in a static property of the constructor. The only drawback is that the instance property would be publicly accessible, meaning that code outside might change it, and we don’t want that.</li><li>Wrapping the instance in a closure. This makes the instance private and not available to the public for modifications.</li></ol><p>Let’s see how the second and third approach looks like in code:</p><h4>Instance in Static Property</h4><pre>    function Person(name, lastName) {<br>        // Do we have an existent instance of the constructor? if  so, please return the instance<br>        if ( typeof Person.instance === &#39;object&#39;) {<br>            return Person.instance;<br>        }<br><br>        // Define some properties as usual<br>        this.name = name;<br>        this.lastName = lastName;<br><br>        Person.instance = this;<br>    }<br><br>    var person = new Person(&#39;John&#39;, &#39;Doe&#39;);<br>    var person2 = new Person(&#39;Alex&#39;, &#39;Foo&#39;);<br>    person === person2 // true</pre><h4>Instance in a Closure</h4><pre>    function Person(name, lastName) {<br>        var instance = this;<br>        this.name = name;<br>        this.lastName = lastName;<br><br>        Person = function(name, lastName) {<br>            return instance;<br>        }<br>    }</pre><p>The first time the user calls the constructor with new, it saves a reference to the instance (this) in a variable called instance, it overrides the constructor and returns the instance.</p><p>The second time the user calls the constructor is actually calling to the override function that returns the instance (available to us thanks to the power of closures).</p><blockquote>Important: instance is only accessible from the lexical scope of person, this also includes the body of the Person function declared later.</blockquote><p>The problem with this implementation is that the rewritten function will lose the properties added to the prototype object between the first and second instance of the constructor. Here is the problem in more detail:</p><pre>  Person.prototype.prop1 = &#39;property 1&#39;;<br><br>  var person = new Person();<br>  <br>  Person.prototype.prop2 = &#39;property 2&#39;;<br><br>  var person2 = new Person();<br>  <br>  console.log(person.prop1); // logs &#39;property 1&#39;<br>  console.log(person2.prop1); // logs &#39;property 1&#39;<br>  console.log(person.prop2); // logs undefined<br>  console.log(person2.prop2); // logs undefined<br> <br>  person.constructor.name; // Person<br>  person.constructor === Person; // false</pre><p>The reason why person.constructor === Person logs false, is because the constructor of the instance of Person (the one created the first time) points to the first Person function. In the second call to the Person constructor, we lose the reference to the outer function because we rewrite it with the second (inner) function.</p><p>A possible solution to this problem is the following:</p><pre>    function Person() {<br>        var instance;<br><br>        Person = function() {<br>            return instance;<br>        }<br>        // We set the constructor of instance to always be the              function that overwrites Person.<br>        instance = new Person;<br>        instance.name = &#39;Bob&#39;;<br>        return instance;<br>    }</pre><p>Another possible solution would be:</p><pre>    // Alternative Solution 1    </pre><pre>    var Person;<br>    (function(){<br>        var instance;<br><br>        Person = function Person() {<br>            if (instance) {<br>                return instance;<br>            }<br>            instance = this;<br>            instance.name = &#39;Bob&#39;;<br>        }<br>    })();<br>  </pre><h3>Factory</h3><h4>Intent</h4><p>Define an interface for creating an object, but let subclasses decide which class to instantiate. Factory method lets a class defer instantiation to subclasses.</p><h4>Motivation</h4><p>The main goal of the factory is to create objects. You will usually see this pattern implemented in a class or in a static method of a class. It has the two following purposes: 1. Performs repeating operations when setting up similar objects 2. It offers a way for the client of the factory to create objects without knowing the specific type (class) at compile time.</p><h4>Structure</h4><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*UZ9X6wxyT8ffnlT8Fx9ESA.jpeg" /></figure><p>The objects that are created by the <em>createFactory</em> method, are inheriting from the same parent object, they are subclasses that implement special functionality.</p><p>Let’s create an Animal factory that handles the creation of different types of animals:</p><ol><li>We’ll have a common AnimalFactory constructor.</li><li>A static method of the AnimalFactory class, called <strong><em>createFactory</em>()</strong>. This method will handle the creation of different types of animals.</li><li>Specialized constructors such as AnimalFactory.Monkey, AnimalFactory.Snake, AnimalFactory.Dog that inherit from AnimalFactory. We will define all of this specialized constructors as static properties of the parent constructor AnimalFac.</li></ol><p>Let’s see how the finish implementation of this pattern looks like:</p><h4>Implementation</h4><pre>    var monkey = AnimalFactory.createFactory(&#39;Monkey&#39;);<br>    var snake = AnimalFactory.createFactory(&#39;Snake&#39;);<br>    var dogo = AnimalFactory.createFactory(&#39;Dog&#39;);<br><br>    monkey.getLegs(); // I have 2 legs<br>    snake.getLegs(); // I have 0 legs<br>    dogo.getLegs(); // I have 4 legs</pre><p>One possible way of implementing a solution would be the following;</p><pre>function AnimalFactory () {};<br><br>// We extend the animal factory functionality by adding a getLegs function that returns the amount of legs of an specific animal.<br>AnimalFactory.prototype.getLegs = function() {<br>        return  &#39;I have &#39; + this.legs + &#39; legs&#39;;<br>}<br><br>AnimalFactory.createFactory = function (type) {<br>    var constr = type, instance;<br>    <br>    if (typeof AnimalFactory[constr] !=== &#39;function&#39;) {<br>        throw new Error(&#39;The constructor &#39; + constr +  &#39; does not exist&#39;);<br>    }<br> // at this point the constructor is known to exist so we have it inherit from the parent<br>    if (typeof AnimalFactory[constr].prototype.getLegs !== &#39;function&#39;) {<br>            AnimalFactory[constr].prototype = new AnimalFactory();<br>    }<br>    <br>    instance = new AnimalFactory[constr]();<br>    return instance;<br>};<br><br>// Specific constructor for the different types of animal. The only singularity about this constructors is that they are assigned to a static property of the AnimalFactory class, apart from that everything looks normal. We can call any of this constructors like this: var monkey = AnimalFactory[&#39;Monkey&#39;];<br>AnimalF.Monctoryakey = function() {<br>    this.legs = 2;<br>}<br>AnimalFactory.Snake = function() {<br>    this.legs = 0;<br>}<br>AnimalFactory.Dogo = function() {<br>    this.legs = 4;<br>}</pre><p>There is nothing complex about this implementation. The main goal of the factory pattern is to look for the constructor function that creates an object of a specific type.</p><p>The inheritance part of the implementation has nothing to do with the factory pattern, it’s just a common technique we can use to reuse code, instead of putting the getLegs method in every constructor type.</p><h3>Iterator</h3><h4>Intent</h4><p>The iterator pattern provides the client with a way of looping over a collection of objects.</p><h4>Motivation</h4><p>An aggregate object (an object that contains other objects), should give us a way to access its elements without exposing its internal structure. In addition, we might want to traverse the object in different ways, depending on what we want to accomplish.</p><h4>Structure</h4><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*C22XMu6jbrcA0j-wtziH8w.jpeg" /></figure><p>In the iterator pattern, the object needs to provide a <strong>next()</strong> method. Calling <strong>next()</strong> must return the next consecutive element. It’s up us to decide what “next” means.</p><p>The aggregate object usually provides another method called <strong>hasNext()</strong>, so that the users of the object know if they have reached the end of the data.</p><p>The implementation of such aggregate object looks like this:</p><h4>Implementation</h4><pre>var aggObj = (function() {<br>  var index = 0,<br>        data = [1, 2, 3, 4, 5],<br>        length = data.length;<br><br>        return {<br>            next: function() {<br>                var element;<br>                if (this.hasNext()) {<br>                    element = data[index];<br>                    index = index + 2;<br>                    return element;<br>                }<br>                return null;<br>            },<br>            hasNext: function() {<br>                return index &lt; length;<br>            }<br>        }<br>} )()<br>console.log(aggObj.next()); // 1<br>console.log(aggObj.next()); // 3<br>console.log(aggObj.next()); // 5<br>console.log(aggObj.next()); // null</pre><h3>Decorator</h3><h4>Intent</h4><p>The decorator provides a way to add additional functionality to an object, dynamically.</p><h4>Motivation</h4><p>Let’s imagine that we are the owners of a MacBook store. We sell MacBooks with different specifications, and the price of a MacBook depends on those specifications. Let’s say that the entry price for a MacBook is 1000 dollars. If we add, for example, an SSD disk, the price increases, if the user wants a MacBook with Retina display, the price increases and so on and so forth. These add-ons are decorators to our MacBooks. Let’s also assume that the warranty of the MacBooks depends on the add ons.</p><h4>Implementation</h4><p>Here is a simple implementation of the decorator pattern for our example:</p><pre>function Macbook() {<br>  this.price = 1000;<br>  this.warranty = 0.5;<br>  this.decorators_list = {};<br>}<br><br>Macbook.decorators = {};<br><br>Macbook.decorators.memory = {<br>  getPrice: function(price) {<br>    return price + 400;<br>  }<br>};<br><br>Macbook.decorators.ssd = {<br>  getPrice: function(price) {<br>    return price + 500;<br>  },<br>  getWarranty: function(warranty) {<br>    return warranty + 1;<br>  }<br>}<br><br>Macbook.decorators.retinaDisplay = {<br>  getPrice: function(price) {<br>    return price + 700;<br>  },<br>   getWarranty: function(warranty) {<br>    return warranty + 1.5;<br>  }<br>}<br><br>Macbook.prototype.decorate = function(method, decorator) {<br>  this.decorators_list[method] =   this.decorators_list[method] || [];<br>  this.decorators_list[method].push(decorator);<br>}<br><br>Macbook.prototype.getPrice = function() {  <br>  return this.price;<br>}<br><br>Macbook.prototype.getWarranty = function() {<br>  return this.warranty;<br>}<br>// Just a helper method that takes a name method and a property, and converts it to a decorated method<br>function makeDecoratedMethod(method, prop) {<br>  Macbook.prototype[method] = function() {<br>  var i = 0, <br>      max = this.decorators_list[method].length,<br>      name,<br>      res = this[prop];<br>  <br>  for (i; i &lt; max; i ++) {<br>    name = this.decorators_list[method][i];<br>    res = Macbook.decorators[name][method](res);<br>  }<br>  return res;<br>}<br><br>}<br><br>makeDecoratedMethod(&#39;getPrice&#39;, &#39;price&#39;);<br>makeDecoratedMethod(&#39;getWarranty&#39;, &#39;warranty&#39;);<br><br>var mb = new Macbook();<br>mb.decorate(&#39;getPrice&#39;,&#39;memory&#39;);<br>mb.decorate(&#39;getPrice&#39;,&#39;ssd&#39;);<br>mb.decorate(&#39;getPrice&#39;,&#39;retinaDisplay&#39;);<br>mb.decorate(&#39;getWarranty&#39;, &#39;retinaDisplay&#39;);<br>console.log(mb.getPrice()); // 2600<br>console.log(mb.getWarranty()); // 2</pre><p>The idea behind this implementation is to have a list of decorators stored in an object where the key is the name of a method and the value is the list of decorators for that particular method.</p><p>As you can see, this is a flexible way of adding functionality to our object on demand.</p><h3>Conclusion</h3><p>We went through some popular design patterns, and how we can apply them in javascript. Bear in mind that most design patterns come from statically typed languages such as C#, Java. JavaScript, however, is a dynamic language and some of the patterns discussed here have little use in javascript. Nevertheless, it doesn’t hurt to know how to apply them in javascript.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=12de08e06edb" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Javascript data structures: Stacks and Queues]]></title>
            <link>https://medium.com/@_jmoller/javascript-data-structures-stacks-and-queues-ea877d72a5f9?source=rss-329d486a68ca------2</link>
            <guid isPermaLink="false">https://medium.com/p/ea877d72a5f9</guid>
            <category><![CDATA[stack]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[data-structures]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[queue]]></category>
            <dc:creator><![CDATA[Jorge Moller]]></dc:creator>
            <pubDate>Thu, 07 Mar 2019 02:09:29 GMT</pubDate>
            <atom:updated>2019-03-07T02:09:29.985Z</atom:updated>
            <content:encoded><![CDATA[<h3>Javascript Data Structures: Stack and Queue</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*O-C-ZYvH9jsf8Tot0If5Rg.png" /></figure><h4>Stacks</h4><p>Stacks are an elementary data structure, they are the last item in, the first item out (LIFO). The last item added into the stack will be the first one taken out of the stack.</p><p>Stacks are basically arrays where the only thing you can do, more or less, is to push and pop.</p><p>Let’s go through the interface needed to build a stack. We need a <strong>storage</strong> variable that holds whatever it is that we are trying to put into our stack. It’s basically a reference to our stack. Regarding the methods, as we mentioned before, we need a method that allows us to add an element into the stack (push), one that allows as to remove and return the last element from the stack (pop), and it would also be nice to have a method that returns the actual size of the stack. In addition to this, we are going to add the last method called peek, that returns the last element from the stack.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_3SPFo9lvJ2rx5VMDZdUug.png" /></figure><p>For the following implementation, we are going to store the elements in an object, therefore our storage variable will hold a reference to an object of key-value pairs. As keys, we are using integers from 0 to the maximum capacity of the stack.</p><p>Here is how it looks like:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4c633d8fc53afa00524fada3f1753e16/href">https://medium.com/media/4c633d8fc53afa00524fada3f1753e16/href</a></iframe><h4>Queues</h4><p>Queues are, the first item added to the queue will be the first one taken out of the queue (FIFO). When adding an item into the queue that operation is called <em>enqueuing</em> and when we take out an item from the queue the operation is called <em>dequeuing</em>.</p><p>Let’s go through the interface of building a Queue.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HbRk1sNiaFLUamFaFr_O7g.png" /><figcaption>queue interface</figcaption></figure><p>Here is how the implementation looks like:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/db6311fb31ec8afde64abd64f0367c18/href">https://medium.com/media/db6311fb31ec8afde64abd64f0367c18/href</a></iframe><h3>Exercise 1</h3><p>Problem: Implement a MinStack. A stack with a min() method that returns the minimum value of the stack in O(1);</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/bb521e6e6fc7226e222fa691fe0f3383/href">https://medium.com/media/bb521e6e6fc7226e222fa691fe0f3383/href</a></iframe><h3>Exercise 2</h3><p>Problem: Implement a Queue with two stacks.</p><p>The solution to this common problem relies on having one stack to enqueue elements and the other stack to only dequeue elements.</p><p>We know for the definition of the stack, that the last item in has to be the first out, so our dequeue stack has to have the elements in reverse order so that when we want to dequeue one, we are actually pulling out the first element in, therefore following the queue specification.</p><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*AhXPqU1JPmQ4gJsSmAV9bw.jpeg" /></figure><p>Let’s see how the implementation of this looks like:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b57393575a83f0432090c5fa57c764b2/href">https://medium.com/media/b57393575a83f0432090c5fa57c764b2/href</a></iframe><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ea877d72a5f9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Javascript Clases and Inheritance]]></title>
            <link>https://medium.com/@_jmoller/javascript-clases-and-inheritance-1f8de29c845c?source=rss-329d486a68ca------2</link>
            <guid isPermaLink="false">https://medium.com/p/1f8de29c845c</guid>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[es6]]></category>
            <category><![CDATA[patterns]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[inheritance]]></category>
            <dc:creator><![CDATA[Jorge Moller]]></dc:creator>
            <pubDate>Mon, 04 Mar 2019 19:22:30 GMT</pubDate>
            <atom:updated>2019-03-20T20:46:35.922Z</atom:updated>
            <content:encoded><![CDATA[<h3>Javascript Classes and Inheritance ES6, ES5</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*B5lXa_6sLSVsbTAq7Rz6rQ.png" /></figure><p>Every developer should strive to write code as reusable as possible. Over time it has huge advantages; writing less code, making it more readable, maintainable and extensible are just a few that comes to mind.</p><p>In the following post, we are going to focus on inheritance, and how we can harness its power to write reusable code. Bear in mind that this is one of many methods to reuse code, but I have found it to be a critical aspect when writing javascript applications.</p><h4>Classes in ES6</h4><p>Classes are special functions, and just as you can define a function expression and a function declaration the class syntax has two components:</p><ol><li>Class declarations</li></ol><pre>    class Reactangle {<br>        constructor(width, height) {<br>            this.width = width;<br>            this.height = height;<br>        }<br>    }</pre><ol><li>Class Expressions</li></ol><pre>    // unnamed<br>    var Rectangle = class {<br>        constructor(width, height) {<br>            this.width = width;<br>            this.height = height;<br>        }<br>    }<br><br>    //named<br>    var Rectangle = class Rectangle{<br>        constructor(width, height) {<br>            this.width = width;<br>            this.height = height;<br>        }<br>    }</pre><blockquote>Important: an important difference between function declarations and class declarations is that function declarations are hoisted and class declarations are not.</blockquote><p>Example:</p><pre>var r = new Rectangle(); // Reference error<br><br>class Rectangle {<br>  ...<br>}</pre><h4>Constructors in ES6</h4><p>The constructor function is a special method for creating and initializing an object created with class.</p><p>Something to take into consideration is that there can be only one constructor within a class, otherwise, a SyntaxError will be thrown.</p><p>A constructor can also make use of the <strong>super</strong> keyword to call the constructor of the superclass.</p><h4>Inheritance in ES6</h4><p>The <strong>extends</strong> keyword is used in class declarations to create a class as a subclass or child of another class.</p><p>For example:</p><pre>class Animal {<br>    constructor(name) {<br>        this.name = name;<br>    }</pre><pre>    speak() {<br>        console.log(this.name + &#39;makes noise&#39;);<br>    }<br>}</pre><pre>class Dog extends Animal {<br>    constructor(name, breed) {<br>        super(name);<br>        this.breed = breed;<br>    }</pre><pre>    speak() {<br>        super.speak();<br>        console.log(this.name + &#39;barks&#39;);<br>    }<br>}</pre><pre>let dog = new Dog(&#39;Bolt&#39;, &#39;White German Shepherd&#39;)<br>dog.speak(); <br>// Bolt makes noise<br>// Bolt barks</pre><p>This is the very (very) basics of classes and inheritance in ES6. But, back in the day when javascript did not have the class, extends and super keyword, how did all of this work?</p><p>I think it’s imperative to understand how things worked before ES6, because when we do, we know what is happening under the hood with classes and inheritance in ES6.</p><p>So let’s dive into the classical way of defining classes and implementing inheritance in JavaScript.</p><h4>Classical Pattern #1 — The default Pattern</h4><p>To understand inheritance, we first need to understand how the prototype chain works.</p><p>The default method to create inheritance is to create an object using a constructor and then assign this object to the child’s prototype. Here is how it look like</p><pre>function Parent(name) {<br>        this.name = name || &#39;Adam&#39;;<br>    }<br>    <br>    // Adding some functionality to the person&#39;s prototype<br>    Parent.prototype.say = function() {<br>        return this.name;<br>    }<br>    <br>    // Empty child constructor<br>    function Child(name) {};<br><br>    function inherit(Child, Parent) {<br>        // We are just pointing the prototype property of Child to                                    // an object, in this case the object is an instance of the Parent.<br>        Child.prototype = new Parent();<br>    }<br><br>    inherit(Child, Parent);<br>    <br>    // Here the kid gets functionality from the Parent() instance //via the prototype.<br>    var kid = new Child();<br>    kid.say(); // &#39;Adam&#39;</pre><p>Using this pattern we inherit both own properties and prototype properties and methods.</p><p>Now, let’s dive under the hood and see what happens with the prototype chain that makes this behavior possible.</p><p>In the following picture, we have two code blocks, the one on the left is when we create an object using <strong>new Parent()</strong>. In this case, we create a code block that holds data for the name property. The one on the right is the prototype object of Parent.</p><p>Behind the scenes, the left code block has a <strong>proto</strong> link that points to the <strong>prototype</strong> object of the constructor function Parent().</p><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*6g7sdbF-LBScNzeQZEw19Q.png" /></figure><p>Now, let&#39;s see what happened when a new object is created, using <strong>var kid = new Child()</strong> (After using the inherit function implemented by us).</p><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*OKr-tOY4VwdXY12OBtf8mA.png" /></figure><p>Remember that the hidden <strong>proto</strong> link always points to the prototype property of that object. In our case, in the inherit() function, we said that we want our Child.prototype pointing to the new Parent() object. This is why the hidden <strong>proto</strong> link now points to the new Parent() object.</p><p>What happens when we do <strong>kid.say()</strong>. First it looks up that method in the Child object, and because it doesn’t exist there, it goes up through the prototype chain and looks it up in the Parent object, which doesn’t have it either, so it searches one more time in the <strong>proto</strong> link (going up in the prototype chain) and finds it there. Now, the say() method has a reference to <strong>this.name</strong> which needs to be resolved. The lookup starts again, in this case, <strong>this</strong> points to new Child() object which doesn’t have <strong>name</strong>. Then, the code block in new Parent() is consulted and it does have a name property with the value “Adam”.</p><p>Let’s take a look at one more example:</p><pre>var kid = new Child();<br>    kid.name = &quot;John&quot;;<br>    kid.say(); // John;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*Mj2KlA95Lq3clgZ63NgBgg.png" /></figure><p>When we set kid.name, we are not overriding the name property of the parent, we are creating a new property owned by the Child object. When we do kid.say(), the same thing happens when trying to look up the say() method. But this time, looking up this.name is quick, because the property is found immediately in the Child’s object.</p><h4>Classical Pattern #2 — Rent a constructor</h4><p>In this pattern, we make use of the parent constructor, passing the child object to be bound to <strong>this</strong> and also forwarding any arguments:</p><pre>function Child(a, b, c, d) {<br>   Parent.apply(this, arguments);<br>}</pre><p>Bear in mind, that by using this pattern we can only inherit properties added to <strong>this</strong> inside the parent constructor, we do not inherit members that were added to the prototype.</p><p>By using this pattern, we basically get a copy of the inherited members, unlike the pattern #1 where we only get references.</p><p>Let’s look at an example:</p><pre>function Animal() {<br>   this.types = [&#39;reptile&#39;, &#39;insect&#39;];<br>} </pre><pre>var animal = new Animal();<br><br>// A Lion that inherits from animal using the pattern #1<br>function Lion() {}<br>Lion.prototype = animal;<br>var lion = new Lion();<br>    <br>// A Monkey that intherits from animal using the pattern #2<br>function Monkey() {<br>    Animal.call(this);<br>}<br>var monkey = new Monkey();<br><br>console.log(animal.hasOwnProperty(&#39;types&#39;)); // true<br>console.log(lion.hasOwnProperty(&#39;types&#39;)); // false<br>console.log(monkey.hasOwnProperty(&#39;types&#39;)); // true<br>  <br>lion.types.push(&#39;felidae&#39;);<br>monkey.types.push(&#39;mammals&#39;)<br>console.log(animal.types.join(&#39;, &#39;)); // &quot;reptile, insect, felidae&quot; <br>console.log(monkey.types.join(&#39;, &#39;)); // &quot;reptile, insect, mammals&quot;</pre><p>In this example, we can clearly see that the lion object modifies the types property of the animal object, unlike monkey which only modifies its own copy of types.</p><p>Let’s see how the prototype chain looks like when using this pattern.</p><pre>    function Parent(name) {<br>        this.name = name || &#39;Adam&#39;;<br>    }<br><br>    // Add some functionality to the prototype<br>    Parent.prototype.say = function() {<br>        return this.name;<br>    }<br><br>    // child constructor<br>    funciton Child(name) {<br>        Parent.apply(this, arguments);<br>    }<br><br>    var kid = new Child(&#39;John&#39;);<br>    kid.name; // &#39;John&#39;<br>    typeof kid.say; // undefined</pre><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*KaAG47lsmlMtUhuqsZZU1w.jpeg" /></figure><p>The main downside of using this pattern is that we don’t inherit anything from the prototype, and the prototype is the place to add reusable methods and properties.</p><p>An advantage is that you get copies of the parent’s own members ( all members of <strong>this</strong> instance, will get copied)</p><p>Let’s look at yet another example of how to approach classes and inheritance in javascript that will address the issues from pattern #2.</p><h4>Classical Pattern #3 — Rent and Set Prototype</h4><p>In this pattern we will combine the previous two, we are first going to borrow the constructor and then also set the child’s prototype to post to a new instance of the constructor:</p><pre>    function Child(a, b, c, d) {<br>        Parent.apply(this, arguments);<br>    }<br>    Child.prototype = new Parent();</pre><p>By following this pattern, we get objects that hold copies of the parent’s own members and also we have references to the parent’s reusable functionality (because of the prototype).</p><p>A downside is that we are calling the constructor twice, so it not that efficient.</p><p>Let’s see this pattern in action with the following example:</p><pre>function Parent(name) {<br>    this.name = name || &#39;Adam&#39;;<br>}<br><br>Parent.prototype.say = function() {<br>    return this.name;<br>}<br><br>function Child() {<br>    Parent.apply(this, arguments);<br>}<br>Child.prototype = new Parent();<br><br>var kid = new Child(&#39;John&#39;);<br>kid.name; // &#39;John&#39;<br>kid.say(); // &#39;John&#39;<br>delete kid.name;<br>kid.say(); // &#39;Adam&#39;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*KxwirgGLgQ7XpylmnWv8hw.jpeg" /></figure><p>Unlike the previous pattern, say() is now inherited. There is something interesting about this example, when we delete the name property from kid and then call say(), javascript looks up the name property of child and doesn’t find it there so it goes up the prototype chain and looks it up in the parent object. Parent has a property name set to ‘Adam’, so that what gets printed in the console.</p><h4>Classical Pattern #4 — Share the Prototype</h4><p>In the next pattern, we are going to see how to get rid of the call to the parent constructor.</p><p>We know that reusable members should go to the prototype and not <strong>this</strong>. Therefore, anything that is worth inheriting should be in the prototype. What would happen if we set the child’s prototype to be the same as the parent’s prototype? Let’s see.</p><pre>    function inherit(C, P){<br>        C.prototype = P.prototype;<br>    }</pre><p>This is how the prototype chain would look like:</p><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*uc68kAc7wSliWiKtbXrwIA.jpeg" /></figure><p>Let’s look at an example:</p><pre>function Parent(name) {<br>    this.name = name || &#39;Adam&#39;;<br>}<br><br>Parent.prototype.say = function(){<br>  return this.name;<br>}<br><br>function Child(name) {<br>    // How can I inherit the name property from Parent!!??<br>    this.name = name;<br>}<br><br>function inherit(C, P){<br>  C.prototype = P.prototype;<br>}<br><br>inherit(Child, Parent);<br><br>var kid = new Child(&#39;John&#39;);<br>console.log(kid.name); // John<br>console.log(kid.say()); // John</pre><p>Well, although both child and parent objects share the same prototype, therefore have access to the say() function, the children objects don’t inherit the <strong>name</strong> property. A workaround to this would be to add the Parent.call(this, name); in the Childs constructor, to get a copy of the name property.</p><h4>ES6 Classes under the hood</h4><p>Let’s wrap up this post going under the hood of ES6 classes, what kind of magic are they doing??!!.</p><p>Let’s just create a very simple Animal class, and see to what it compiles to in ES5.</p><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*UwBRLI60R-YgsAN1Rd7NIg.png" /></figure><p>Right off the bat, we can see that an immediate function gets executed and assigned to the Animal variable.</p><p>The second thing to notice is that a constructor gets created, and a strange function (_classCallCheck) gets called with the instance of the constructor and the constructor (function) itself. Let’s see what this function does.</p><pre>function _classCallCheck(instance, Constructor) {<br>    if (!(instance instanceof Constructor)) {<br>        throw new TypeError(&quot;Cannot call a class as a function&quot;);<br>    }<br>}</pre><p>It just checks if we are calling the constructor as a function or with the <strong>new</strong> keyword. Remember that the new keyword tells javascript to create an empty object and assign that empty object to <strong>this</strong> inside the constructor.</p><pre>var animal = new Animal(&#39;lion&#39;); // Everything ok<br><br>var animal = Animal(&#39;lion&#39;); <br>// Not ok, we are calling the constructor function without the new //keyword, therefore javascript uses the immediate this from it&#39;s //lexical scope, which in our case points to the window object, and //the window object is not an instance ot the Animal constructor.</pre><p>Great, so far so good, now in line 6 it sets the name member of this to the value we pass as an argument to the constructor, nothing weird here.</p><p>In line 9 is where the magic happens. There is a method _createClass that gets called. This method passes two parameters, the Animal function, and an array of objects containing a key property that hold the name of the functions declared in our Animal class, and a value property that holds, well, the function itself.</p><p>Let’s peek this _createClass function, shall we?</p><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*DXIYETbCvfSaia4UHzOT2g.png" /></figure><p>In line 11 we notice that it returns a function that takes a Constructor (in our case the Animal function) and also some protoProps (in our case, the array with object that holds the key and value for our class functions). For now, let’s not worry about the staticProps.</p><p>It checks if there are protoProperties (functions), if so, it calls the defineProperties function with the Constructor.prototype (Animal.prototype in our case) and with the protoProperties (array of object that hold the functions).</p><p>Let’s analyze the signature of the defineProperties function. It takes a target, which is the constructor.prototype and some props which are an array of objects that holds our class functions.</p><p>Now let’s dive into the function and explain what it does in each and every step.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b0d7248d12c95f804a734b12b7b1d639/href">https://medium.com/media/b0d7248d12c95f804a734b12b7b1d639/href</a></iframe><p>After all of this magic happens, it just returns the constructor.</p><h3>Conclusion</h3><p>I really hope you have found something useful in this post, if you have any comments or suggestions don’t hesitate to write them in the comment section.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1f8de29c845c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Javascript Functions]]></title>
            <link>https://medium.com/@_jmoller/javascript-functions-794c46e4139c?source=rss-329d486a68ca------2</link>
            <guid isPermaLink="false">https://medium.com/p/794c46e4139c</guid>
            <category><![CDATA[javascript-tips]]></category>
            <category><![CDATA[software]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[patterns]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Jorge Moller]]></dc:creator>
            <pubDate>Wed, 27 Feb 2019 13:53:10 GMT</pubDate>
            <atom:updated>2019-04-02T12:24:18.967Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*M9cY0UHTbmlBfoPMCQwxYA.png" /></figure><p>Every javascript developer should know his way around functions because the language has many uses for them. The goal of this post is to explain the different types of functions, how the local scope and the variable hoisting works. Also, we will dive into some useful patterns to provide better interfaces for our functions.</p><p>There are two important factors of a function in JavaScript:<br>1. Functions are objects.<br>2. Functions provide scope.</p><p>If you are not familiar with the term scope in JavaScript, it means basically where your variables are available.</p><p>It may not be obvious why functions are objects, so let&#39;s look at the following example:</p><pre>var times = new Function(&#39;a,b&#39;, &#39;return a * b&#39;);<br>times(2,3); // returns 6</pre><p>In this code, we can clearly see that times() is an object because It was created by a constructor. Bear in mind that creating functions this way is not recommended.</p><p>The second important feature is that functions provide scope. In javascript we don’t have curly braces local scope, meaning that blocks don’t create scope. There is only function scope. Every variable declared within a function is scoped to that function, and not accessible outside of that function.</p><p>When we say that curly braces don’t provide local scope it means that a variable declared inside of an if, for or while statement, it doesn’t mean that that variable is local to that if or for. <strong>It’s only local to the wrapping function</strong>.</p><h3>Function Declarations vs Function Expressions</h3><p>There are two ways to define a function in javascript: <em>function expressions and function declarations</em>. Function expressions can be both named or unnamed (anonymous). Let’s take a look at an example:</p><pre>// named function expressions<br>var times = function times(a,b) {<br> return a * b;<br>}</pre><pre>// unnamed function expression<br>var times = function (a,b) {<br> return a * b;<br>}</pre><pre>// function declaration<br>function foo() {<br> // function body <br>}</pre><h3>Function Hoisting</h3><p>From the above example, you might think that the behavior of <em>function declarations</em> is the same as the <em>function expressions</em>. That is not entirely correct, the difference lies in the hoisting behavior.</p><p>In the creation phase, javascript hoists all variables to the top of the function. The same applies to functions, as they are just objects assign to variables. The only problem here is when we try to invoke a function expression before it’s declaration point. Let’s look at an example:</p><pre>function hoistMe() {</pre><pre> console.log(typeof foo); &quot;function&quot;<br> console.log(typeof bar); &quot;undefined&quot;</pre><pre> foo(); // &quot;local foo&quot;<br> bar(); // TypeError: bar is not a function</pre><pre> // function declaration<br> function foo() {<br>  alert(&#39;local foo&#39;);<br> }</pre><pre> // function expression<br> var bar = function() {<br>  alert(&#39;local bar&#39;);<br> }<br>}<br>hoistMe();</pre><p>The main difference here is that foo()’s definition is hoisted to the top and works just fine, although it’s defined later, but the definition of bar() is not hoisted, only the declaration is hoisted and initialized as <strong><em>undefined</em></strong>. This is what happens:</p><pre>function hoistMe() {<br> var bar = undefined;</pre><pre> console.log(typeof foo); &quot;function&quot;<br> console.log(typeof bar); &quot;undefined&quot;</pre><pre> foo(); // &quot;local foo&quot;<br> bar(); // TypeError: bar is not a function</pre><pre> // function declaration, it is stored in memory in <br> // creation phase so when it reaches its invokation <br> // it&#39;s available<br> function foo() {<br>  alert(&#39;local foo&#39;);<br> }</pre><pre> // function expression<br> bar = function() {<br>  alert(&#39;local bar&#39;);<br> }<br>}<br>hoistMe();</pre><p>Now that we understand the very basics of functions in JavaScript let’s go through some of the patterns related to them.</p><h3>Callback Pattern</h3><p>A callback function it’s just a function being passed as an argument to another function. When this happens we say that the function being passed is a callback function, because eventually, it’s likely to execute.</p><p>Let’s take a look at an example and start without a callback first and then refactor it later. Imagine we have a general-purpose function that does some complicated work and returns a large data set as a result. Let’s call it <strong>findNodes()</strong>, and the task of this function is to crawl the DOM tree of a page and return an array of page elements that are interesting to us:</p><pre>var findNodes = function() {<br>  var i = 100000, // big loop<br>  nodes = [], // array od nodes<br>  found; // the next node found</pre><pre>  while (i) {<br>   i -= 1;<br>   // complex logic here<br>   nodes.push(found);<br>  }<br>  return nodes;<br>}</pre><p>It’s a good idea to keep this function generic and have it simply return an array of DOM nodes, without doing anything with the actual elements.</p><p>We can write the logic of modifying the nodes in a different function, for example, a function called <strong>hide()</strong> which hides the node&#39;s elements that are being passed as a parameter.</p><pre>var hide = function (nodes) {<br> var i = 0, max = nodes.length;<br> for (i; i &lt; max; i += 1) {<br>  nodes[i].style.display = &quot;none&quot;;<br> }<br>}</pre><pre>// Executing both functions<br>hide(findNodes());</pre><p>This implementation is not very efficient, because hide() has to loop again through the array of nodes returned by findNodes(). It would be much more efficient if we were to hide each node as soon as we get a hold of it in the findNodes function. This is a great case where we can make use of the <strong><em>callback pattern.</em></strong> Let’s do some refactor then.</p><pre>var findNodes = function(callback) {<br>  var i = 100000,<br>  nodes = [],<br>  found;</pre><pre>  // check whether we can call callback<br>  if (typeof callback !== &quot;function&quot;) {<br>   callback = false;<br>  }</pre><pre>  while (i) {<br>   i -= 1;<br>   // complex logic here<br>  <br>   // if possible invoke callback with our node<br>   if (callback) {<br>    callback(found);<br>   }<br>   nodes.push(found);<br>  }<br> return nodes;<br>}</pre><p>The additional task performed by findNodes now is to check whether a callback is being passed as an argument, if so then call it with every node we found. Now, there is some more refactoring left to do in the hide() function.</p><p>Bear in mind that the callback function can be an existing function like in the example shown above, or it can also be an anonymous function (unnamed function expression), which we create as we call the main function.</p><p>Here is we would call findNodes with an anonymous function:</p><pre>findNodes(function(node) {<br> node.style.display = &quot;none&quot;;<br>});</pre><h3>Callbacks and Scope</h3><p>There are different scenarios where the callbacks are not an anonymous or a global function, but a method of an object. If the method uses <strong>this</strong> to refer to the object it belongs to, it can produce some unexpected behavior.</p><p>For example:</p><pre>var myObj = {<br> color: &#39;green&#39;,<br> paint: function (node) {<br>  node.style.color = this.color;<br> }<br>};</pre><p>What would happen if we call the findNodes function with the paint method as it’s callback? Something like this <em>findNodes(myObj.paint)</em>.</p><p>The object <strong><em>this</em></strong> will refer to the global object because <strong>findNodes()</strong> is a global function. If findNodes() were a method of an object called <strong>dom</strong> for example, like dom.findNodes(), then this will refer to the <strong>dom</strong> object instead.<br> <br>A practical solution to this problem would be to pass the callback function and in addition the object to where the callback function belongs to.</p><pre>findNodes(myObj.paint, myObj);</pre><pre>...</pre><pre>var findNodes = function(callback, callback_obj) {<br>  // ...<br>  if (typeof callback === &#39;function&#39;) {<br>   callback.call(callback_obj, node);<br>  }<br>  // ...<br>}</pre><h3>Returning Functions</h3><p>Functions can be used as a return value, meaning that a function can return another function, or it can create another function and then return it.</p><p>Let’s have a look at an example:</p><pre>var setup = function() {<br>  alert(1);<br>  return function () {<br>   alert(2);<br>  }<br> }</pre><pre> // using the setup function<br> var mySetup = setup(); // alerts 1<br> mySetup(); // alerts 2</pre><p>Because setup() wraps the returned function, it creates a closure (a closure is just the combination of variables and the environment on where those variables were defined), and we can make use of this closure to store some private data. An example would be a counter that gives you an incremented value every time you call it:</p><pre>var counter = function() {<br>  var count = 0;<br>  return function() {<br>   return count += 1;<br>  };<br> };</pre><pre>var nextCount = counter();<br>nextCount(); // returns 1<br>nextCount(); // returns 2</pre><h3>Lazy Function Definitions ( Self-Defining Functions )</h3><p>So, we know that functions can be assigned to a variable, but what if we can assign a function to a variable that already holds another function? In this case, we would be overwriting the old function with the new one. Let’s clarify this concept with an example:</p><pre>var work = function() {<br>  console.log(&quot;do some initial work here&quot;);<br>  work = function () {<br>   console.log(&quot;now let&#39;s do the rest of the work&quot;);<br>  }<br> }</pre><pre>work(); // do some initial work<br>work(); // now let&#39;s do the rest of the work <br>work(); // now let&#39;s do the rest of the work</pre><p>This pattern is very useful when we want to perform some initial work in our function, and we want that code to only run once.</p><p>A downside though of this pattern is that the properties added to the original function will be lost when we redefined it.</p><h3>Immediate Functions</h3><p>The immediate functions, better known as Immediately-Invoked Functions (IIFEs) is a syntax that makes possible for the execution of a function as soon as it is defined.</p><p>Let’s look at an example:</p><pre>(function(){<br> alert(&quot;Hello I&#39;m a IIFE&quot;);<br>}());</pre><p>The immediate function syntax consist of the following:</p><p>1. We define a function using a function expression.<br>2. We add parentheses at the end, which makes the function to be invoked immediately.<br>3. We wrap the whole function in parentheses.</p><p>There is an alternative syntax to the one presented in the previous example that behaves exactly the same:</p><pre>(function(){<br> alert(&quot;Hello I&#39;m also a IIFE&quot;);<br>})();</pre><p>The main advantage of implementing this pattern is that IIFE’s provide a “safe” environment (scope) for us to declare variables. By safe I mean that no matter what variables we declare inside the IIFE, we know for sure that it won’t collide with another variable declared in any part of our code.</p><p>If there is one thing you should learn about IIFE’s is this:</p><blockquote>The code wrapped in an IIFE doesn’t interfere or crash into any other code that might be included in your application.</blockquote><h3>Parameters of an Immediate Function</h3><p>We can also pass parameters to immediate functions.</p><pre>(function(car, brand) {<br> console.log(&quot;I just bought a &quot; + car + &quot; &quot; + brand);<br>})(&#39;Honda&#39;, &#39;Civic&#39;);</pre><pre>// prints: <br>// I just bought a Honda Civic</pre><p>I quick note: <strong><em>this</em></strong> inside of an IIFE always points to the global object, which in the case of the browser is the window object.</p><h3>Returned Values From Immediate Functions</h3><p>We can also return values from an IIFE. There are three different syntaxes we can follow that gets us the same result.</p><pre>var result = (function() {<br>  return 2 + 2;<br>}());</pre><pre>var result = function() {<br>  return 2 + 2;<br>}();</pre><pre>var result = (function() {<br>  return 2 + 2;<br>})();</pre><p>Although we are only returning a primate value (number) from this IIFEs, bear in mind that we can return any type of value, including another function.</p><p>Another interesting use of IIFEs is to use its scope to privately store some data.</p><p>Let’s take a look at this example:</p><pre>var mySuperCar = (function(){<br> var brand = &#39;Ferrari&#39;;<br> var model = &#39;Italia&#39;;<br> <br> return function() {<br>  return brand + &quot; &quot; + model;<br> }</pre><pre> return getCar;<br>})();</pre><pre>mySuperCar(); // prints Ferrari Italia</pre><h3>Main Benefits and Usage of IIFE</h3><ol><li>It provides a safe environment (scope) for us to define variables without the possibility of collision with other variables included in your application.</li><li>It enables us to wrap individual features into self-contained modules. For example, if we need to add a new feature to our application, IIFE’s gives us a safe way to wrap that code and we can make sure the page works fine with or without it.</li><li>It provides a scope in which we can privately store some data.</li></ol><h3>Immediate Object Initialization</h3><p>Similar to the immediate functions, there is a pattern called <strong><em>immediate object initialization</em></strong>, which consists of building an object literal and initializing it with an <strong>init()</strong> method.</p><pre>({<br> brand: &#39;honda&#39;,<br> model: &#39;civic&#39;,<br> getFullCar: function() {<br>  return this.brand + &quot; &quot; + this.model;<br>    },<br> init: function() {<br>  console.log(this.getFullCar(), &quot;bruuum bruuum&quot;);<br> }<br>}).init();</pre><p>So, we are basically creating a new object and wrapping it around parentheses, this tells javascript engine to treat the curly braces as an object literal instead of a code block. After closing the parentheses, we invoke the init function.</p><h3>Function Properties — Memoization</h3><p>For those who are not familiar with the term Memoization, it is basically a technique that is usually used to speed up algorithms. It achieves this optimization by storing the results of expensive function calls and returning the cached result when the same inputs occur again.</p><p>So, we know that functions are objects, and objects can store properties at any time, hence, functions can store properties at any time. One common case for custom properties in a function is to cache the results (the return value) of a function. This will help us the next time the function is called, it doesn’t have to perform the expensive operations all over again but it just needs to return the cache value, if it exists.</p><p>Let’s look at an example:</p><pre>var myExpensiveFunction = function(param) {<br>  if (!myExpensiveFunction[param]){<br>   var result = {};<br>   // some expensive operations here<br>   myExpensiveFunction.cache[param] = result;<br>  }<br>  return myExpensiveFunction.cache[param];<br> }</pre><pre> // cache storage<br> myFunc.cache = {};</pre><p>We basically add a custom property to our function called <em>cache</em>. Then every time the function runs, we ask if for the param being passed as an argument; have we already perform some heavy operations?. If so, return the result value previously stored in our cache obj (myFunc.cache[param]). If not we perform some heavy operations and then store the result in our custom property <em>cache</em>.</p><h3>Configuration Objects Pattern</h3><p>It’s known that requirements change as we develop software. Let’s suppose we are writing a function called addPerson(), which accepts a first and a last name, and adds that person to a list. Something like this:</p><pre>function addPerson(first, last) {...}</pre><p>In later stages, the client says that he also needs to store the birthday and gender of a person. So we refactor our code to reflect what the clients want. Something along these lines:</p><pre>function addPerson(first, last, gender, birthday) {...}</pre><p>At this point, the signature of the function is getting a little longer. What if the client needs to add more information in the near future? Keep adding parameter is not convenient, because we would have to be very careful not to mix the order when calling addPerson.</p><p>A better approach is to substitute all the parameters with only one object, called config, that holds all the properties of the entity person in our case. And then pass this object to our function.</p><pre>var conf = {<br>  first: &#39;George&#39;,<br>  last: &#39;Moller&#39;,<br>  birthday: new Date(&#39;December 17, 1995 03:24:00&#39;),<br>  gender: &#39;Male&#39;<br>}</pre><pre>addPerson(conf);</pre><p>Some of the advantages are:<br>1. There is no need to remember the parameters and their order<br>2. We can safely skip optional parameters<br>3. Better readability<br>4. Easier to add or remove parameters</p><h3>Conclusion</h3><p>In this post, we dived into the basics concepts of functions and we also went through some of the patterns we can use to harness their power. I really hope you have found this useful and got a chance to learn something new. Feel free to leave suggestions or questions in the comment section!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=794c46e4139c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Javascript Conventions and Best Practices]]></title>
            <link>https://medium.com/@_jmoller/javascript-conventions-and-best-practices-9e980751c70f?source=rss-329d486a68ca------2</link>
            <guid isPermaLink="false">https://medium.com/p/9e980751c70f</guid>
            <category><![CDATA[best-practices]]></category>
            <category><![CDATA[convention]]></category>
            <category><![CDATA[antipattern]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[guides-and-tutorials]]></category>
            <dc:creator><![CDATA[Jorge Moller]]></dc:creator>
            <pubDate>Sun, 24 Feb 2019 16:01:04 GMT</pubDate>
            <atom:updated>2019-02-24T16:01:04.284Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2xwHezT1n5-q-S6IEmKILA.png" /></figure><h3>Antipatterns</h3><h4>Globals</h4><p>If you are reading this you probably know how javascript manages the scope, but let’s refresh our memory. Javascript manages scope through its functions, meaning that any variable declared inside of a function is scoped to that particular function, and cannot be accessed from outside of that function. Now globals, are variables that are declared outside of any function, or variables that are used without being declared.</p><p>The problem with globals is basically <em>naming collision</em>. This happens when two separate parts of an application define global variables with the same name but with different purposes. Imagine we are using a third party library that uses a global namespace called <em>result</em>, if we were to write a global variable with the same name, we would override the result variable, hence breaking up the third party library.</p><p>A good practice to follow is to at least declare all your variables at the top of your functions. Here are some benefits :<br>1. It provides a single place for a developer to look up for variables.<br>2. Prevents logical errors when trying to use a variable before it’s being declared.</p><pre>mySum = 1; // declaring a global variable (antipattern)<br>function fn() {<br> mySum += 3;<br> var mySum = 2;<br> return mySum;<br>}</pre><p>Javascript has two phases so to speak, Creation Phase and Execution Phase. The above code would look like this in the Creation Phase:</p><pre> mySum = 1;<br> function fn() {<br>  mySum = undefined;<br>  mySum += 3; // output NaN<br>  mySum = 2;<br>  return mySum;<br>}</pre><h4>For loops</h4><p>Let&#39;s take a look at the usual <em>for loop</em> pattern like the following:</p><pre> // sub optimal loop<br> for (var i = 0; i &lt; myArray.length; i ++ ) {<br>   // do something<br> }</pre><p>A problem with this for loop is that the length of the array is accessed on every loop iteration. This can slow down your code, especially when myArray is not an array but an HTMLCollection object such as:</p><ul><li>document.getElementsByName()</li><li>document.getElementsByClassName()</li><li>document.getElementsByTagName()</li><li>…</li></ul><p>The problem with HTMLCollections is that they are live queries against the underlying document (HTML page), so every time we are trying to access the length of the collection we are querying the live DOM, and DOM operations are often expensive.</p><p>A better pattern for writing the for loop would be to cache the length of the collection before the iteration begins.</p><pre>for ( var i = 0, length = myArray.length; i &lt; length; i ++ ) {<br> // do something<br>}</pre><p>There is some even more tweaking we can do to the for loop such us writing i= i+ 1 instead of i++ to avoid ‘excessive trickiness’ or even to write the for loop in a decremental fashion because it is usually faster to compare to 0 than to the length of an array.</p><p>I personally don’t like to use these two micro-optimizations because it hurts readability and they can only be noticed in performance-critical operations.</p><h4>For-in loops</h4><p>For-in loops are used to iterate over non-array objects. One important thing to use when iterating over object properties is the hasOwnProperty() method. This will filter out properties that come down the prototype chain.<br>For example:</p><pre>var car = {<br> wheels: 4,<br> hasAirbag: true,<br> doors: 3,<br>}</pre><pre>// somewhere else in the code a method is added to all car  objects</pre><pre>if (typeof Object.prototype.startEngine === &#39;undefined&#39;) {<br>  <strong>Object.prototype.startEngine</strong> = function() {<br>   // starts the car engine<br>  }<br>}</pre><p>In this example, we have a car object that has been augmented by adding a function to its prototype object called startEngine.</p><p>If we were to iterate over the properties of this object without filtering down the properties with the hasOwnProperty method it would go through startEngine property.</p><pre>for (var c in car) {<br> console.log(c, &quot;:&quot; ,car[c]);<br>}<br>/*<br> results<br> wheels: 4<br> hasAirbag: true<br> doors: 4<br> <strong>startEngine: function() </strong><br>*/</pre><pre>for (var c in car) {<br> if (car.hasOwnProperty(c)) {<br>  console.log(c, &quot;:&quot; ,car[c]);<br> }<br>}<br>/*<br> results<br> wheels: 4<br> hasAirbag: true<br> doors: 4<br>*/</pre><h4>Avoid Implied Typecasting</h4><p>Javascript implicitly typecasts variables when we use the loose equality operator. That’s why comparisons such as false == 0 or “” == 0 return true.</p><p>As a good rule of thumb I always use strict equality operator === and !== to make sure I’m checking for both values and types of the expressions to compare.</p><h3>Coding Conventions</h3><p>A good definition for coding conventions would be; a set of guidelines and rules to follow when writing code, period. Now, why should we even care about this? Well, if you have been programming for a while now, chances are that you find yourself working with a team of developers. Imagine each and every developer follows his or her own set of rules to write code. How do you think that code would look like in a month, a year from now?.</p><p>What coding conventions try to solve is code that looks like it was written by different developers. Helps us write more maintainable and readable programs.</p><p>There are some useful and popular guidelines out there such as the one written by Airbnb for example that applies not only to javascript but to react projects as well.</p><p>I don’t think there is right and wrong here as long as you are following some kind of convention, to keep your code consistent.</p><p>Let’s go through some of them, shall we?</p><h4>Indentation</h4><p>Code without indentation is impossible to read, as simple as that. Some prefer indentation with tabs, others prefer spaces. If you ask me I like to follow a two space indentation, is the one I have found to be the most enjoyable to work with.</p><p>What should you indent? Well, everything within curly braces.</p><h4>Curly Braces</h4><p>Oh, this is a good one. Should you always use curly braces? Even when you have one-line if or for loops? Or, is it ok to treat them as optional on those occasions?</p><p>Most books will tell you to always write curly braces because it makes the code more consistent and easier to update. While this can be true to a certain extent, I think it depends on the statement you are writing. For an experienced programmer at least, (and I might be wrong here assuming every person in the team is an experienced programmer) I found the two following blocks of code to have the same readability.</p><pre>if (msg !== &#39;&#39;)  alert(msg)<br>else  alert(&#39;There is no message to show&#39;);</pre><pre>if (msg !== &#39;&#39;) {<br>  alert(msg);<br> } else {<br>  alert(&#39;There is no message to show&#39;);<br>}</pre><p>Not only that but the first approach only takes two lines of code, against the five lines of code of the second statement.</p><p>Although I’m all in for coding conventions, I don’t like to marry to the ‘curly braces are always required’ statement. I think it doesn’t hurt to have some flexibility in this case.</p><p>I always use curly braces in for loops though, the only time where I like to not use curly braces is for very simple if statements similar to the example shown above.</p><h4>White Spaces</h4><p>White spaces can also contribute to improved readability and consistency. Let’s look at some good places to use them:</p><ol><li>After the semicolons that separate the parts of a <strong>for</strong>.</li><li>After commas that delimit array items: <em>var a = [1, 2, 3]</em></li><li>After commas in object properties and after colons that divide property names and their values: <em>var o = {a: 1, b: 2}</em></li><li>Delimiting <strong>function</strong> arguments: <em>fn(a, b, c)</em></li><li>Before the curly braces in function declarations:<em> function fn() {};</em></li><li>After <strong>function</strong> in anonymous function expressions: <em>var fn = function () {};</em></li><li>Before opening curly braces <em>{</em> in functions, if-else cases, loops and object literals.</li><li>Between the closing curly brace, <em>}</em> and <strong>else</strong> or <strong>while</strong></li></ol><p>Another overlooked example is the use of vertical white space. I like to use blank lines to separate units of code and ideas.</p><h4>Naming Conventions</h4><p>here is a common saying among programmers that goes:</p><blockquote>There are two hard things in computer science: cache invalidation and naming things.</blockquote><p>Basically, the goal here is to choose names for variables and function in a consistent manner.</p><h4>Capitalizing Constructors</h4><pre>var car = new Car();</pre><p>Because constructors are just functions, it helps if you can tell just by looking at the function name whether it was supposed to behave as a constructor or as a normal function. Naming constructors with a capital first letter help to achieve this.</p><h4>Separating Words</h4><p>Which naming convention should we use when we have multiple words in a variable or a function? Should we go with camelCase, PascalCase, snake_case??</p><p>A common convention here and the one I personally use is camelCase. By following this convention you type the words in lower case only capitalizing the first letter in each word (except for the first word).</p><pre> // camel case exmaple<br> var myAwesomeFunction = function () { <br>  // do something awesome!<br> }</pre><p>I only use<em> upper camel case</em> or Pascal case for constructors.</p><pre>MyConstructor() { ... }</pre><p>For constants when there was no way to define them in javascript, I often followed the all caps convention, where the name of the variable was written in all caps. But now that we have a way, I don’t use that convention anymore, I just don’t see the point of doing that.</p><p>A convention I personally like to follow is the /private members convention/. It basically states that you should name private members with an underscore prefix, for example:</p><pre>var car = {<br>  getBrand: function() {<br>   return this._getModel() + &#39;&#39; + this._getYear();<br>  },<br>  _getModel: function() { //... },<br>  _getYear: function() { //... }<br> }</pre><p>Although _getModel and _getYear still work as public methods, I think its good approach that lets the user of the car object know that those are not meant to be used as public methods.</p><h4>Writing Comments</h4><p>When I find myself writing a new feature of fixing a particular bug, It seems obvious to me what my code is intended to solve, but of course, that is a biased opinion, chances are that other developers out there would struggle just a little bit to understand what I am trying to achieve.</p><p>Writing comments is a good way to add some extra information that will help you and others in the future to understand quickly what a particular part of your code does.</p><p>Now, you shouldn’t go overboard with comments. There is no need for commenting every function or every line of code. I usually like to comment intermediate to complex functions, unusual algorithms or some specific technique I used to solve a particular problem.</p><p>I think it’s important to find a balance when writing comments because remember that they need to be maintained in the future. If a part of your application changes, your comments regarding that specific part should change also, and that adds some extra work over time.</p><p>Comments are also a good way to auto-generate documentation (if you are into that). For example, YUIDoc is a tool that lets you auto-generate documentation by following some conventions when commenting code.</p><pre>/**<br>* My method description.  Like other pieces of your comment blocks, <br>* this can span multiple lines.<br>*<br>* <a href="http://twitter.com/method">@method</a> methodName<br>* <a href="http://twitter.com/param">@param</a> {String} foo Argument 1<br>* <a href="http://twitter.com/param">@param</a> {Object} config A config object<br>* <a href="http://twitter.com/param">@param</a> {String} config.name The name on the config object<br>* <a href="http://twitter.com/param">@param</a> {Function} config.callback A callback function on the config object<br>* <a href="http://twitter.com/param">@param</a> {Boolean} [extra=false] Do extra, optional work<br>* <a href="http://twitter.com/return">@return</a> {Boolean} Returns true on success<br>*/</pre><p>The decorators are going to be picked up later by YUIDoc to autogenerate documentation. Explaining how to use YUIDoc it’s outside of the scope of this post, so if you want to learn more about it, feel free to dive into the official docs at <a href="https://yui.github.io/yuidoc/">https://yui.github.io/yuidoc/</a>.</p><h3>Conclusion</h3><p>In this post, we looked at different conventions and patterns to both follow and avoid. Bear in mind that these are just a very few guidelines, and there are plenty more.</p><p>Hope you have learned something new from this post, feel free to share your thoughts and suggestions!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9e980751c70f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Javascript data structures: Trees]]></title>
            <link>https://medium.com/@_jmoller/javascript-data-structures-trees-c961297e6482?source=rss-329d486a68ca------2</link>
            <guid isPermaLink="false">https://medium.com/p/c961297e6482</guid>
            <category><![CDATA[category]]></category>
            <category><![CDATA[subcategories]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[data-structures]]></category>
            <category><![CDATA[trees]]></category>
            <dc:creator><![CDATA[Jorge Moller]]></dc:creator>
            <pubDate>Sun, 17 Feb 2019 21:00:11 GMT</pubDate>
            <atom:updated>2019-02-20T14:05:11.125Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*DdUzdaJOqIQbB4bBrD-W0A.jpeg" /></figure><p>The main goal of this post is to explain how to create, traverse and search Trees in javascript, using a real world example.</p><p>Let’s say we are working for a client that needs to have an e-commerce store for their business. In one of the meetings, he states the following requirements:</p><p>1. The store administrator must be able to add, remove and edit categories.<br>2. A category can have one or n subcategories.<br>3. A product should have a name, price and the category he belongs to. (Category is a mandatory field here, there is no point to have a product with no category)</p><p>From this requirements list one can think of making a class diagram like the following:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gFYulrDJJslRSz9Gorc1sg.png" /></figure><p>There is nothing wrong with this approach, but what would happened if we want to remove a product?. We have to first search for the category he belongs to and remove it from the products array of that particular category. That seems some extra work that I don’t want to do.</p><p>Another approach would be that categories know nothing about the products they hold, instead, the products are the only schema that holds a relationship to the category they belong to.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*h_VR4_U6hEZdqPIvAnsD3w.png" /></figure><p>You might be asking yourself, “Where do trees take place in all this nonsense?”. Well, we need to think of a way to structure our categories and subcategories, and for that, we are going to use trees. Look at the following example:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5gnPJ1nfkhJl4dn-4Gbpjw.png" /></figure><p>That looks like a tree to me. Let’s go through the logic of building the tree structure in javascript, but first let&#39;s think of the operations we need to perform over it.</p><ol><li>Add a category (node) to the tree. For this operation, we would take the parent node to which we want to add a category, as a parameter. Something like this: /_addNode(parentNode) {…}/</li><li>Remove a category (node) from the tree. For this, we would only need the node to remove as a parameter.</li><li>Search operation that takes a category as a parameter and returns the node.</li><li>I would also want to know the leafs of a particular node. This is going to come in handy when the user clicks on a category, we would search for the leafs and then iterate through the product list and see if any product has at least one of leafs (categories), in case it has, we should display it. For example the user clicks in the Notebooks category, the leafs of this node are: Asus, MacBook Air, and MacBook Pro. We iterate through the products list and only display those products that have one of this tree subcategories.</li></ol><p>Finally, let’s write some code to hold the structure of our tree.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/61dabe800684e725728c80c34136b3e3/href">https://medium.com/media/61dabe800684e725728c80c34136b3e3/href</a></iframe><h3>Traverse</h3><p>The traverse method takes a callback function as its parameter, this callback function will be called with a particular node throughout the iteration process.</p><p>It defines a goThrough function that takes a node, in our case the first time calling this function we are going to pass down the root node.</p><p>Inside the goThrough function, the first thing is to call the callback function with that particular node, then it iterates through every child of the node and performs a recursive call with each and every child. Just to shed some light on this code let’s see how we would make use of this function.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f323b98641666a477d3a14e0d844ecd6/href">https://medium.com/media/f323b98641666a477d3a14e0d844ecd6/href</a></iframe><h3>Add node</h3><p>The _addNode method takes a value and a parentValue to which we want to add the node.</p><p>We start by creating the structure of the new node with its value set to the one passed by parameter and with an array of empty children.</p><p>We check if our root node is null, if it is, we just set our root node to point to our newly created node.</p><p>If our root node is not null, we traverse the tree to find the parentValue, and once we find it we push our newly created node to our parentNode children.</p><h3>Remove node</h3><p>This method is pretty much self-explanatory. We iterate through the tree with the traverse operation and when we find the parent node of the node we want to remove, we just remove it from the parent’s node children array.</p><h3>Search node</h3><p>The search operation traverses the tree and when we find that the value of the node matches the one being search, we return the entire node.</p><h3>Display leafs</h3><p>The display leafs method takes a parentValue such as “Notebooks” and aims to display all the leaf categories of this node, in our example would be “Asus” “MacBook Pro” and “MacBook Air”.</p><p>The first line checks whether the parameter being passed to the function is a string or a node. If it’s a string we perform a search operation to retrieve the actual node.</p><p>Then it checks the condition for a node to be a leaf, which is to have no children. If this is the case then we know for sure we have a leaf of our parent node so we return its value.</p><p>We store each leaf in an array, and we finally flatten that array just before returning. So the result of this would be something like [“Asus”, Macbook Pro”, “MacBook Air”].</p><p>Now we have all the operations we need to perform some tests.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0359aceb6436d87a7389abf5e4b29e1e/href">https://medium.com/media/0359aceb6436d87a7389abf5e4b29e1e/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/794/1*CO_FoGd1DQjZ_YoY7IG_sQ.png" /><figcaption>chrome console output</figcaption></figure><p>Hope you have found this post helpful! If you have any questions or suggestions don’t hesitate to post them!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c961297e6482" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How does styled-components work under the hood? ]]></title>
            <link>https://medium.com/@_jmoller/how-does-styled-components-work-under-the-hood-28cb035d48c6?source=rss-329d486a68ca------2</link>
            <guid isPermaLink="false">https://medium.com/p/28cb035d48c6</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[how-to]]></category>
            <category><![CDATA[styled-components]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[componentes]]></category>
            <dc:creator><![CDATA[Jorge Moller]]></dc:creator>
            <pubDate>Tue, 12 Feb 2019 00:26:25 GMT</pubDate>
            <atom:updated>2019-02-20T14:07:59.730Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GjUyGAWu2_F3Bja5-FusLw.png" /></figure><p>To really understand how styled-components work we need to go over a javascript feature called template literals, which is what powers styled-components. If you are already familiar with template literals feel free to skip over this section, if not stay around and I will explain to you what is it.</p><p>Template literals are string literals that allow you to embed expressions. They are enclosed by the back-tick character instead of single quotes, and can contain placeholders, these placeholders are indicated by the dollar sign and curly braces. The expression in the placeholders and the text between them get passed to a function, that function concatenates the parts into a single string. Let’s look at an example.</p><p><strong>Expression interpolation:</strong></p><p>In order to embed expressions with normal string, you would use the following syntax.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b68f88594c772e298b3b2ca7433dc3c9/href">https://medium.com/media/b68f88594c772e298b3b2ca7433dc3c9/href</a></iframe><p>Now with template literals, you are able to make use of syntactic sugar making the code more readable.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8c91f485067834f4023550cd410878cd/href">https://medium.com/media/8c91f485067834f4023550cd410878cd/href</a></iframe><p><strong>Tagged Templates:</strong></p><p>A more advanced form of template literals are<em> tagged templates</em>, tags allow you to parse template literals with a function. The first argument of a tag function contains an array of string values and the remaining arguments are related to the expressions. Let&#39;s look at yet another example:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/900bcb81a26ed99481721bcf89dc21fe/href">https://medium.com/media/900bcb81a26ed99481721bcf89dc21fe/href</a></iframe><p>Ok, so what is happening here, the first thing you might notice is that we are calling myTag function with back-tick instead of the usual parenthesis. As I said before, the first argument of a tag function is an array of strings values that are contained within the back-ticks, in our case the array contains the word That in the first position and the sentence `is a `in the second position. The remaining arguments are related to the expressions we passed to the tag function, in our case, the first expression is ${person} and the second one is ${age}.</p><p>To make things a little bit more clear, that tag function is equivalent to this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e3fe26627a51738f01a88f8f0e444351/href">https://medium.com/media/e3fe26627a51738f01a88f8f0e444351/href</a></iframe><p>Now that you we know how tagged templates work let’s see how styled-components make use of them.</p><p>Let’s create a simple button with some static styles using styled components. First, we need to import the styled object from styled-components. The styled object gives us access to a ton of utility functions to create different html elements. We can think of the styled object as a component factory for html elements.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8d9eafe197aa6bce6b766c2016807ec9/href">https://medium.com/media/8d9eafe197aa6bce6b766c2016807ec9/href</a></iframe><p>For a complete list of supported elements, you can check out the official GitHub of styled components: <a href="https://github.com/styled-components/styled-components/blob/master/packages/styled-components/src/utils/domElements.js">official documentation</a></p><p>To better understand what’s happening here we need to first know what is styled.h1 doing under the hood. If dive deep into the styled-components files you will see this file.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e5427fa37efa08a1800fd0713c58b01a/href">https://medium.com/media/e5427fa37efa08a1800fd0713c58b01a/href</a></iframe><p>By looking at this piece of code we now know two things:</p><ol><li>The styled object holds a key for each dom element and its value is a function! 🤯</li><li>This function takes the tag (in our case the h1 tag) and returns yet another function with the StyledComponent function and tag as it’s parameters!🤯🤯</li></ol><p>Simplifying, whenever we call styled.h1, we are really calling a function that returns another function. This last function is…..a <strong>template function!. </strong>How do I know this… well take a look at the following piece of code from styled-components files:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3409cf95a6ccdb37077b1f853ef6b247/href">https://medium.com/media/3409cf95a6ccdb37077b1f853ef6b247/href</a></iframe><p>There is no need to understand everything that’s happening here. The key point is to understand that the constructWithOptions function is returning a template function as it clearly states in line 20 of the constructWithOptions.js file.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3ad42cb7737569faf2cdaf9c7fb27984/href">https://medium.com/media/3ad42cb7737569faf2cdaf9c7fb27984/href</a></iframe><p>This is the function we have access when calling styled.h1``, we might not know exactly what this function does, but we know we can pass as many arguments as we want and the componentConstructor function (which is the StyledComponent function passed in earlier as a parameter) will take care of it.</p><p>Some key aspects of what styled components do when calling the template function styled.h1`…`:</p><ol><li><strong>It generates CSS class name: </strong>Each component instance with unique props has it’s own CSS class name. This class name is a hash, something like this: <em>sc-bwzfXH.</em></li><li><strong>CSS Preprocessing: </strong>it adds the hash of the class generated to the styles being passed to our component, in our case the title tag.</li><li><strong>It injects CSS string into the page: </strong>Now the CSS should be injected into the &lt;style&gt; element in the head.</li><li><strong>render():</strong> Creates an element with the corresponding className</li></ol><h3>Conclusion</h3><p>To sum up what styled-components does under the hood, it creates CSS on the flight by creating hashes for the classes of the component being styled, secondly it puts together these classes with the styles defined by the user, then injects those to a style tag in the head of our HTML document and finally add the class to our HTML tag.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=28cb035d48c6" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>