<?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 Ricardo Luz on Medium]]></title>
        <description><![CDATA[Stories by Ricardo Luz on Medium]]></description>
        <link>https://medium.com/@_rxluz?source=rss-892e3096e4fa------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*z_wVuVsn2cOft-Q4GcSsjQ.jpeg</url>
            <title>Stories by Ricardo Luz on Medium</title>
            <link>https://medium.com/@_rxluz?source=rss-892e3096e4fa------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 18 Nov 2026 04:07:44 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@_rxluz/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[An AI Therapy Guide to its Benefits and Potential]]></title>
            <link>https://ai-therapy-insights.mind-r.ai/an-ai-therapy-guide-to-its-benefits-and-potential-b7eff58f54cd?source=rss-892e3096e4fa------2</link>
            <guid isPermaLink="false">https://medium.com/p/b7eff58f54cd</guid>
            <dc:creator><![CDATA[Ricardo Luz]]></dc:creator>
            <pubDate>Mon, 22 May 2023 13:13:09 GMT</pubDate>
            <atom:updated>2023-05-22T13:56:00.743Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*o9h4cpQqnOz1MEU3.png" /></figure><p>Embark on a memorable journey into the world of AI therapy! AI, short for artificial intelligence, has emerged as an effective tool in promoting mental and physical health.</p><p>This guide seeks to provide an in-depth understanding of AI therapy, its functioning, and its potential impact on your life, inspired by breakthroughs highlighted in articles like the one from the <a href="https://www.weforum.org/agenda/2021/12/ai-mental-health-cbt-therapy/">World Economic Forum</a>.</p><p>AI therapy uses special computer programs and apps to provide treatment and support. One example is <a href="https://www.mind-r.ai/en-US">Solace</a>, an AI Therapist created by <a href="https://www.mind-r.ai/en-US">Mind-R.AI.</a> Solace uses AI to give personalized therapy help to individuals who may not have entry to classic therapy resources, similar to the work done by AI in a mental health clinic called <a href="https://www.technologyreview.com/2021/12/13/1043886/ai-mental-health-therapy/">Ieso</a>.</p><p>Let us delve more in-depth into AI therapy and discover its potential to assist you in various ways.</p><h3>The History of AI Therapy</h3><p>AI therapy has a rich history, spanning many years, and has undergone significant evolution over time. Its roots can be outlined back to the design of ELIZA, a basic chatbot designed to simulate a computerized therapist. However, thanks to remarkable technological advancements, AI therapy has significantly improved since then, with AI tools now able to help refine diagnosis and assign the right therapist, as outlined in a <a href="https://www.weforum.org/agenda/2021/12/ai-mental-health-cbt-therapy/">World Economic Forum article</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/751/0*bzFWeXAxRmaoLRNn.png" /></figure><h3>Types of AI Therapy</h3><p>There are different types of AI therapy. One type is AI therapy apps that you can install on your phone or tablet. These apps use AI to analyze what you say or type and provide personalized advice and support, a use-case explored in the <a href="https://www.technologyreview.com/2021/12/13/1043886/ai-mental-health-therapy/">MIT Technology Review</a>.</p><p>Notable examples of AI therapy apps encompass Solace, Woebot, and Wysa, among others. These applications utilize AI technology to analyze your verbal or written input, offering tailored guidance and support.</p><p>Another type is AI physical therapy, which helps people with their physical health. For example, AI can analyze how you move and create personalized treatment plans. It can also help therapists monitor your progress and ensure you get the best care, similar to how AI is helping with the quality control of treatment and the training of therapists, as discussed in the <a href="https://www.weforum.org/agenda/2021/12/ai-mental-health-cbt-therapy/">World Economic Forum article</a>.</p><h3>How AI Therapy Apps Help</h3><p>AI therapy apps are like having a therapist on your phone. They listen to you and give you advice to help you feel better. Let’s look at some popular AI therapy apps and what they offer:</p><p><strong>Solace</strong>: <a href="https://www.mind-r.ai/en-US">Solace</a> is an AI Therapist that can talk to you in different languages. It provides therapy naturally and engagingly, similar to how the AI at Ieso operates.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*FeoKwO-uCQlkBQmt.jpg" /></figure><p><strong>Woebot</strong>: Woebot uses cognitive-behavioural therapy techniques to help you manage your emotions and thoughts. It provides exercises and checks in with you every day, akin to the AI developed by Ieso, as outlined in the <a href="https://www.technologyreview.com/2021/12/13/1043886/ai-mental-health-therapy/">MIT Technology Review article</a>.</p><p><strong>Wysa</strong>: Wysa offers personalized support through different therapy techniques. You can have text conversations with the AI and get guidance and exercises, much like the AI therapy services discussed in the <a href="https://www.weforum.org/agenda/2021/12/ai-mental-health-cbt-therapy/">World Economic Forum article</a>.</p><h3>AI in Physical Therapy</h3><p>AI is not only for mental health but also for physical therapy. It helps therapists create personalized treatment plans and monitor your progress. Here are some instances of how AI is used in physical therapy:</p><p><strong>Gait Analysis</strong>: AI can analyze how you walk and help therapists understand movement problems. This leads to better treatments and improved mobility, a point underscored by how AI improves diagnostics and treatment plans in the <a href="https://www.weforum.org/agenda/2021/12/ai-mental-health-cbt-therapy/">World Economic Forum article</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*XNz5j6t71gH_8TXz.png" /></figure><p><strong>AI-Powered Walking Helpers</strong>: These wearable devices assist people with trouble walking. AI algorithms analyze your movements and adjust the support to help you move better.</p><p><strong>AI-Assisted Rehabilitation Exercises</strong>: AI makes rehabilitation exercises more fun and interactive. It guides you through workouts and provides feedback to guarantee you gain the most from your therapy.</p><h3>The Role of Therapy AI in Mental Health</h3><p>AI also plays a crucial role in assisting therapists with mental health. It enhances the precision of diagnoses and treatments by utilizing advanced algorithms. These algorithms can recognize patterns in your thoughts and feelings, resulting in more effective therapy sessions, a crucial point made in the <a href="https://www.technologyreview.com/2021/12/13/1043886/ai-mental-health-therapy/">MIT Technology Review article</a>.</p><figure><a href="https://www.mind-r.ai/en-US"><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Z3Ts9u8QFvsPL4ZD.jpg" /></a></figure><h3>Benefits and Drawbacks of AI Therapy</h3><p>AI therapy apps have many benefits. They are accessible, personalized, and more affordable than traditional therapy. However, they may only be as effective for some, and privacy and ethical concerns must be addressed, as discussed in the <a href="https://www.weforum.org/agenda/2021/12/ai-mental-health-cbt-therapy/">World Economic Forum</a> and the <a href="https://www.technologyreview.com/2021/12/13/1043886/ai-mental-health-therapy/">MIT Technology Review article</a>.</p><p>—</p><h3>AI Companions in Therapy</h3><p>AI companions, like chatbots or virtual assistants, can be helpful in therapy. They provide emotional support and advice, and they are available anytime. AI companions also reduce the stigma associated with mental health issues, a point stressed in the <a href="https://www.weforum.org/agenda/2021/12/ai-mental-health-cbt-therapy/">World Economic Forum article</a>.</p><h3>The Future of AI in Therapy</h3><p>The future of AI therapy looks very promising. As technology advances, it will evolve even more personalized and effective. Here are some exciting advancements and trends to look out for:</p><ul><li><strong>Enhanced Personalization and Adaptation</strong>:</li></ul><p>AI therapy apps can customize and adjust their approach to meet your needs and preferences. They will analyze your experiences, emotions, and behaviours to provide advice and recommendations.</p><ul><li><strong>AI and Awesome Devices Join Forces:</strong></li></ul><p>When AI collaborates with incredible devices like smartwatches and fitness trackers, they gather essential information about your body and mind. With AI’s help, these gadgets can give you valuable tips and suggestions immediately to help you stay healthy and happy.</p><ul><li><strong>Improved AI-Based Diagnostics:</strong></li></ul><p>AI algorithms will become better at diagnosing mental health disorders. They will analyze your behaviour, speech, and other factors to identify patterns and provide earlier and more accurate diagnoses. This will lead to more effective treatment plans, a future vision articulated in the <a href="https://www.technologyreview.com/2021/12/13/1043886/ai-mental-health-therapy/">MIT Technology Review article</a>.</p><ul><li><strong>Virtual Reality (VR) and Augmented Reality (AR) in Therapy:</strong></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*A1AK1dLYTcUpO6hd.png" /></figure><p>AI-guided VR and AR experiences will be used to treat mental health disorders like anxiety disorders and phobias. These technologies will provide engaging and effective therapy sessions by immersing you in therapeutic environments.</p><ul><li><strong>Ethical Guidelines and Regulations:</strong></li></ul><p>As AI therapy becomes more widespread, it’s essential to develop guidelines and regulations to ensure the ethical use of the technology. This will protect patient privacy and maintain trust in AI-based therapy services, a crucial point raised in the <a href="https://www.technologyreview.com/2021/12/13/1043886/ai-mental-health-therapy/">MIT Technology Review article</a>.</p><p>In conclusion, AI therapy can transform how we approach mental and physical health treatment. It offers personalized, accessible, and practical solutions for those in need.</p><p>AI therapy will become even more critical as technology improves in helping us lead healthier and happier lives, an optimistic future presented in both the <a href="https://www.technologyreview.com/2021/12/13/1043886/ai-mental-health-therapy/">MIT Technology Review</a> and the <a href="https://www.weforum.org/agenda/2021/12/ai-mental-health-cbt-therapy/">World Economic Forum</a> articles.</p><p>—</p><h3>Embracing the Potential of AI in Therapy</h3><p>This article has provided a more reasonable sense of AI therapy and how it can help you. AI therapy apps, AI physical therapy, therapy AI, and AI companions are all valuable tools for improving our mental and physical well-being.</p><p>If you ever need therapy or support, consider exploring the benefits of AI therapy. It can provide accessible, personalized, and practical solutions that positively impact your life. Moreover, by embracing the potential of AI in treatment, you are taking a step towards a brighter and healthier future, a sentiment echoed in the <a href="https://www.technologyreview.com/2021/12/13/1043886/ai-mental-health-therapy/">MIT Technology Review article</a>.</p><p>Remember, therapy is essential to treating your mental and physical health. Whether through AI or traditional therapy, seeking help when needed is a brave and critical choice. You deserve support and direction to assist you in guiding life’s challenges.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b7eff58f54cd" width="1" height="1" alt=""><hr><p><a href="https://ai-therapy-insights.mind-r.ai/an-ai-therapy-guide-to-its-benefits-and-potential-b7eff58f54cd">An AI Therapy Guide to its Benefits and Potential</a> was originally published in <a href="https://ai-therapy-insights.mind-r.ai/">AI Therapy Insights</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[S.O.L.I.D Principles with JS examples]]></title>
            <link>https://medium.com/front-end-weekly/s-o-l-i-d-principles-with-js-examples-db95b44e82e?source=rss-892e3096e4fa------2</link>
            <guid isPermaLink="false">https://medium.com/p/db95b44e82e</guid>
            <category><![CDATA[solid-principles]]></category>
            <category><![CDATA[design-patterns]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[nodejs]]></category>
            <dc:creator><![CDATA[Ricardo Luz]]></dc:creator>
            <pubDate>Tue, 28 Jun 2022 20:24:43 GMT</pubDate>
            <atom:updated>2022-07-29T11:18:28.767Z</atom:updated>
            <content:encoded><![CDATA[<p>The <strong>SOLID Principles</strong> were presented initially by Uncle Bob in his book <strong>Agile Software Development: Principles, Patterns, and Practices</strong> and they intended to make software designs more understandable, flexible and maintainable.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*N6oicFABkJFlPrplPsbv9A.png" /></figure><p>According to Uncle Bob, they are:</p><blockquote>The SOLID principles are not rules. They are not laws. They are not perfect truths. The are statements on the order of <em>“An apple a day keeps the doctor away.”</em> This is a good principle, it is good advice, but it’s not a pure truth, nor is it a rule.</blockquote><blockquote>The principles are mental cubby-holes. They give a name to a concept so that you can talk and reason about that concept. They provide a place to hang the <em>feelings</em> we have about good and bad code. They attempt to categorize those feelings into concrete advice. In that sense, the principles are a kind of anodyne. Given some code or design that you <em>feel bad</em> about, you may be able to find a principle that explains that bad feeling and advises you about how to feel better.</blockquote><blockquote>These principles are heuristics. They are common-sense solutions to common problems. They are common-sense disciplines that can help you stay out of trouble. But like any heuristic, they are empirical in nature. They have been observed to work in many cases; but there is no proof that they always work, nor any proof that they should always be followed.</blockquote><blockquote><a href="https://sites.google.com/site/unclebobconsultingllc/getting-a-solid-start"><strong>Getting a SOLID start</strong></a><strong> by Uncle Bob</strong></blockquote><p>Let’s analyse them with practical examples in javascript</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fupscri.be%2Ff%2F788447%3Fas_embed%3Dtrue&amp;dntp=1&amp;display_name=Upscribe&amp;url=https%3A%2F%2Fupscri.be%2F788447%2F&amp;type=text%2Fhtml&amp;schema=upscri" width="800" height="400" frameborder="0" scrolling="no"><a href="https://medium.com/media/18214d8333adbb5668f31791a3202b60/href">https://medium.com/media/18214d8333adbb5668f31791a3202b60/href</a></iframe><h3><strong>Single Responsibility Principle (SRP)</strong></h3><blockquote><em>A class should have one, and only one, reason to change.</em></blockquote><p>The idea behind this principle is we need to split different responsibilities into different classes, we have the following code below that illustrates the User class:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/904ba44e2d363049334dcc3dcb3c175b/href">https://medium.com/media/904ba44e2d363049334dcc3dcb3c175b/href</a></iframe><p>The problem with this example is the User class has to manage two different responsibilities:</p><ul><li>Edit user data</li><li>Logs the user data edition</li></ul><p>This generates problems in maintaining stability; once we have more than one reason to change this class, let’s suppose that we need to implement a better Log control with date and time; when we add this, we could break things that are not directly with Log like edit user name or age, also, this will become this class bigger than it needs to be.</p><p>We could recreate this code using the Proxy Pattern, and the result will be:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0c2c24bdd1d24a90f18722e572dc2b12/href">https://medium.com/media/0c2c24bdd1d24a90f18722e572dc2b12/href</a></iframe><p>Now we have two classes with different responsibilities:</p><ul><li><strong>User class: </strong>Manages only stuffs related directly to user data (edit name and age)</li><li><strong>UserLogProxy:</strong> Manage only the logs of user actions</li></ul><h3>Open/Closed Principle (OCP)</h3><blockquote><em>Objects or entities should be open for extension, but closed for modification.</em></blockquote><p>There is only one constant in code development which is <strong>C H A N G E S</strong>, everything that we code will change at some moment in future, so we need to create code that makes it easier.</p><p><strong>The way that we change our code will define the code quality</strong>, if we constantly change our current classes, this will generate bugs in our code, but if we extend our classes with new ones this will help us to avoid bugs in our code, that’s the main idea of <strong>OCP Principle</strong>.</p><p>Let’s analyse the code below:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/289022f6b991907599307895d89d5602/href">https://medium.com/media/289022f6b991907599307895d89d5602/href</a></iframe><p>If we want to add a new Sandwich size, giant, for example, we need to edit the Sandwich class, and potentially break something else, if we delegate this list to another class and load this class from the Sandwich class we make the future maintenance easier and safer:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b435e5225622f08d6191d2a11409e238/href">https://medium.com/media/b435e5225622f08d6191d2a11409e238/href</a></iframe><p>Now we have 2 different classes connected through the setSize method in the Sandwich class, it doesn’t matter how many sizes we’d like to add we don’t need to edit the Sandwich class anymore, that’s the OCP Principle essence.</p><h3>Liskov substitution principle</h3><blockquote><em>Let q(x) be a property provable about objects of x of type T. Then q(y) should be provable for objects y of type S where S is a subtype of T.</em></blockquote><p>This definition doesn’t help us to understand faster what’s this principle means, but the idea is very simple: <strong>a parent class could be replaced by a derived class without breaking its behaviour</strong>.</p><p>The code below is a classic example of a derived class breaking the behaviour of a parent class:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/af0f5a120455e91dd1ca72ea846128f1/href">https://medium.com/media/af0f5a120455e91dd1ca72ea846128f1/href</a></iframe><p>The problem in this example is the derived class Square changes how is calculated the area of his parent class Rectangle, <strong>this is a classic case where a Duck that needs batteries don’t replace a real Duck, </strong>in our example if Square can’t replace a Rectangle its means that Square shouldn’t inherit from Rectangle class.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/0*FdopVquiGKzUEIEX.jpg" /><figcaption>Found <a href="https://lostechies.com/derickbailey/2009/02/11/solid-development-principles-in-motivational-pictures/">here</a></figcaption></figure><p>To solve this, we could reimplement this algorithm using this approach:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/533b74291d90dcbba9db6a4b512d9a63/href">https://medium.com/media/533b74291d90dcbba9db6a4b512d9a63/href</a></iframe><p>Now the Rectangle class and Square class are independent classes, avoiding the Square class changes the Rectangle class&#39;s behaviour.</p><h3><strong>Interface Segregation Principle (ISP)</strong></h3><blockquote><em>Clients should not be forced to depend upon interfaces that they do not use.</em></blockquote><p>You could think “Ok there is no problem here once Javascript doesn’t provide Interfaces types”, but we could use this principle to avoid sending useless parameters like in the example below:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d9d1eaffce4b7d600a6ff854bf4f9d7d/href">https://medium.com/media/d9d1eaffce4b7d600a6ff854bf4f9d7d/href</a></iframe><p>In this example the method setName in the Product class always requires the user to send the onFinish function even when the user doesn’t need to call this function, this is better implemented in this way:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/52e6ea30c38ade11a90b6697d706f654/href">https://medium.com/media/52e6ea30c38ade11a90b6697d706f654/href</a></iframe><p>The change between the two codes is subtle but greatly improves the implementation of the code, instead of this:</p><pre>setName({ <em>name</em>, <strong><em>onFinish</em></strong> }) {<br>  <em>this</em>.name = name;<br>  onFinish(<em>this</em>);<br>}</pre><p>We put this:</p><pre>setName({ <em>name</em>, <strong><em>onFinish = () =&gt; {}</em></strong> }) {<br>  <em>this</em>.name = name;<br>  onFinish(<em>this</em>);<br>}</pre><p>We are using the <strong>Object Destructuring</strong> ES6 feature to create a clean code! If you want to know more about Destructuring, I wrote an article about this:</p><p><a href="https://medium.com/@_rxluz/8-functional-approach-destructuring-b39dcbb40683">#8 Functional Approach: Destructuring</a></p><h3>Dependency Inversion Principle (DIP)</h3><blockquote>1. High-level modules should not depend on low-level modules. Both should depend on abstractions.</blockquote><blockquote>2. Abstractions should not depend upon details. Details should depend upon abstractions.</blockquote><p>The idea here is to create a way to become our classes less dependent on other classes, making it easier to replace dependency on others.</p><p>To visualize this in a real situation let’s analyse the code below:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/aec2ac5e8fe7b4a051c0ea0fcfbf450f/href">https://medium.com/media/aec2ac5e8fe7b4a051c0ea0fcfbf450f/href</a></iframe><p>In this example, we have the Client class tightly coupled with ValidateEmailSimple, every time that we call the setEmail we create a new instance from ValidateEmailSimple, the problem here is when you decide to change this validation to another more complex (ValidateEmailAdvanced), you’ll need a change in Client class all occurrences to the old Validation system, and this could create new bugs and inconsistency in our application.</p><p>The solution to solve this transforms this <strong>tightly coupled dependency </strong>into a <strong>loosely coupled dependenc</strong>y, how to do that? Simple, let’s create a var inside our Client class called _emailValidationService, and call this to validate our email instead of calling directly the validation Class that we need:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a9b100709f630039ef50acbed4092869/href">https://medium.com/media/a9b100709f630039ef50acbed4092869/href</a></iframe><p>With this approach, we don’t need to change the Client class when we decide to put a more advanced Validation Email System, cool right?</p><p>If you want to know more about <strong>Design Patterns</strong> and <strong>SOLID Design Principles</strong> I recommend these books:</p><ul><li><strong>Design Patterns: Elements of Reusable Object-Oriented Software by GoF</strong></li><li><strong>Agile Principles, Patterns, and Practices in C# by Micah Martin and Robert Cecil Martin</strong></li><li><strong>Head First Design Patterns by Elisabeth Freeman and Kathy Sierra</strong></li><li><strong>Learning JavaScript Design Patterns by Addy Osmani</strong></li></ul><p><strong><em>Thanks for reading! Feel free to hit the recommend button below if you found this article helpful.</em></strong></p><p><a href="https://twitter.com/_rxluz">Ricardo Luz (@_rxluz) | Twitter</a></p><blockquote>If this post was helpful, please click the clap 👏 button below to show your support! ⬇⬇</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=db95b44e82e" width="1" height="1" alt=""><hr><p><a href="https://medium.com/front-end-weekly/s-o-l-i-d-principles-with-js-examples-db95b44e82e">S.O.L.I.D Principles with JS examples</a> was originally published in <a href="https://medium.com/front-end-weekly">Frontend Weekly</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[#15 Data Structures with JS examples: Sets]]></title>
            <link>https://medium.com/front-end-weekly/15-data-structures-with-js-examples-sets-5c0c7e52203?source=rss-892e3096e4fa------2</link>
            <guid isPermaLink="false">https://medium.com/p/5c0c7e52203</guid>
            <category><![CDATA[data-structures]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[rxluz]]></category>
            <dc:creator><![CDATA[Ricardo Luz]]></dc:creator>
            <pubDate>Wed, 27 May 2020 13:20:57 GMT</pubDate>
            <atom:updated>2020-05-27T13:20:57.571Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mfz-HW5TIBU0AvprtApydQ.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/photos/FmD8tIkf8bo?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Nick Karvounis</a> on <a href="https://unsplash.com/search/photos/unique?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p>This article belongs to the <strong>JS Data Structures series</strong>, which contains these articles:</p><ul><li><a href="https://medium.com/p/e1bc57bda950">Arrays</a></li><li><a href="https://medium.com/p/7dcea711c091">Stacks</a></li><li><a href="https://medium.com/p/17f714057817">Queues</a></li><li><a href="https://medium.com/p/29cb496d8bff">Linked List</a></li><li><a href="https://medium.com/p/5c0c7e52203"><strong>Sets</strong></a></li><li><em>Dictionaries/maps (soon)</em></li><li><em>Hashes tables (soon)</em></li><li><em>Trees: Binary Search Tree (BST) (soon)</em></li><li><em>Trees: AVL Tree (soon)</em></li><li><em>Trees: Red-black Tree (soon)</em></li><li><em>Trees: Binary Heap / Heapsort</em></li><li><em>Graphs (soon)</em></li></ul><p><strong>Set</strong> are a collection of sequential and unique elements, this structure doesn’t allow adding duplicate values, we have several examples of sets:</p><ol><li>The natural numbers {0, 1, 2, 3, 4, 5, 6, 7, 8 …}</li><li>The followers/following list in any social network</li><li>Some list with tags in blogs</li><li>A shopping list</li><li>A to-do list with unique items</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/400/0*0SvdZ-pfgAFnGClh.gif" /><figcaption>A list with unique lists is a set!</figcaption></figure><p>This article will cover the following content:</p><ul><li><strong>Basic structure</strong></li><li><strong>Sets methods</strong></li><li><strong>Operations with sets</strong></li><li><strong>Using the ES6 Set</strong></li><li><strong>Instantiating our Set</strong></li><li><strong>Time and space complexity</strong></li></ul><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fupscri.be%2Ff%2F788447%3Fas_embed%3Dtrue&amp;dntp=1&amp;display_name=Upscribe&amp;url=https%3A%2F%2Fupscri.be%2F788447%2F&amp;type=text%2Fhtml&amp;schema=upscri" width="800" height="400" frameborder="0" scrolling="no"><a href="https://medium.com/media/18214d8333adbb5668f31791a3202b60/href">https://medium.com/media/18214d8333adbb5668f31791a3202b60/href</a></iframe><h3>Basic structure</h3><p>Let’s create a function that will allow us to output only the public Sets methods. working like a closure, avoiding changes in internal attributes, the skeleton will be:</p><pre>function Set() {<br>  let items = {}<br>  let size = 0</pre><pre>  class PublicSet {<br>    ...the set methods will be here<br>  }</pre><pre>  return new PublicSet()<br>};</pre><p>With this approach, the only public methods will be the methods included in PublicSet class, if you want to know more about closures this article is really useful:</p><p><a href="https://medium.com/javascript-scene/master-the-javascript-interview-what-is-a-closure-b2f0d2152b36">Master the JavaScript Interview: What is a Closure?</a></p><h3>Set methods</h3><p>After we created the basic structure we are ready to implement the required set methods:</p><ul><li><strong>has</strong>: Returns if a set contains an item or not</li><li><strong>add</strong>: Allows add a new item inside a set</li><li><strong>delete</strong>: Remove a specific item from a set</li><li><strong>clear</strong>: Remove all items from a set</li><li><strong>size</strong>: Returns the set number of items</li><li><strong>values</strong>: Returns how many items there are inside a set</li></ul><p><em>Note: In order to create a set you need to create the method </em><em>has before the other methods, once this will be used by the other methods.</em></p><p><strong>has(item)<br></strong>To check if the required item is inside our set, and we have some different ways to do that:</p><pre>has(<em>item</em>) {<br>  return items.hasOwnProperty(item)<br>}</pre><p>Or:</p><pre>has(<em>item</em>) {<br>  return item in items<br>}</pre><p>Or:</p><pre>has(<em>item</em>) {<br>  return typeof items[item] !== &#39;undefined&#39;<br>}</pre><p>I prefer the second approach because the syntax is nicer and cleaner than others.</p><p><strong>add(item)<br></strong>The process to add a new item is simple, first, we check if this item was not added before, if don’t we add this list to our set items.</p><p>In the end, we need increment our size variable.</p><pre>add(item){<br>  if(this.has(item)){<br>    return false<br>  }</pre><pre>  items[item] = item<br>  size++</pre><pre>  return true<br>}</pre><p><strong>delete(item)<br></strong>In order to remove some item, first, we need to check if the item was added before, so if we found the item we remove it.</p><p>Also, we need decrement the size variable.</p><pre>delete(item){<br>  if(!this.has(item)){<br>    return false<br>  }</pre><pre>  delete items[item]<br>  size--</pre><pre>  return true<br>}</pre><p><strong>clear()<br></strong>To clear all items from a set we need to restore the items and size variables to its original state.</p><pre>clear(){<br>  items = {}<br>  size = 0<br>}</pre><p><strong>size()<br></strong>In our approach, we are using the size variable to control the Set size, this helps to get the total without the need to traverse all items in our Set.</p><pre>size(){<br>  return size<br>}</pre><p>Without this approach, we’ll need to use items.keys().length, the problem is when we use this we are using a slower operation to do that, in the time and complexity session this is better explained.</p><p><strong>values()<br></strong>To get all Set values we use the for..in loop:</p><pre>values(){<br>  let valuesList = []<br>  for(let value in items){<br>    valuesList.push(value)<br>  }</pre><pre>  return valuesList<br>}</pre><p><strong>Putting all together</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5a8871e9c4925122441d9a5b416db33a/href">https://medium.com/media/5a8871e9c4925122441d9a5b416db33a/href</a></iframe><p>If you want to check out other <strong>Javascript Data Structures examples</strong> take a look in this GitHub repository:</p><p><a href="https://github.com/rxluz/js-data-structures">rxluz/js-data-structures</a></p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fupscri.be%2Ff%2F788447%3Fas_embed%3Dtrue&amp;dntp=1&amp;display_name=Upscribe&amp;url=https%3A%2F%2Fupscri.be%2F788447%2F&amp;type=text%2Fhtml&amp;schema=upscri" width="800" height="400" frameborder="0" scrolling="no"><a href="https://medium.com/media/18214d8333adbb5668f31791a3202b60/href">https://medium.com/media/18214d8333adbb5668f31791a3202b60/href</a></iframe><h3>Operations with sets</h3><p>Once sets are composed of unique elements we could compare one set with other and create different operations like union, intersection, difference and subset.</p><h4>Union</h4><p>This operation allows joining two different sets to create a new one, example:</p><blockquote>Set A = A,B,C,D</blockquote><blockquote>Set B = B,C,D,E</blockquote><blockquote>Union A with B = A, B, C, D, E</blockquote><p>This concept could be visually represented by this picture:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/0*9wVbc0X9MJTUL7nM.png" /><figcaption>Source: <a href="https://upload.wikimedia.org/wikipedia/commons/0/06/Set_union.png">https://upload.wikimedia.org/wikipedia/commons/0/06/Set_union.png</a></figcaption></figure><p>To find the union set we need:</p><ol><li>Create the Sets.</li><li>Call the union method that accepts as a parameter the second set.</li><li>Get the values from both sets.</li><li>Create a new union empty set where we will store the values.</li><li>Traverse all elements from the first set and add all them in the union set.</li><li>Traverse all elements from the second set and add all them in the union set.</li></ol><p>As a result of these steps we have this code:</p><pre>union(<em>secondSet</em>) {<br>  const unionSet = new <em>Set</em>()<br>  const firstSetValues = <em>this</em>.values()<br>  const secondSetValues = secondSet.values()</pre><pre>  firstSetValues.forEach(<em>value</em> =&gt; {<br>    unionSet.add(value)<br>  })</pre><pre>  secondSetValues.forEach(<em>value</em> =&gt; {<br>    unionSet.add(value)<br>  })</pre><pre>  return unionSet<br>}</pre><p>We could reduce this code using the <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_syntax">spread operator</a> and removing the curly braces from the foreach loop:</p><pre>union(<em>secondSet</em>) {<br>  const unionSet = new <em>Set</em>()<br>  const firstSetValues = <em>this</em>.values()<br>  const secondSetValues = secondSet.values()<br>  const allSetValues = [...firstSetValues, ...secondSetValues]</pre><pre>  allSetValues.forEach(<em>value</em> =&gt; unionSet.add(value))</pre><pre>  return unionSet<br>}</pre><h4>Intersection</h4><p>This operation allows creating a new set with the commons items in both sets, example:</p><blockquote>Set A = a,b,c,d</blockquote><blockquote>Set B = b,c, d,e</blockquote><blockquote>Intersection A and B = b,c,d</blockquote><p>This concept could be visually represented by this picture:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*CqvD1crGtyxr5ASG.png" /><figcaption>Source: <a href="https://upload.wikimedia.org/wikipedia/commons/c/cb/SetIntersection.svg">https://upload.wikimedia.org/wikipedia/commons/c/cb/SetIntersection.svg</a></figcaption></figure><p>To find the intersection set we need:</p><ol><li>Create the Sets.</li><li>Call the intersection method that accepts as a parameter the second set.</li><li>Get the values from both Sets.</li><li>Create a new Set where we will store the values.</li><li>Traverse all elements from the first set checking if the value is also present in the second set, when is present in both we add this value in intersection set.</li><li>Do the same with the second set</li></ol><p>As a result of these steps we have this code:</p><pre>intersection(<em>secondSet</em>) {<br>  const intersectionSet = new <em>Set</em>()<br>  const firstSetValues = <em>this</em>.values()<br>  const secondSetValues = secondSet.values()</pre><pre>  firstSetValues.forEach(<em>value</em> =&gt; {<br>    if (secondSet.has(value)) {<br>      intersectionSet.add(value)<br>    }<br>  })</pre><pre>  secondSetValues.forEach(<em>value</em> =&gt; {<br>    if (<em>this</em>.has(value)) {<br>      intersectionSet.add(value)<br>    }<br>  })</pre><pre>  return intersectionSet<br>}</pre><p>We could reduce this code using the <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_syntax">spread operator</a> and removing the curly braces from the foreach loop:</p><pre>intersection(<em>secondSet</em>) {<br>  const intersectionSet = new <em>Set</em>()<br>  const firstSetValues = <em>this</em>.values()<br>  const secondSetValues = secondSet.values()<br>  const allValues = [...firstSetValues, ...secondSetValues]</pre><pre>  allValues.forEach(<br>    <em>value</em> =&gt;<br>      secondSet.has(value) &amp;&amp; <br>      <em>this</em>.has(value) &amp;&amp; <br>      intersectionSet.add(value),<br>  )</pre><pre>  return intersectionSet<br>}</pre><p>What we did inside our loop is an uncommon but efficient way to call a function only if some condition matches:</p><pre>allValues.forEach(<br>    <em>value</em> =&gt;<br>     <strong> secondSet.has(value) &amp;&amp; <br>      <em>this</em>.has(value) &amp;&amp; <br>      intersectionSet.add(value),</strong><br>  )</pre><p>What’s happening here is, only if the first two conditions are true the function will be called, you could try it in your browser inspector to understand better how it works:</p><pre><strong><em>// this never displays &#39;hello world&#39;:</em></strong><br>true &amp;&amp; false &amp;&amp; console.log(&#39;hello world&#39;)</pre><pre><strong>// this will display &#39;hello world&#39;:<br></strong>true &amp;&amp; true &amp;&amp; console.log(&#39;hello world&#39;) </pre><h4>Difference</h4><p>This operation allows creating a new set with the elements in the first set that is not present in the second set, example:</p><blockquote>Set A = a,b,c,d</blockquote><blockquote>Set B = b,c, d,e</blockquote><blockquote>Difference A and B =a</blockquote><p>This concept could be visually represented by this picture:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/442/0*KEMcQWWXEU65_XXQ.png" /><figcaption>Source: <a href="https://commons.wikimedia.org/wiki/File:SetDifferenceA.svg">https://commons.wikimedia.org/wiki/File:SetDifferenceA.svg</a></figcaption></figure><p>To find the difference set we need:</p><ol><li>Create the Sets.</li><li>Call the difference method that accepts as a parameter the second set.</li><li>Traverse all elements from the first set checking if the value is also present in the second set, when is not present in the second we add this value in difference set.</li></ol><p>As a result of these steps we have this code:</p><pre>difference(<em>secondSet</em>) {<br>  const differenceSet = new <em>Set</em>()<br>  const firstSetValues = <em>this</em>.values()</pre><pre>  firstSetValues.forEach(<em>value</em> =&gt; {<br>    if (!secondSet.has(value)) {<br>      differenceSet.add(value)<br>    }<br>  })</pre><pre>  return differenceSet<br>}</pre><h4>Subset</h4><p>This operation allows checking if the second sets is a subset of the first set, which means that all elements in a second set also is inside the first set, example:</p><blockquote>Set A = a,b,c,d</blockquote><blockquote>Set B = b,c</blockquote><blockquote>Set c = b,c, d, e</blockquote><blockquote>B is subset of A=true</blockquote><blockquote>C is subset of A = false</blockquote><p>This concept could be visually represented by this picture:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/300/0*Hmb9dc182jBRi8yV.png" /><figcaption>Source: <a href="https://commons.wikimedia.org/wiki/File:Set_subsetBofA.svg">https://commons.wikimedia.org/wiki/File:Set_subsetBofA.svg</a></figcaption></figure><p>To check if a second set is a subset of the first set we need:</p><ol><li>Create the Sets.</li><li>Call the subset method that accepts as a parameter the second set.</li><li>Traverse all elements from the second set checking if the value is also present in the first set and return true if all values match this condition or false if don’t.</li></ol><p>As a result of these steps we have this code:</p><pre>subset(<em>secondSet</em>) {<br>  if (secondSet.size() &lt; <em>this</em>.size()) {<br>    return false<br>  }</pre><pre>  const firstSetValues = this.values()</pre><pre>  for (let value of firstSetValues) {<br>    if (!secondSet.has(value)) {<br>      return false<br>    }<br>  }</pre><pre>  return true<br>}</pre><p>We also could do the same using <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/every">every js native method</a>:</p><pre>subset(<em>secondSet</em>) {<br>  if (secondSet.size() &lt; <em>this</em>.size()) {<br>    return false<br>  }<br>  <br>  return <em>this</em>.values().every(<em>value</em> =&gt; secondSet.has(value))<br>}</pre><h3><strong>Using the ES6 Set</strong></h3><p>We could use the native JS method Set to do what we did with our code, let’s try an example from <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set">MDN Sets documentation</a>:</p><pre>var mySet = new Set();<br><br>mySet.add(1); // Set [ 1 ]<br>mySet.add(5); // Set [ 1, 5 ]<br>mySet.add(5); // Set [ 1, 5 ]<br>mySet.add(&#39;some text&#39;); // Set [ 1, 5, &#39;some text&#39; ]<br>var o = {a: 1, b: 2};<br>mySet.add(o);<br><br>mySet.add({a: 1, b: 2}); // o is referencing a different object so this is okay<br><br>mySet.has(1); // true<br>mySet.has(3); // false, 3 has not been added to the set<br>mySet.has(5);              // true<br>mySet.has(Math.sqrt(25));  // true<br>mySet.has(&#39;Some Text&#39;.toLowerCase()); // true<br>mySet.has(o); // true<br><br>mySet.size; // 5<br><br>mySet.delete(5); // removes 5 from the set<br>mySet.has(5);    // false, 5 has been removed<br><br>mySet.size; // 4, we just removed one value<br>console.log(mySet);// Set [ 1, &quot;some text&quot;, Object {a: 1, b: 2}, Object {a: 1, b: 2} ]</pre><p>Also, we could simulate our operations using ES6 Sets:</p><pre>// from <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set">https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set</a></pre><pre>function isSuperset(set, subset) {<br>    for (var elem of subset) {<br>        if (!set.has(elem)) {<br>            return false;<br>        }<br>    }<br>    return true;<br>}</pre><pre>function union(setA, setB) {<br>    var _union = new Set(setA);<br>    for (var elem of setB) {<br>        _union.add(elem);<br>    }<br>    return _union;<br>}<br><br>function intersection(setA, setB) {<br>    var _intersection = new Set();<br>    for (var elem of setB) {<br>        if (setA.has(elem)) {<br>            _intersection.add(elem);<br>        }<br>    }<br>    return _intersection;<br>}<br><br><br>function difference(setA, setB) {<br>    var _difference = new Set(setA);<br>    for (var elem of setB) {<br>        _difference.delete(elem);<br>    }<br>    return _difference;<br>}<br><br>//Examples<br>var setA = new Set([1, 2, 3, 4]),<br>    setB = new Set([2, 3]),<br>    setC = new Set([3, 4, 5, 6]);<br><br>isSuperset(setA, setB); // =&gt; true<br>union(setA, setC); // =&gt; Set [1, 2, 3, 4, 5, 6]<br>intersection(setA, setC); // =&gt; Set [3, 4]<br>difference(setA, setC); // =&gt; Set [1, 2]</pre><h3>Instantiating our Set</h3><p>After declaring your Set, you could call it in this way:</p><pre>const mySet = new <em>Set</em>();</pre><pre><strong><em>// adding items<br></em></strong>mySet.add(&quot;a new item&quot;);</pre><pre><strong><em>// searching for a item</em></strong><br>mySet.has(&quot;a new item&quot;);</pre><pre><strong><em>// getting the set  size</em></strong><br>mySet.size()</pre><pre><strong><em>// getting all items inside a set</em></strong><br>mySet.values()</pre><pre><strong><em>// removing item</em></strong><br>mySet.delete(&quot;a new item&quot;);</pre><pre><strong><em>// removing all items inside a set</em></strong><br>mySet.clear()</pre><h3>Time and space complexity</h3><p><strong>Time complexity</strong> defines <strong>how faster</strong> is your algorithm, and <strong>space complexity </strong>defines how <strong>much memory your algorithm needs to run, </strong>this is also called <strong>Big-O notation.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SB5fLibxprTSNLx9We07ow.png" /><figcaption>From <a href="http://bigocheatsheet.com/">http://bigocheatsheet.com/</a></figcaption></figure><p>Let’s analyse the methods inside our set to find out this:</p><ul><li><strong>add</strong>: We have <strong>O(1) to time and O(1) to space</strong>, once the time and memory that we need to run this operation remains the same regardless of the number of items inside our Set.</li><li><strong>delete</strong>: Same thing here, <strong>O(1) to time and O(1) to space</strong>.</li><li><strong>has</strong>: Differently from arrays we don’t need to traverse the items inside a set to check if an item exists or not, also we don’t need store any additional information in memory to run this operation, thus this is <strong>O(1) to time and O(1) to space</strong>.</li><li><strong>clear</strong>: When we clear our set we simply redefine the items object to an empty one, this operation is <strong>O(1) to time and to space because</strong> will take the same time and memory regardless of the set size.</li><li><strong>size</strong>: We are using the variable size to control the set length, with this approach this operation takes the same time and space even with millions of items, thus <strong>O(1) to time and space</strong>.</li><li><strong>values</strong>: To get all items and output them in array format we need to transverse all items inside our set, push each one to a temporary array and output them, it means that bigger set will take more time and space to run this same operation, so <strong>O(n) to time and space.</strong></li></ul><p>Also, let’s check the time and space complexity of the Sets Operations:</p><ul><li><strong>union</strong>: To understand better let’s divide this algorithm into steps, and check the complexity of each one:</li></ul><pre>union(<em>secondSet</em>) {<br>  const unionSet = new <em>Set</em>() <strong>// O(1) time and O(1) space</strong><br>  const firstSetValues = <em>this</em>.values() <strong>// O(n) time and O(n) space</strong><br>  const secondSetValues = secondSet.values() <strong>// O(n) time and O(n) space</strong></pre><pre>  firstSetValues.forEach(<em>value</em> =&gt; { <strong>// O(n) time and O(1) space</strong><br>    unionSet.add(value) <strong>// O(1) time and O(n) space</strong><br>  })</pre><pre>secondSetValues.forEach(<em>value</em> =&gt; { <strong>// O(n) time and O(1) space</strong><br>    unionSet.add(value) <strong>// O(1) time and O(n) space</strong><br>  })</pre><pre>  return unionSet<br>}</pre><p>When we put all together we have:</p><p>Time: O(1), O(N), O(N), O(N), O(1), O(N), O(1) = O(N)<br>Space: O(1), O(N), O(N), O(1), O(N), O(1), O(N) = O(N)</p><p>Thus <strong>O(n) both to space and time</strong>.</p><ul><li><strong>intersection</strong>: Same thing here <strong>O(n) to space and time</strong>.</li><li><strong>difference</strong>: We need more time as we have more items, and more memory to store the result, so we have <strong>O(n) to space and time</strong>.</li><li><strong>subset</strong>: This operation will take more time when you have more items, but will use the same memory regardless of the number of items, therefore is <strong>O(n) to time and O(1) to space.</strong></li></ul><p>If you want to know more about <strong>Big O Notation</strong> and how to calculate this I wrote this article that will help you:</p><p><a href="https://medium.com/front-end-weekly/big-o-in-js-the-basic-that-you-need-to-know-a5abb45570fa">#9 Big O in JS: The basic that you need to know</a></p><p>If you to want to know more about <strong>Javascript and Data Structures</strong> I recommend these books:</p><ul><li><strong>You Don’t Know JS Serie by Kyle Simpson (My favourite)</strong></li><li><strong>Eloquent JS by Marijn Haverbeke</strong></li><li><strong>Head First Javascript by Michael Morrison</strong></li><li><strong>Secrets of the JavaScript Ninja by Bear Bibeault and John Resig</strong></li><li><strong>Learning JavaScript Data Structures and Algorithms by Loiane Groner</strong></li></ul><p><strong><em>Thanks for reading! Feel free to hit the recommend button below if you found this article helpful, also, </em>please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.</strong></p><p><a href="https://twitter.com/_rxluz">Ricardo Luz (@_rxluz) | Twitter</a></p><blockquote>If this post was helpful, please click the clap 👏 button below to show your support! ⬇⬇</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5c0c7e52203" width="1" height="1" alt=""><hr><p><a href="https://medium.com/front-end-weekly/15-data-structures-with-js-examples-sets-5c0c7e52203">#15 Data Structures with JS examples: Sets</a> was originally published in <a href="https://medium.com/front-end-weekly">Frontend Weekly</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[#14 JS Data Structures: Linked List]]></title>
            <link>https://medium.com/@_rxluz/14-js-data-structures-linked-list-29cb496d8bff?source=rss-892e3096e4fa------2</link>
            <guid isPermaLink="false">https://medium.com/p/29cb496d8bff</guid>
            <category><![CDATA[interview]]></category>
            <category><![CDATA[interview-questions]]></category>
            <category><![CDATA[javascript-tips]]></category>
            <category><![CDATA[data-structures]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Ricardo Luz]]></dc:creator>
            <pubDate>Sun, 19 Apr 2020 14:39:13 GMT</pubDate>
            <atom:updated>2020-04-19T14:49:30.801Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0F2QxXjksOkcmVhDYp_Rxw.png" /><figcaption>Photo by <a href="https://unsplash.com/photos/DtWyp_4YEes?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Ishan @seefromthesky</a> on <a href="https://unsplash.com/search/photos/connected?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><h3>#14 Data Structures with JS examples: Linked List</h3><p>This article belongs to the <strong>JS Data Structures series</strong>, which contains these articles:</p><ul><li><a href="https://medium.com/p/e1bc57bda950">Arrays</a></li><li><a href="https://medium.com/p/7dcea711c091">Stacks</a></li><li><a href="https://medium.com/p/17f714057817">Queues</a></li><li><a href="https://medium.com/p/29cb496d8bff"><strong>Linked List</strong></a></li><li><em>Sets (soon)</em></li><li><em>Dictionary and Hashes (soon)</em></li><li><em>Trees: Binary Search Tree (BST) (soon)</em></li><li><em>Trees: AVL Tree (soon)</em></li><li><em>Trees: Red-black Tree (soon)</em></li><li><em>Trees: Binary Heap / Heapsort (soon)</em></li><li><em>Graphs (soon)</em></li></ul><p><strong>Linked Lists</strong> are a collection of elements where is possible to add items in any position that you want, we have several practical examples of linked lists like:</p><ol><li>Creating a music player (next, previous, skip back/forward)</li><li>Manage low-level memory where each node representing a used or available (free) block of memory</li><li>The train wagons (probably the most famous example).</li><li>And my favourite: A dog conga line:</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/400/0*s6rsswdb3oSvBNTx" /><figcaption>A good example of a real-world linked list!</figcaption></figure><p>This article will cover the following content:</p><ul><li><strong>Basic structure</strong></li><li><strong>Linked list methods</strong></li><li><strong>Doubly linked list</strong></li><li><strong>Instantiating your linked list</strong></li><li><strong>Time and space complexity</strong></li></ul><h3>Basic structure</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/0*dFPMUcRahZTEmvdy.jpg" /><figcaption>Source: <a href="https://commons.wikimedia.org/wiki/File:Linkedlist.jpg">https://commons.wikimedia.org/wiki/File:Linkedlist.jpg</a></figcaption></figure><p>Let’s create a closure function that will allow us to output only the public Linked List methods, avoiding changes in internal attributes, the skeleton will be:</p><pre>const LinkedList = (() =&gt; {<br>  let head = null<br>  let length = 0</pre><pre>  class Utils {<br>    ...the utils methods<br>  }</pre><pre>  class PublicLinkedList {<br>    ...the linked list methods will be here<br>  }</pre><pre>  return PublicLinkedList<br>})();</pre><p>With this approach, the only public methods will be the methods included in PublicLinkedList class, if you want to know more about closures this article is really useful:</p><p><a href="https://medium.com/javascript-scene/master-the-javascript-interview-what-is-a-closure-b2f0d2152b36">Master the JavaScript Interview: What is a Closure?</a></p><p>You’ll need to create a Utils class with a static node method to each one of Linked List elements as well a reference to the next node.</p><pre>class Utils {<br>  <strong>static</strong> node(<em>element</em>){<br>    return {<br>      element,<br>      next: null<br>    }<br>  }<br>}</pre><p>Using the static before the item function name, we are able to call this function without instantiating the Utils class. If you want to know more about static methods in JS this article will help you:</p><p><a href="https://medium.com/@assortedPickle/es6-static-properties-b7fd2a163328">ES6 static properties.</a></p><h3>Linked List methods</h3><p>After we created the basic structure we are ready to implement the required linked list methods:</p><ul><li>size</li><li>isEmpty</li><li>append</li><li>insert</li><li>removeAt</li><li>remove</li><li>indexOf</li><li>getHead</li><li>toString</li></ul><h4>size()</h4><p>This method returns how many items there are inside a linked list, you’ll need simply return the length variable:</p><pre>size(){<br>  return length<br>}</pre><h4>isEmpty()</h4><p>This method returns if the linked list contains or not contains items inside, to do that you’ll use the size linked list attribute is equal to zero:</p><pre>isEmpty(){<br>  return this.size() === 0<br>}</pre><h4>append(element)</h4><p>This method allows to add an item at the end of a list, when we append an item we need to change the next attribute of the current last item of a list to refer to this new item, we don’t need to do that when the list is empty, but we need to change the head of the list to refer to this new item, the visual concept is this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ev4ar_ZMzBOz2D4w9N3BNA.png" /><figcaption>Source: <a href="https://www.cs.cmu.edu/~adamchik/15-121/lectures/Linked%20Lists/linked%20lists.html">https://www.cs.cmu.edu/~adamchik/15-121/lectures/Linked%20Lists/linked%20lists.html</a></figcaption></figure><p>The code that we need to do that is this:</p><pre>append(element){<br>  const newItem = Utils.node(element)</pre><pre>  if(this.isEmpty()){<br>    head = newItem<br>  } else {<br>    let currentLastItem = head<br>    while(currentLastItem.next !== null){<br>      currentLastItem = currentLastItem.next<br>    }</pre><pre>    currentLastItem.next = newItem<br>  }</pre><pre>  length++<br>}</pre><h4>insert(position, element)</h4><p>This method allows adding a new item in any position of a Linked List, to do that we need:</p><ol><li>Checks if the desired position is the first, in this case, we need to store the current head value as the next value of the new element, after this, we need to replace the head by this new element.</li><li>If is not the first element we need to get the element that is currently placed in the same position that we need to add the new element and then:<br>2.1. Change the next value of this element, pointing to the new item<br>2.2. Change the next value of the new element, pointing to the element that is currently placed in the next position after that we need to add the new element</li><li>Increase the length value</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*-s6NkiDMsUSYjtO7.png" /><figcaption>Source: <a href="https://en.wikipedia.org/wiki/Linked_list">https://en.wikipedia.org/wiki/Linked_list</a></figcaption></figure><p>The code that we need to do that is:</p><pre>insert(position, element){<br>  if (position &lt; 0 || position &gt; length) {<br>    throw new <em>Error</em>(&quot;Invalid position&quot;)<br>  }</pre><pre>  const newNode = Utils.n<em>ode</em>(element)</pre><pre>  if (position === 0) {<br>    newNode.next = head<br>    head = newNode<br>  } else {<br>    let previousNode = head<br>    let nextNode = head.next<br>    let currentNode = head<br>    let currentPosition = 0</pre><pre>    while (currentPosition++ &lt; position) {<br>      previousNode = currentNode<br>      nextNode = currentNode.next<br>      currentNode = currentNode.next<br>    }</pre><pre>    previousNode.next = newNode<br>    newNode.next = nextNode<br>  }</pre><pre>  length++</pre><pre>  return true<br>}</pre><h4>removeAt(position)</h4><p>This method allows removing an item in any position, to archive that we need:</p><ol><li>If the element is the first element we need to set the head value to the next value of the current head attribute.</li><li>If this element is not the first element we need to:<br>2.1. Get the element placed <strong>before</strong> the position that we want to remove.<br>2.2. Get the element placed <strong>after</strong> the position that we want to remove.<br>2.3. Change the next value of the element before to refer to the element after the position that we want to remove.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/380/0*CuxiE3I8lECtzGV1.png" /><figcaption>Source: <a href="https://en.wikipedia.org/wiki/Linked_list">https://en.wikipedia.org/wiki/Linked_list</a></figcaption></figure><p>3. Return the element removed.</p><p>The code to do that is:</p><pre>removeAt(<em>position</em>) {<br>  if (position &lt; 0 || position &gt; length - 1) {<br>    throw <strong>new</strong> <em>Error</em>(&quot;Invalid position&quot;)<br>  }</pre><pre>  length--</pre><pre>  if (position === 0) {<br>    const currentHeadELement = <em>Object</em>.assign({}, head)<br>    head = head.next<br>    return currentHeadELement.element<br>  }</pre><pre>  let currentPosition = 0,<br>    nodeBefore,<br>    currentNode</pre><pre>  while (currentPosition++ &lt; position) {<br>    nodeBefore = currentNode<br>    currentNode = currentNode.next<br>  }</pre><pre>  nodeBefore.next = currentNode.next<br> <br>  return currentNode.element<br>}</pre><h4>remove(element)</h4><p>This method allows removing a given element from linked this, to do that we need:</p><ol><li>Go through the linked list until we find this element.</li><li>Store the previous element before this and the next element after this.</li><li>Change the reference in the previous element next value to point to the next element after the element that will be deleted.</li><li>If the element is not found, return false, if the element is found first decrease the length attribute and after returns true.</li></ol><p>The code is:</p><pre>remove(<em>element</em>) {<br>  if (<em>this</em>.isEmpty()) {<br>    throw new <em>Error</em>(&quot;The linked list is empty&quot;)<br>  }</pre><pre>  if (head.element === element) {<br>    head = head.next<br>    length--<br>    return true<br>  }</pre><pre>  let currentNode = head<br>  let previousNode</pre><pre>  while (currentNode !== null &amp;&amp; currentNode.element !== element) {<br>    previousNode = currentNode<br>    currentNode = currentNode.next<br>  }</pre><pre>  if (currentNode === null || currentNode.element !== element) {<br>    return false<br>  }<br>  <br>  previousNode.next = currentNode.next<br>  length--<br>  return true<br>}</pre><h4>indexOf(element)</h4><p>This method allows checking the position where is some element inside a linked list, to archive this we need to do:</p><ol><li>Go through the linked list until we find this element.</li><li>When finding the item returns the index of the item, or return -1 case the item is not found</li></ol><p>The code is:</p><pre>indexOf(<em>element</em>) {<br>  if (<em>this</em>.isEmpty()) {<br>    throw new <em>Error</em>(&quot;The linked list is empty&quot;)<br>  }</pre><pre>  for (<br>    let currentItem = head, positionItem = 0;<br>    currentItem !== null;<br>    currentItem = currentItem.next, positionItem++</pre><pre>  ) {<br>    if (currentItem.element === element) {<br>      return positionItem<br>    }<br>  }</pre><pre>  return -1<br>}</pre><p>In this example, we are using FOR structure with more than one variable and increment, some developers don’t know all things that are possible with FOR, most people only know this:</p><pre>for(let index = 0; index &lt; 10; index++){<br>   ...some code here<br>}</pre><p>But is possible to create as well as increment more variables when you create the FOR loop, like this example:</p><pre>for(<br>  <strong><em>// you could define more than one initial variable, separing with comma<br>  </em></strong>let index = 0, myVar = &#39;&#39;; </pre><pre>  index &lt; 10; </pre><pre>  <strong><em>// you could increment more than one variable, separing them with comma<br>  </em></strong>index++,myVar=index*2<br>  <br>){<br>  console.log(index, myVar)<br>}</pre><pre><em>/* will output:<br>  0, 0<br>  1, 2<br>  2, 4<br>  3, 6<br>  4, 8<br>  5, 10<br>  6, 12<br>  7, 14<br>  8, 16<br>  9, 18<br> 10, 20<br>*/</em></pre><p>If you want to know more about loops in JS I wrote this article about this:</p><p><a href="https://medium.com/@_rxluz/10-js-basics-the-different-loops-and-examples-cd871895d2aa">#10 JS Basics: The different loops and examples</a></p><h4>getHead()</h4><p>This method is fundamental because it allows retrieving all data inside our Linked list, its implementation is very simple</p><pre>getHead() {<br>  return head<br>}</pre><p>Calling this method and using the next attribute is possible to get all elements.</p><h4>toString()</h4><p>The javascript has a default toString method to Objects and Arrays, if you try to use to string in an array JS will return this:</p><pre>[1, 2, 3, 4, 5, 6].toString()<br>// will output: &quot;1,2,3,4,5,6&quot;</pre><p>If you try an object:</p><pre>({hello: &#39;world&#39;}).toString()<br>// will output: &quot;[object Object]&quot;</pre><p>But none of these behaviours is what we want to our linked list when we call toString method, what we want is this function outputs all our element values inside our nodes, to do that we need to reimplement this method to override the default JS one.</p><p>To archive this we need:</p><ol><li>Go through the linked list and store all elements values in a string</li><li>Output this string</li></ol><p>This is the code:</p><pre>toString() {<br>  if (<em>this</em>.isEmpty()) {<br>    throw <strong>new</strong> <em>Error</em>(&quot;The linked list is empty&quot;)<br>  }</pre><pre>  let outputString = &quot;&quot;</pre><pre>  const addComma =<br>    <em>currentString</em> =&gt; (currentString !== &quot;&quot; ? &quot;, &quot; : &quot;&quot;)</pre><pre>  for (<br>    let currentItem = head;<br>    currentItem !== null;<br>    currentItem = currentItem.next<br>  ) {<br>    outputString = `${outputString}${addComma(outputString)}${currentItem.element}`<br>  }</pre><pre>  return outputString<br>}</pre><h4>Putting all together</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d698b0de09b77436301ca5cc7e4e9ed8/href">https://medium.com/media/d698b0de09b77436301ca5cc7e4e9ed8/href</a></iframe><p>If you want to check out other <strong>Javascript Data Structures examples</strong> take a look in this GitHub repository:</p><p><a href="https://github.com/rxluz/js-data-structures">rxluz/js-data-structures</a></p><h3><strong>Doubly linked list</strong></h3><p>The main difference between a common linked list and a doubly-linked list is inside a doubly linked list each node has an additional attribute to refer to the previous node, also a doubly linked list has a new attribute called tail that allows knowing what is the last node without the need go through all items, this makes the append function faster.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*8jNSkfS0Jti8blMS.png" /><figcaption>Source: <a href="https://en.wikipedia.org/wiki/Linked_list">https://en.wikipedia.org/wiki/Linked_list</a></figcaption></figure><p>The methods list remains the same, but inside some of them we have some differences that we need to implement</p><h4>append(element)</h4><p>Unlike a Linked List in a Doubly Linked List, we don’t need to go through all items to find the last item and add a new item after this, we simply do that:</p><ol><li>If the Linked List is empty, we need to refer to this new node to the head and put the tail as a null value</li><li>Add a reference in the old tail to the new tail using the next attribute</li><li>In the new node, we refer the prev value to old tail</li><li>Finally, we replace the tail with the new node</li></ol><pre>append(<em>element</em>) {<br>  const newNode = <strong>Utils.n</strong><em>ode</em>(element)<br>  if (<em>this</em>.isEmpty()) {<br>    <strong><em>// its means that this item will be the head and tail<br>    </em></strong>head = newNode<br>    tail = newNode<br>  } else if (<em>this</em>.size() === 1) {<br>    <strong>// its means that this DLL have only the head, so we need refer the newNode to the head<br>    </strong>head.next = newNode<br>    newNode.prev = head<br>    tail = newNode<br>  } else {<br>    <strong><em>// its means that this DLL have more than 1 item so we only need change the tail<br>    </em></strong>tail.next = newNode<br>    newNode.prev = tail<br>    tail = newNode<br>  }</pre><pre>  <strong><em>// in the end we need increase the length of our DLL<br>  </em></strong>length++<br>  return true<br>}</pre><h4>insert(position, element)</h4><p>The difference between inserting items in a simple Linked Linked list and in a Doubly Linked List is you’ll need to change the previous value of the nodes involved in this operation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/495/0*ttRL5n2HVx9-qBax.png" /><figcaption>Source: <a href="https://en.wikipedia.org/wiki/Linked_list">https://en.wikipedia.org/wiki/Linked_list</a></figcaption></figure><p>Bellow the code with the differences from the Linked List explained:</p><pre>insert(<em>position</em>, <em>element</em>) {<br>  if (position &lt; 0 || position &gt; length) {<br>    throw <strong>new</strong> <em>Error</em>(&#39;Invalid position&#39;)<br>  }</pre><pre>  const newNode = Utils.n<em>ode</em>(element)</pre><pre>  if (position === 0) { <em>// will add as fist item</em><br>    if (<em>this</em>.isEmpty()) {<br><strong>      <em>// the DLL is empty, its meand that this element is the head and tail</em></strong><em><br>      </em>head = newNode<br>      tail = newNode|<br>    } else if (<em>this</em>.size() === 1) {<br><strong>      <em>// the DLL has only one node, its meand that this current node is the new tail and the new node is the head</em></strong><em><br>      </em>head.prev = newNode<br>      tail = head<br>      newNode.next = tail<br>      head = newNode<br>    } else {<br>      <strong><em>// the DLL has more than one item, it&#39;s meand that the newNode is the head, and the current head will refer to newNode<br>      </em></strong>newNode.next = head<br>      head.prev = newNode<br>      head = newNode<br>    }<br>  } else if (position === length) {<br>    <strong><em>// this means that this item will be added in the end, so is possible to use the append method - we need add return to avoid increase the length 2 times<br>    </em></strong>return <em>this</em>.append(element)<br>  } else {<br>    <strong><em>// this means that this item will be added between the first and the last, we need search the current item that is placing the desired position and add the new item before this item<br>    </em></strong>let currentNode = head<br>    let currentPosition = 0<br>    while (currentPosition &lt; position) {<br>      currentNode = currentNode.next<br>      currentPosition++<br>    }</pre><pre>    const prevNode = currentNode.prev<br>    prevNode.next = newNode<br>    newNode.prev = prevNode<br>    newNode.next = currentNode<br>    currentNode.prev = newNode<br>  }</pre><pre>  <strong><em>// in the end we need to increase the length<br>  </em></strong>length++</pre><pre>  return true</pre><pre>}</pre><h4>removeAt(position)</h4><p>To remove an item from a doubly-linked list we need to change the next value from the element left from the element that will be removed and change the prev value from the element in the right:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/263/0*vELNlUdUKLFX23K2.png" /><figcaption>Source: <a href="https://it.wikipedia.org/wiki/Lista_concatenata">https://it.wikipedia.org/wiki/Lista_concatenata</a></figcaption></figure><pre>removeAt(<em>position</em>) {<br>  if (position &lt; 0 || position &gt;= length) {<br>    throw <strong>new</strong> <em>Error</em>(&#39;Invalid position&#39;)<br>  }</pre><pre>  if (position === 0) {<br>    <strong><em>// will remove a item from the beggining, to we need use the head attribute to do that<br>    </em></strong>if (<em>this</em>.size() === 1) {<br>    <strong><em>// we need change the head and the tail once this DLL has only one element<br>      </em></strong>head = null<br>      tail = null<br>    } else {<br>      <strong><em>// this DLL has more than one item, we need change the head<br>      </em></strong>head = head.next<br>      head.prev = null<br>    }<br>  } else if (position === length - 1) {<br>    <strong><em>//this case means that this item will be removed from tail<br>    </em></strong>tail = tail.prev<br>    tail.next = null<br>  } else {<br>    <strong><em>// this case means that this item will be remove from the middle<br>    </em></strong>let currentPosition = 0<br>    let currentNode = head</pre><pre>    while (currentPosition &lt; position) {<br>      currentPosition++<br>      currentNode = currentNode.next<br>    }</pre><pre>    const prevNode = currentNode.prev<br>    const nextNode = currentNode.next<br>    prevNode.next = nextNode<br>    nextNode.prev = prevNode<br>  }</pre><pre>  // in the end we reduce the length and return true<br>  length--<br>  return true<br>}</pre><h4><strong>remove(element)</strong></h4><p>Remove an item using the element name in a doubly-linked list is almost the same process, the difference is you need to change the next value from the item in the left of the removed item and the previous value from the item in the right</p><pre>remove(<em>element</em>) {<br>  if (<em>this</em>.isEmpty()) {<br>    throw new <em>Error</em>(&#39;The linked list is empty&#39;)<br>  }</pre><pre>  <strong><em>// first will check if the removed item is the head<br>  </em></strong>if (head.element === element) {<br>    if (<em>this</em>.size() === 1) {<br>      <strong><em>// in this case we&#39;ll need to remove the tail and the head<br>      </em></strong>head = null<br>      tail = null<br>    } else {<br>      <strong><em>// this case means that this DLL has at leat 2 items, so we need only change the head<br>      </em></strong>head = head.next<br>      head.prev = null<br>    }<br>  <br>    length--<br>    return true<br>  }</pre><pre>  if (tail.element === element) {<br>    <strong><em>// this means that we need remove the tail from this DLL<br>    </em></strong>tail = tail.prev<br>    tail.next = null<br>    length--<br>    return true<br>  }</pre><pre>  <strong><em>// this case means that we need search though all elements<br>  </em></strong>let currentNode = head.next<br>  while (currentNode !== null &amp;&amp; currentNode.element !== element) {<br>    currentNode = currentNode.next<br>  }</pre><pre>  if (currentNode.element === element) {<br>    <strong><em>//this means that the item was found, so we could remove them<br>    </em></strong>let previousNode = currentNode.prev<br>    let nextNode = currentNode.next<br>    previousNode.next = nextNode<br>    nextNode.prev = previousNode<br>    length--<br>    return true<br>  }</pre><pre>  <strong><em>//this means that the item was not found<br>  </em></strong>return false<br>}</pre><p><strong>The other methods (size, isEmpty, indexOf and toString) remains the same.</strong></p><h4>Putting all together</h4><p>This is the result of a Doubly Linked List</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/43aa1b402337206d4d824242e5912a96/href">https://medium.com/media/43aa1b402337206d4d824242e5912a96/href</a></iframe><p>If you want to check out other <strong>Javascript Data Structures examples</strong> take a look in this GitHub repository:</p><p><a href="https://github.com/rxluz/js-data-structures">rxluz/js-data-structures</a></p><h3><strong>Instantiating our linked list</strong></h3><p>After declaring your Linked List, you could call it in this way:</p><pre>const myLinkedList = new <em>LinkedList</em>();</pre><pre><strong><em>// adding items in the bottom<br></em></strong>myLinkedList.append(&quot;a new item&quot;);</pre><pre><strong><em>// adding items in the top<br></em></strong>myLinkedList.insert(0, &quot;first item&quot;);</pre><pre><strong><em>// searching for a item</em></strong><br>myLinkedList.indexOf(&quot;first item&quot;);</pre><pre><strong><em>// getting the LL size</em></strong><br>myLinkedList.size()</pre><pre><strong><em>// checking if the LL is empty</em></strong><br>myLinkedList.isEmpty()</pre><pre><strong><em>// removing item by index</em></strong><br>myLinkedList.removeAt(1);</pre><pre><strong><em>// removing item by name</em></strong><br>myLinkedLIst.remove(&quot;a new item&quot;)</pre><pre><strong><em>// getting all elements inside your LL</em></strong><br>myLinkedList.toString()</pre><h3><strong>Time and space complexity</strong></h3><p><strong>Time complexity</strong> defines <strong>how faster</strong> is your algorithm, and <strong>space complexity </strong>defines how <strong>much memory your algorithm needs to run, </strong>this is also called <strong>Big-O notation.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SB5fLibxprTSNLx9We07ow.png" /><figcaption>From <a href="http://bigocheatsheet.com/">http://bigocheatsheet.com/</a></figcaption></figure><p>Let’s analyse the methods inside our linked list to find out this:</p><ul><li><strong>size</strong>: We have <strong>O(1) to time and O(1) to space</strong>, both to Linked List and Doubly Linked List, once the time and memory that we need to run this operation remains the same regardless of the number of items inside our Linked List.</li><li><strong>isEmpty</strong>: Same thing here, <strong>O(1) to time and O(1) to space</strong> to both linked list types.</li><li><strong>append</strong>: The complexity in the append method varies according to the type of Linked list:</li></ul><p>— <strong>Linked List</strong>: To add an item at the bottom we need to go through all items until we found the last item and connect this last item with the new one that we want to add, it means that the <strong>time complexity is O(n)</strong>, but the memory that we need remains constant because we don&#39;t need to store the sequence of nodes, only the last node, so <strong>the space complexity is O(1)</strong>.</p><p>— <strong>Doubly Linked List</strong>: In this case, we have the tail variable that helps us to identify faster which is the last item of our Doubly Linked List, making the time to append this item constant regardless of the number of items, the same applies to memory, its usage doesn’t increase according to the number of items, so we have <strong>O(1) to time and space</strong>.</p><ul><li><strong>insert</strong>: To insert an item in our lists we need to find the element that is currently placed in the same position that we want to add and move this element, it means that this operation will take more time with more items thus its <strong>time complexity is O(n)</strong>, but the memory that we need to allocate is the same if the list has one or one million items so <strong>O(1) is the space complexity</strong>.</li><li><strong>removeAt</strong>: To remove an item from a given position we need to go through our Linked List until we found this position, it means that this operation will take more time when the Linked List grows, but the memory that we need remains the same, thus <strong>O(n) to time complexity and O(1) to space complexity</strong>.</li><li><strong>remove</strong>: Same thing here <strong>O(n) to time complexity and O(1) to space complexity.</strong></li><li><strong>indexOf</strong>: To find an item that matches with a given string we need to go through our Linked List until we found it, it means that this operation will take more time when the Linked List grows, but the memory that we need remains the same, thus <strong>O(n) to time complexity and O(1) to space complexity</strong>.</li><li><strong>toString</strong>: You need to go through all items and join all them in a string to print, <strong>so space and time complexity will be O(n)</strong> once you need more memory and time according to the Linked List size.</li></ul><p>If you want to know more about <strong>Big O Notation</strong> and how to calculate this I wrote this article that will help you:</p><p><a href="https://medium.com/front-end-weekly/big-o-in-js-the-basic-that-you-need-to-know-a5abb45570fa">#9 Big O in JS: The basic that you need to know</a></p><p>If you to want to know more about <strong>Javascript and Data Structures</strong> I recommend these books:</p><ul><li><strong>You Don’t Know JS Serie by Kyle Simpson (My favourite)</strong></li><li><strong>Eloquent JS by Marijn Haverbeke</strong></li><li><strong>Head First Javascript by Michael Morrison</strong></li><li><strong>Secrets of the JavaScript Ninja by Bear Bibeault and John Resig</strong></li><li><strong>Learning JavaScript Data Structures and Algorithms by Loiane Groner</strong></li></ul><p><strong><em>Thanks for reading! Feel free to hit the recommend button below if you found this piece helpful, also, </em>please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.</strong></p><p><a href="https://twitter.com/_rxluz">Ricardo Luz (@_rxluz) | Twitter</a></p><blockquote>If this post was helpful, please click the clap 👏 button below to show your support! ⬇⬇</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=29cb496d8bff" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[#13 JS Data Structures: Queues]]></title>
            <link>https://medium.com/@_rxluz/13-js-data-structures-queues-17f714057817?source=rss-892e3096e4fa------2</link>
            <guid isPermaLink="false">https://medium.com/p/17f714057817</guid>
            <category><![CDATA[data-structures]]></category>
            <category><![CDATA[tutorial]]></category>
            <category><![CDATA[queue]]></category>
            <category><![CDATA[rxluz]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Ricardo Luz]]></dc:creator>
            <pubDate>Tue, 30 Apr 2019 07:34:42 GMT</pubDate>
            <atom:updated>2019-04-30T07:34:42.864Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ttf8XdTsY-w3h1prAqdAVg.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/photos/s2NPL7XBsUk?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Ethan Hu</a> on <a href="https://unsplash.com/?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p>This article belongs to the <strong>JS Data Structures series</strong>, which contains these articles:</p><ul><li><a href="https://medium.com/p/e1bc57bda950">Arrays</a></li><li><a href="https://medium.com/p/7dcea711c091">Stacks</a></li><li><a href="https://medium.com/p/17f714057817"><strong>Queues</strong></a></li><li><em>Linked List (soon)</em></li><li><em>Sets (soon)</em></li><li><em>Dictionary and Hashes (soon)</em></li><li><em>Trees: Binary Search Tree (BST) (soon)</em></li><li><em>Trees: AVL Tree (soon)</em></li><li><em>Trees: Red-black Tree (soon)</em></li><li><em>Trees: Binary Heap / Heapsort (soon)</em></li><li><em>Graphs (soon)</em></li></ul><p>Queues are a collection of elements where is possible to add items only in the bottom, we have several practical examples of queues like the snake game, packages in data communication, aeroplanes waiting for landing instructions and many others.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/598/1*q-uE3Xboz_fqntxDALZakA.png" /><figcaption>A queue example</figcaption></figure><p>The order to get elements from a Queue is known as <strong>FIFO (Fist In, first out), </strong>the main idea is this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/773/0*XxsGmHVbohaHz6sq.png" /></figure><p>This article will cover the following content:</p><ul><li><strong>Basic structure</strong></li><li><strong>Queue methods</strong></li><li><strong>Instantiating your queue</strong></li><li><strong>Priority Queue</strong></li><li><strong>Time and space complexity</strong></li></ul><h3>Basic structure</h3><p>Let’s create a closure function that will allow us to output only the public Queues methods, avoiding changes in internal attributes like the item list:</p><pre>function Queue() {</pre><pre>  let items = [];</pre><pre>  class PublicQueue(){<br>        ...the queue methods will be here</pre><pre>  }</pre><pre>  return new PublicQueue();</pre><pre>};</pre><p>With this approach, the only public methods will be the methods included in PublicQueue class, if you want to know more about closures this article is really useful:</p><p><a href="https://medium.com/javascript-scene/master-the-javascript-interview-what-is-a-closure-b2f0d2152b36">Master the JavaScript Interview: What is a Closure?</a></p><p>If you decide to implement this Queue without using the Javascript native functions — <strong><em>for educational/training purposes</em></strong> — like push, pop and length, your basic structure will be:</p><pre>const Queue() {<br>  let first = null;<br>  let last = null;<br>  let size = 0;</pre><pre>  class Node {<br>    ...the node methods<br>  }</pre><pre>  class PublicQueue(){<br>      ...the stack methods will be here<br>  }</pre><pre>  return new PublicQueue();<br>};</pre><p>Without the native JS methods, you’ll need to create a Node to store your data sequentially, this node will contain the data itself and an attribute called previous that will refer to the node added before the current node.</p><pre>class Node(data){<br>  constructor(data){      <br>    this.data = data;<br>    this.previous = null;<br>  }<br>}</pre><p>Also, you’ll need to control manually the total of elements inside your queue, and controls the first and last element, they will help you to access faster the elements when you need.</p><h3><strong>Queue methods</strong></h3><p>After we created the basic structure we are ready to implement the required stack methods:</p><ul><li>size</li><li>isEmpty</li><li>enqueue</li><li>dequeue</li><li>peek</li><li>print</li></ul><h4>Size</h4><p>This method returns how many items there are inside a queue, using JS methods you could use the length to return this value:</p><pre>size(){<br>  return items.length;<br>}</pre><p>Without the JS native methods, you’ll need simply return the size variable:</p><pre>size(){<br>  return size;<br>}</pre><h4>isEmpty</h4><p>This method returns if the queue contains or not contains items inside, to implement this with JS native function you’ll use the size queue attribute is equal to zero:</p><pre>isEmpty(){<br>  return this.size() === 0;<br>}</pre><p>The implementation is the same when you aren’t using JS native methods.</p><h4>Enqueue</h4><p>This method allows us to add a new item as the last element of a queue, using the native JS methods this implementation is very simple:</p><pre>enqueue(data){<br>  items.push(data);<br>}</pre><p>Without the JS natives methods you need:</p><p>1. Create a new node.<br>2. Put the current node stored in the last variable as the next node of the new node.<br>3. If the first variable is null you need to put the new node inside it.<br>4. Increase the size variable.</p><pre>enqueue(<em>data</em>) {<br>  const utils = {<br>    nodeData: <strong>new</strong> <em>Node</em>(data),<br>    increase() {<br>      size++;<br>    },<br>  };</pre><pre>  if (last !== null) {<br>    last.next = utils.nodeData;<br>  }</pre><pre>  last = utils.nodeData;<br>  <br>  if (first == null) {<br>    first = utils.nodeData;<br>  }<br>  <br>  utils.increase();<br>}</pre><h4>Dequeue</h4><p>This method allows us to remove the first element of a queue, using the JS native methods the implementation is:</p><pre>dequeue() {<br>  items.shift();<br>}</pre><p>Without the JS native methods, you’ll need:</p><p>1. Store the top node in a temporary variable<br>2. Put the previous node as the new top node<br>3. Clear the last variable case the first variable is empty<br>4. Decrement the size variable<br>5. Return the old top node</p><pre>dequeue() {<br>  if (<em>this</em>.isEmpty()) throw <strong>new</strong> <em>Error</em>(&quot;The queue is empty&quot;);<br>  <br>  const utils = {<br>    previousFirst: <em>Object</em>.assign({}, first),<br>    decrease() {<br>      size--;<br>    },<br>  };</pre><pre>  first = first.next;<br>  <br>  if (first === null) {<br>    last = null;<br>  }</pre><pre>  utils.decrease();<br>  return utils.previousFirst.data;<br>}</pre><h4>Peek</h4><p>This method returns the first element of a queue, using JS native methods the implementation is:</p><pre>peek() {<br>  if (<em>this</em>.isEmpty()) throw new <em>Error</em>(&quot;The queue is empty&quot;);<br>  return items[0];<br>}</pre><p>Without JS native methods you simply return the first.data:</p><pre>peek(){<br>  if(this.isEmpty()) throw new Error(&#39;This queue is empty&#39;);</pre><pre>  return first.data;<br>}</pre><h4>Print</h4><p>This method allows us to output all elements inside an array, to do that using native JS methods we simply call toString():</p><pre>print() {<br>  if (<em>this</em>.isEmpty()) throw <strong>new</strong> <em>Error</em>(&quot;The queue is empty&quot;);<br>  return items.toString();<br>}</pre><p>Without JS native methods you’ll to need to create a recursive function to loop all your items, also you’ll need a function to add commas between the items.</p><pre>print() {<br>  if (<em>this</em>.isEmpty()) throw <strong>new</strong> <em>Error</em>(&quot;The queue is empty&quot;);</pre><pre>  const utils = {<br>    addComma(<em>data</em>) {<br>      return data !== &quot;&quot; ? &quot;, &quot; : &quot;&quot;;<br>    },<br>    getInnerItems(<em>node</em>) {<br>      if (node == null) {<br>        return &quot;&quot;;<br>      }</pre><pre>      const innerContent = utils.getInnerItems(node.next);<br>       return `${node.data}${utils.addComma(innerContent)}${innerContent}`;<br>    },<br>  };</pre><pre>  return utils.getInnerItems(first);<br>}</pre><h3>Instantiating your queue</h3><p>After declaring your queue, you could call it in this way:</p><pre>const myQueue = <strong>new</strong> <em>Queue</em>();</pre><p>To add items:</p><pre>myQueue.enqueue(&quot;first item&quot;);</pre><pre>myQueue.enqueue(&quot;second item&quot;);</pre><pre>myQueue.enqueue(&quot;third item&quot;);</pre><pre>myQueue.enqueue(&quot;fourth item&quot;);</pre><pre>myQueue.enqueue(&quot;fifth item&quot;);</pre><pre>myQueue.enqueue(&quot;sixth item&quot;);</pre><pre>myQueue.enqueue(&quot;seventh item&quot;);</pre><p>The idea is the same to call other methods.</p><h3>Priority Queue</h3><p>In a priority queue, you could redefine the order of getting items creating a list with special items that should be picked first, in a real-world example this could be useful to create lines in a hospital according to the patient condition, or lines to enter in a plane (first class, business class, economy class).</p><p>To create a priority queue you’ll need to define two different arrays to store your elements, a priority array and a common array, the result of this implementation will be:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fb307f6727a4f2d55cf818591db1b8cc/href">https://medium.com/media/fb307f6727a4f2d55cf818591db1b8cc/href</a></iframe><p>If you want to check out other <strong>Javascript Data Structures examples</strong> take a look in this GitHub repository:</p><p><a href="https://github.com/rxluz/js-data-structures">rxluz/js-data-structures</a></p><h3>Time and space complexity</h3><p><strong>Time complexity</strong> defines <strong>how faster</strong> is your algorithm, and <strong>space complexity </strong>defines how <strong>much memory your algorithm needs to run, </strong>this is also called <strong>Big-O notation.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SB5fLibxprTSNLx9We07ow.png" /><figcaption>From <a href="http://bigocheatsheet.com/">http://bigocheatsheet.com/</a></figcaption></figure><p>Let’s analyse the methods inside our queue to find out this:</p><ul><li><strong>size</strong>: We have <strong>O(1) to time and O(1) to space</strong>, once the time and memory that we need to run this operation remains the same regardless of the number of items inside our queue.</li><li><strong>isEmpty</strong>: Same thing here, <strong>O(1) to time and O(1) to space</strong>.</li><li><strong>enqueue</strong>: When we enqueue an item we do it at the end of the queue, it means that we don’t need to change the position of the other items, thus this operation run exactly at the same time regardless of the queue size, also we don’t need any recursive function here or store something that increases according to the queue size, it means that the memory that we need is always the same, so is <strong>O(1) to time and O(1) to space</strong>.</li><li><strong>dequeue</strong>: Dequeue complexity depends on which approach you used to implement it if you use the JS shift native method the time complexity will be <strong>O(n)</strong> once under the woods JS will need to move all other items to a new position, and space will be <strong>O(n)</strong>, if you create your own implementation using node the time complexity will be <strong>O(1)</strong> as well space complexity.</li><li><strong>peek</strong>: To peek an item you always will need the same time and space once you don’t need to analyse the full queue, so space/time complexity will be <strong>O(1)</strong>.</li><li><strong>print</strong>: You need to go through all items and join all them in a string to print, <strong>so the space complexity will be O(1)</strong> once you need more memory according to the queue size, and the <strong>time complexity is O(1)</strong> too, once this operation will take more time when the queue grows.</li></ul><p>If you want to know more about <strong>Big O Notation</strong> and how to calculate this I wrote this article that will help you:</p><p><a href="https://medium.com/front-end-weekly/big-o-in-js-the-basic-that-you-need-to-know-a5abb45570fa">#9 Big O in JS: The basic that you need to know</a></p><p>If you to want to know more about <strong>Javascript and Data Structures</strong> I recommend these books:</p><ul><li><strong>You Don’t Know JS Serie by Kyle Simpson (My favourite)</strong></li><li><strong>Eloquent JS by Marijn Haverbeke</strong></li><li><strong>Head First Javascript by Michael Morrison</strong></li><li><strong>Secrets of the JavaScript Ninja by Bear Bibeault and John Resig</strong></li><li><strong>Learning JavaScript Data Structures and Algorithms by Loiane Groner</strong></li></ul><p><strong><em>Thanks for reading! Feel free to hit the recommend button below if you found this piece helpful, also, </em>please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.</strong></p><p><a href="https://twitter.com/_rxluz">Ricardo Luz (@_rxluz) | Twitter</a></p><blockquote>If this post was helpful, please click the clap 👏 button below to show your support! ⬇⬇</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=17f714057817" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[#12 JS Data Structures: Stacks]]></title>
            <link>https://medium.com/@_rxluz/12-js-data-structures-stacks-7dcea711c091?source=rss-892e3096e4fa------2</link>
            <guid isPermaLink="false">https://medium.com/p/7dcea711c091</guid>
            <category><![CDATA[algorithms]]></category>
            <category><![CDATA[rxluz]]></category>
            <category><![CDATA[stack]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[data-structures]]></category>
            <dc:creator><![CDATA[Ricardo Luz]]></dc:creator>
            <pubDate>Fri, 29 Mar 2019 17:10:52 GMT</pubDate>
            <atom:updated>2019-04-30T07:24:38.032Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7eyxFLTlKFlJREIQGGYmfQ.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/photos/i6IP8o3ZeXA?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Bailey Hall</a> on <a href="https://unsplash.com/?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p>This article belongs to the <strong>JS Data Structures series</strong>, which contains these articles:</p><ul><li><a href="https://medium.com/p/e1bc57bda950">Arrays</a></li><li><a href="https://medium.com/p/7dcea711c091"><strong>Stacks</strong></a></li><li><a href="https://medium.com/p/17f714057817">Queues</a></li><li>Linked List <em>(soon)</em></li><li>Sets <em>(soon)</em></li><li>Dictionaries/maps <em>(soon)</em></li><li>Hashes tables <em>(soon)</em></li><li>Trees: Binary Search Tree (BST) <em>(soon)</em></li><li>Trees: AVL Tree <em>(soon)</em></li><li>Trees: Red-black Tree <em>(soon)</em></li><li>Trees: Binary Heap / Heapsort <em>(soon)</em></li><li>Graphs <em>(soon)</em></li></ul><p>Stacks are a collection of elements where is possible to add items only in the top, we have several practical examples of stacks like the browser history, undo operations, recursion and many others.</p><p>The order to get elements from a Stack is known as <strong>LIFO (Last in, first out), </strong>the main idea is this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/350/0*J6t6UM9bMuUwLAjf.png" /></figure><p>This article will cover the following content:</p><ul><li><a href="#6559"><strong>Basic structure</strong></a></li><li><a href="#ec84"><strong>Stack methods</strong></a></li><li><a href="#0263"><strong>Stacks algorithms examples</strong></a><strong><br>- </strong><a href="#224c"><strong>Decimal to binary</strong></a><strong><br>- </strong><a href="#d8e6"><strong>Reverse a string using a stack</strong></a><strong><br>- </strong><a href="#b0aa"><strong>Next Greater Element</strong></a></li><li><a href="#d77f"><strong>Time and space complexity</strong></a></li></ul><h3>Basic structure</h3><p>Let’s create a closure function that will allow us to output only the public Stacks methods and prevents changes in internal attributes like the item list:</p><pre>function Stack(){</pre><pre>    let items = []</pre><pre>    class PublicStack(){<br>      ...the stack methods will be here</pre><pre>    }</pre><pre>    return new PublicStack()</pre><pre>}</pre><p>With this approach, the only public methods will be the methods included in PublicStack class, if you want to know more about closures this article is really useful:</p><p><a href="https://medium.com/javascript-scene/master-the-javascript-interview-what-is-a-closure-b2f0d2152b36">Master the JavaScript Interview: What is a Closure?</a></p><p>If you decide to implement this Stack without using the Javascript native functions — <strong><em>for educational/training purposes</em></strong> — like push, pop and length, your basic structure will be:</p><pre>function Stack(){ <br>  let top = null<br>  let size = 0</pre><pre>  class Node {<br>    ...the node methods<br>  }</pre><pre>  class PublicStack {<br>      ...the stack methods will be here</pre><pre>  }</pre><pre>  return new PublicStack()<br>};</pre><p>Without the native JS methods, you’ll need to create a Node to store your data sequentially, this node will contain the data itself and an attribute called previous that will refer to the node added before the current node.</p><pre>class Node {<br>  constructor(data){      <br>    this.data = data<br>    this.previous = null<br>  }<br>}</pre><h3>Stack methods</h3><p>After we created the basic structure we are ready to implement the required stack methods:</p><ul><li>size</li><li>isEmpty</li><li>push</li><li>pop</li><li>peek</li><li>clear</li></ul><h4>Size</h4><p>This method returns how many items there are inside a stack, using JS methods you could use the length to return this value:</p><pre>size(){<br>  return items.length<br>}</pre><p>Without the JS native methods, you’ll need simply return the size variable:</p><pre>size(){<br>  return size<br>}</pre><h4>isEmpty</h4><p>This method returns if the stack contains or not contains items inside, to implement this with JS native function you’ll use the size stack attribute is equal to zero:</p><pre>isEmpty(){<br>  return this.size() === 0<br>}</pre><p>The implementation is the same when you aren’t using JS native methods.</p><h4>Push</h4><p>This method allows us to add a new item in the top of a stack, using the native JS methods this implementation is very simple</p><pre>push(data){<br>  items.push(data)<br>}</pre><p>Without the JS natives methods you need:</p><p>1. Create a new node<br>2. Put the current node stored in the top variable as the next node of the new node<br>3. Increment the size variable</p><pre>push(data){<br>   const node = new Node(data)<br>   node.previous = top<br>   top = node</pre><pre>   size++<br>}</pre><h4>Pop</h4><p>This method allows us to remove the element in the top of a stack, using the JS native methods the implementation is:</p><pre>pop(){<br>  if(this.isEmpty()) throw new Error(&#39;This stack is empty&#39;)</pre><pre>  const lastItemIndex = items.length - 1<br>  const currentLastItem = items[lastItemIndex]</pre><pre>  items.pop()</pre><pre>  return currentLastItem</pre><pre>}</pre><p>Without the JS native methods, you’ll need:</p><p>1. Store the top node in a temporary variable<br>2. Put the previous node as the new top node<br>3. Decrement the size variable<br>4. return the old top node;</p><pre>pop() {<br>  if(this.isEmpty()) throw new Error(&#39;This stack is empty&#39;)</pre><pre>  const tempTop = Object.assign({}, top)<br>  const nextElement = tempTop.previous<br>  top = nextElement<br>  size--</pre><pre>  return tempTop.data</pre><pre>}</pre><h4>Peek</h4><p>This method returns the element in the top of the stack, using JS native methods the implementation is:</p><pre>peek(){<br>  if(this.isEmpty()) throw new Error(&#39;This stack is empty&#39;)</pre><pre>  const lastItemIndex = items.length - 1<br>  return items[lastItemIndex]</pre><pre>}</pre><p>Without JS native methods you simply return the top.data:</p><pre>peek(){<br>  if(this.isEmpty()) throw new Error(&#39;This stack is empty&#39;)</pre><pre>  return top.data<br>}</pre><h4>Clear</h4><p>This method allows us to delete all data inside a stack, to do that using the JS native functions you need to redefine the items array to [].</p><pre>clear(){<br>  items = []<br>}</pre><p>Without JS native methods you’ll need to redefine the top var as null and the size to 0.</p><pre>clear(){<br>  top = null<br>  size = 0<br>}</pre><h3>Putting all together</h3><p>If you decide to use the JS native method this will be your final stack implementation:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4158631c846bc645658dc6798e21f6f5/href">https://medium.com/media/4158631c846bc645658dc6798e21f6f5/href</a></iframe><p>Using the nodes approach without JS native functions this will be the result:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ca8242a0a8574f0d68964a4f8a97e6a8/href">https://medium.com/media/ca8242a0a8574f0d68964a4f8a97e6a8/href</a></iframe><p>If you want to check out other <strong>Javascript Data Structures examples</strong> take a look in this GitHub repository:</p><p><a href="https://github.com/rxluz/js-data-structures">rxluz/js-data-structures</a></p><h3>Stacks algorithms applications</h3><h4>Decimal to binary</h4><p>A binary number is represented by 0 and 1, when we want to transform a number to binary data we need to divide this number by 2 until the result will be zero, to each division we store the remainder in a stack</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/377/0*s494NSyKr8hTdDsX.png" /><figcaption>From <a href="https://www.geeksforgeeks.org/program-decimal-binary-conversion/">https://www.geeksforgeeks.org/program-decimal-binary-conversion/</a></figcaption></figure><p>In the end, we get all the remainders stored in our stack and create a string with these values, this could be reached using this algorithm:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0b882fb79fabf9f02251b126b89f6fd4/href">https://medium.com/media/0b882fb79fabf9f02251b126b89f6fd4/href</a></iframe><h4>Reverse a string using a stack</h4><p>The approach to solving this problem is:</p><ol><li>Add all letters from a string in a stack</li><li>Extract the letters from the top of a stack and add them in a new string</li></ol><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/de68361416686863df3f0ced6ad8a41c/href">https://medium.com/media/de68361416686863df3f0ced6ad8a41c/href</a></iframe><p><strong>Note</strong>: This algorithm is only to study purposes, the same result could be archived with some lines of code using a simple array:</p><pre>const reverseString = currentString =&gt; <br>  currentString<br>   .split(&#39;&#39;)<br>   .reverse()<br>   .join(&#39;&#39;);</pre><h4>Next Greater Element</h4><p>The idea is to return the next element greater after this element in a list than the given element to check, for example:</p><pre>const numbers = [10, 2, 3, 4, 5, 50, 100]</pre><pre>nextGreaterElement(numbers, 10); //will return 50<br>nextGreaterElement(numbers, 5); //will return 50<br>nextGreaterElement(numbers, 3); // will return 4</pre><p>The approach to solving this problem is:</p><ol><li>Add all items that are in the right of the checked element in a stack</li><li>Remove elements from this stack until found the closer element greater than the checked element</li></ol><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1beef4651a6cb09fc36ddb56ad4833f8/href">https://medium.com/media/1beef4651a6cb09fc36ddb56ad4833f8/href</a></iframe><h3>Time and space complexity</h3><p><strong>Time complexity</strong> defines <strong>how faster</strong> is your algorithm, and <strong>space complexity </strong>defines how <strong>much memory your algorithm needs to run, </strong>this is also called <strong>Big-O notation.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SB5fLibxprTSNLx9We07ow.png" /><figcaption>From <a href="http://bigocheatsheet.com/">http://bigocheatsheet.com/</a></figcaption></figure><p>Let’s analyse the methods inside our stack to find out this:</p><ul><li><strong>size</strong>: We have <strong>O(1) to time and O(1) to space</strong>, once the time and memory that we need to run this operation remains the same regardless of the number of items inside our queue.</li><li><strong>isEmpty</strong>: Same thing here, <strong>O(1) to time and O(1) to space</strong>.</li><li><strong>push</strong>: When we push an item we do it at the top of the queue, it means that we don’t need to change the position of the other items, thus this operation run exactly at the same time regardless of the stack size, also we don’t need any recursive function here or store something that increases according to the size of stack, it means that the memory that we need is always the same, so is <strong>O(1) to time and O(1) to space</strong>.</li><li><strong>pop</strong>: Pop time complexity will be the same using JS native methods or creating your own implementation using nodes, once you don’t need to move the position of other elements the complexity and space will be always the same regardless of the size, thus <strong>O(1) to time and O(1) to space</strong>.</li><li><strong>peek</strong>: To peek an item you always will need the same time and space once you don’t need to analyse the full queue, so <strong>space/time complexity will be O(1)</strong>.</li><li><strong>clear</strong>: You need to go through all items and join all them in a string to print, <strong>so space and time complexity will be O(1)</strong> once you need more memory and time according to the stack size.</li></ul><p>If you want to know more about <strong>Big O Notation</strong> and how to calculate this I wrote this article that will help you:</p><p><a href="https://medium.com/front-end-weekly/big-o-in-js-the-basic-that-you-need-to-know-a5abb45570fa">#9 Big O in JS: The basic that you need to know</a></p><p>If you to want to know more about <strong>Javascript and Data Structures</strong> I recommend these books:</p><ul><li><strong>You Don’t Know JS Serie by Kyle Simpson (My favourite)</strong></li><li><strong>Eloquent JS by Marijn Haverbeke</strong></li><li><strong>Head First Javascript by Michael Morrison</strong></li><li><strong>Secrets of the JavaScript Ninja by Bear Bibeault and John Resig</strong></li><li><strong>Learning JavaScript Data Structures and Algorithms by Loiane Groner</strong></li></ul><p><strong><em>Thanks for reading! Feel free to hit the recommend button below if you found this piece helpful, also, </em>please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.</strong></p><p><a href="https://twitter.com/_rxluz">Ricardo Luz (@_rxluz) | Twitter</a></p><blockquote>If this post was helpful, please click the clap 👏 button below to show your support! ⬇⬇</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7dcea711c091" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[#11 JS Data Structures: Arrays]]></title>
            <link>https://medium.com/@_rxluz/11-js-data-structures-arrays-e1bc57bda950?source=rss-892e3096e4fa------2</link>
            <guid isPermaLink="false">https://medium.com/p/e1bc57bda950</guid>
            <category><![CDATA[rxluz]]></category>
            <category><![CDATA[arrays]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[data-structures]]></category>
            <category><![CDATA[tutorial]]></category>
            <dc:creator><![CDATA[Ricardo Luz]]></dc:creator>
            <pubDate>Wed, 13 Mar 2019 07:58:23 GMT</pubDate>
            <atom:updated>2019-04-30T07:25:02.829Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hEjY9ssG3bEA-NnSE94bLw.png" /></figure><p>This article belongs to the <strong>JS Data Structures series</strong>, which will contain these articles:</p><ul><li><a href="https://medium.com/p/e1bc57bda950"><strong>Arrays</strong></a></li><li><a href="https://medium.com/@_rxluz/12-js-data-structures-stacks-7dcea711c091">Stacks</a></li><li><a href="https://medium.com/p/17f714057817">Queues</a></li><li>Linked List <em>(soon)</em></li><li>Sets <em>(soon)</em></li><li>Dictionaries/maps <em>(soon)</em></li><li>Hashes tables <em>(soon)</em></li><li>Trees: Binary Search Tree (BST) <em>(soon)</em></li><li>Trees: AVL Tree <em>(soon)</em></li><li>Trees: Red-black Tree <em>(soon)</em></li><li>Trees: Binary Heap / Heapsort <em>(soon)</em></li><li>Graphs <em>(soon)</em></li></ul><p>Like any other programming language, JS supports arrays, arrays are the most simple data structure and help us to store data sequentially, let’s suppose that we want to store the animals in a zoo, without an array we could do in this way:</p><pre>const animal1 = &#39;elephant&#39;;<br>const animal2 = &#39;monkey&#39;;<br>const animal3 = &#39;snake&#39;;<br>const animal4 = &#39;lion&#39;;</pre><p>The problem is we need to create a variable for each animal, if the zoo has 1000 animals we need 1000 variables, manage this is hard and depending on the situation is impossible, imagine create a list of thousand people living in your city using variables.</p><p>To solve situations like this we could use an array, the same example above could be done in this way:</p><pre>const animals = [&#39;elephant&#39;, &#39;monkey&#39;, &#39;snake&#39;, &#39;lion&#39;];</pre><p>Simple right? Arrays give us extra powers to handle with more complex data sets!</p><h3>Creating an array</h3><p>There are many ways to create an array, we could do it using the new operator:</p><pre>const myArray = new Array();</pre><p>Is also possible to define the numbers of items in this way:</p><pre>const myArray = new Array(9);</pre><p>This is especially useful when you need to execute an operation with a fixed number of times, let’s say we want to print ‘hello’ 10 times, we could do it:</p><pre>[...Array(10)].forEach(emptyItem =&gt; console.log(&#39;Hello&#39;));</pre><p>But the most common way to create an array is simply using [] instead of using New and Array words, like this:</p><pre>const myArray = [];</pre><h4>Multi-dimensional arrays</h4><p>Arrays allow us to create arrays inside arrays that generate 3D, 4D or xD arrays, let’s say that we store the results of a soccer game championship, we could do in this way:</p><pre>const soccerChampionshipResults = [[3, 2], [0, 0], [1, 0], [4, 1]]</pre><p>In this example, we build a 3D array, and we could access each result in the same way that we did before <strong>soccerChampionshipResults[0]</strong> will return <strong>[3, 2]</strong>, <strong>soccerChampionshipResults[1]</strong> will return <strong>[0, 0]</strong> and so on.</p><h3><strong>Accessing the elements of an array</strong></h3><p>You could access an element inside an array point the cursor directly to the desired element like this:</p><pre>const animals = [&#39;elephant&#39;, &#39;monkey&#39;, &#39;snake&#39;, &#39;lion&#39;];</pre><pre>console.log(animals[2])</pre><p>In this example you’ll get the third element (snake) of your array, the reason is <strong>the array pointer starts in 0</strong>.</p><pre>const animals = [<br>  &#39;elephant&#39;, // element number 0<br>  &#39;monkey&#39;, // element number 1<br>  &#39;snake&#39;,  // element number 2<br>  &#39;lion&#39; // element number 3<br>];<br></pre><p>If you need to know how many items the array has, you could use the <strong>length attribute</strong>:</p><pre>const animals = [&#39;elephant&#39;, &#39;monkey&#39;, &#39;snake&#39;, &#39;lion&#39;];</pre><pre>console.log(<strong>animals.length</strong>) // will return 4</pre><p>Another method to access the elements inside an array is using <strong>forEach method</strong>:</p><pre>const animals = [&#39;elephant&#39;, &#39;monkey&#39;, &#39;snake&#39;, &#39;lion&#39;];</pre><pre>animals.<strong>forEach</strong>(animal =&gt; console.log(`Hello I am a ${animal}`));</pre><pre>/* will output</pre><pre>Hello I am a elephant<br>Hello I am a monkey<br>Hello I am a snake<br>Hello I am a lion<br>*/</pre><p>You also could use<strong> map, reduce, filter, for..in, for..of </strong>depending that you want to do, if you want more about these methods I wrote some articles about this:</p><ul><li><a href="https://medium.com/@_rxluz/2-functional-approach-reduce-c882c68c4cdf">#2 Functional approach: Reduce</a></li><li><a href="https://medium.com/@_rxluz/10-js-basics-the-different-loops-and-examples-cd871895d2aa">#10 JS Basics: The different loops and examples</a></li></ul><h3><strong>Creating new items inside an array</strong></h3><p>There are many different ways to add an item depending on which position you want to add this item, some examples are:</p><h4>Adding an item at the beginning of an array</h4><p>To add an item at the beginning of array you need to move the other items to a new position, you could do it in this way:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/64f5ae9afe49697ebb5d983e01eac3f8/href">https://medium.com/media/64f5ae9afe49697ebb5d983e01eac3f8/href</a></iframe><p>But the simplest way to do that is using the <strong>unshift</strong> function:</p><pre>const animals = [&quot;elephant&quot;, &quot;monkey&quot;, &quot;snake&quot;, &quot;lion&quot;];<br><strong>animals.unshift(&#39;macaw&#39;);</strong></pre><pre><em>console</em>.log(animals); // will return [ &#39;macaw&#39;, &#39;elephant&#39;, &#39;monkey&#39;, &#39;snake&#39;, &#39;lion&#39; ]</pre><h4>Adding an item at the end of an array</h4><p>This is simpler than adding in the middle or in the begging, you could use the array.length to do that:</p><pre>const animals = [&quot;elephant&quot;, &quot;monkey&quot;, &quot;snake&quot;, &quot;lion&quot;];<br><strong>animals[animals.length] = &#39;macaw&#39;;</strong></pre><pre><em>console</em>.log(animals); // will return [ &#39;elephant&#39;, &#39;monkey&#39;, &#39;snake&#39;, &#39;lion&#39;, &#39;macaw&#39; ]</pre><p>The <strong>array.length</strong> attribute always returns the number of items inside an array, you also could use the <strong>push method</strong> to add items in the end, like this:</p><pre>const animals = [&quot;elephant&quot;, &quot;monkey&quot;, &quot;snake&quot;, &quot;lion&quot;];<br><strong>animals.push(&#39;macaw&#39;);</strong></pre><pre><em>console</em>.log(animals); // will return [ &#39;elephant&#39;, &#39;monkey&#39;, &#39;snake&#39;, &#39;lion&#39;, &#39;macaw&#39; ]</pre><h4>Adding items in the middle (or in any position) of an array</h4><p>The process to add in the middle is almost the same of adding the beginning, the difference is you’ll only move the items after the desired position:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2fc5cf087439a78d03e953a65323c0be/href">https://medium.com/media/2fc5cf087439a78d03e953a65323c0be/href</a></iframe><p>You also could use the native method <strong>splice</strong> to do the same in a most simple way:</p><pre>const animals = [&quot;elephant&quot;, &quot;monkey&quot;, &quot;snake&quot;, &quot;lion&quot;];<br><strong>animals.splice(2, 0, &#39;macaw&#39;);</strong></pre><pre><em>console</em>.log(animals); // will return [ &#39;elephant&#39;, &#39;monkey&#39;, &#39;snake&#39;, &#39;lion&#39;, &#39;macaw&#39; ]</pre><p>Where 2 is the position that you want to add and 0 is the total items that you want to remove after this position.</p><h3>Removing items from an array</h3><p>The methods to remove an item varies according to the position you want to remove an item.</p><h4>Removing an item from beginning</h4><p>To remove from the beginning you need to overwrite the first item with the second, the second with third and so on, after this we need to redefine the array length to ignore the last item:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/518b81cedec7e797e99f2535c0fa82f0/href">https://medium.com/media/518b81cedec7e797e99f2535c0fa82f0/href</a></iframe><p>Is better we use the approach of redefining the length than use delete, once <strong>delete will keep the last item without any value</strong>, like this:</p><pre>const animals = [&quot;elephant&quot;, &quot;monkey&quot;, &quot;snake&quot;, &quot;lion&quot;];<br>delete animals[3];</pre><pre><em>console</em>.log(animals); // will return [ &#39;elephant&#39;, &#39;monkey&#39;, &#39;snake&#39;, &lt;1 empty item&gt; ]</pre><pre><em>console</em>.log(animals.length); // will return 4</pre><p>You also could use the native method <strong>shift</strong> to do the item remotion in a most simple way:</p><pre>const animals = [&quot;elephant&quot;, &quot;monkey&quot;, &quot;snake&quot;, &quot;lion&quot;];<br>animals.shift();</pre><pre><em>console</em>.log(animals); // will return [ &#39;monkey&#39;, &#39;snake&#39;, &#39;lion&#39; ]</pre><h4><strong>Removing an item from the middle (or any position) from an array</strong></h4><p>To remove from middle you need to move back all items after the position of the item that you want to remove, like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c1f5ab143a52a001eef3eaed7cd77f33/href">https://medium.com/media/c1f5ab143a52a001eef3eaed7cd77f33/href</a></iframe><p>You also could use the method splice without a third parameter to remove the item that you want to:</p><pre>const animals = [&quot;elephant&quot;, &quot;monkey&quot;, &quot;snake&quot;, &quot;lion&quot;];</pre><pre>animals.splice(2, 1); <br>console.log(animals); // will return [&quot;elephant&quot;, &quot;monkey&quot;, &quot;lion&quot;]</pre><p>Where 2 is the position of the item and 1 is the number of items that you want to remove.</p><h4><strong>Removing an item from the end of an array</strong></h4><p>Is very simple to remove an item from the end, you’ll need simply <strong>redefine the length to length -1</strong>:</p><pre>const animals = [&quot;elephant&quot;, &quot;monkey&quot;, &quot;snake&quot;, &quot;lion&quot;];</pre><pre><strong>animals.length = animals.length - 1;</strong></pre><pre>console.log(animals); // will return [&quot;elephant&quot;, &quot;monkey&quot;, &quot;snake&quot;]</pre><p>You also could remove more than one item from the end defining length to length -x where x is the number of items that you want to remove.</p><pre><strong>animals.length = animals.length - 2;</strong></pre><pre>console.log(animals); // will return [&quot;elephant&quot;, &quot;monkey&quot;]</pre><h3>Sorting an array</h3><h4>Default sorting</h4><p>The most simple sorting method to organize the items in <a href="https://unicode-table.com/en/#control-character">Unicode order</a> is using the sort method:</p><pre>const animals = [&quot;elephant&quot;, &quot;monkey&quot;, &quot;snake&quot;, &quot;lion&quot;];<br><strong>animals.sort();</strong></pre><pre><em>console</em>.log(animals); // will return [ &#39;elephant&#39;, &#39;lion&#39;, &#39;monkey&#39;, &#39;snake&#39; ]</pre><p>This method runs an in-<a href="https://en.wikipedia.org/wiki/In-place_algorithm">place</a> sort which means that this won’t generate a new array, instead of that it will replace the current array order.</p><p><strong>Be careful when you have items with the lower and upper case inside your array once the upper case characters come first in Unicode Table, so an item like Zebra will be put before an item called alligator for example</strong>.</p><pre>const animals = [&quot;elephant&quot;, &quot;monkey&quot;, &quot;Zebra&quot;, &quot;snake&quot;, &quot;lion&quot;];<br>animals.sort();</pre><pre><em>console</em>.log(animals); <strong>// will return [ &#39;Zebra&#39;, &#39;elephant&#39;, &#39;lion&#39;, &#39;monkey&#39;, &#39;snake&#39; ]</strong></pre><h4>Custom Sorting</h4><p>The sort method allows you to create your custom sorting algorithms, let’s say that you have an array with population list and you want to order this from the smallest to biggest population, you could do that:</p><pre>const populationList = [10000000, 1000000, 500000, 600000];<br><strong>populationList.sort((<em>a</em>, <em>b</em>) =&gt; a - b);</strong></pre><pre><em>console</em>.log(populationList); <br>// will return: [ 500000, 600000, 1000000, 10000000 ]</pre><h4><strong>Reverse sorting</strong></h4><p>Is possible invert the items of an array using the algorithm below:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/cd1f52c37fa227172e39909427989a27/href">https://medium.com/media/cd1f52c37fa227172e39909427989a27/href</a></iframe><p>The idea is to go through the array till the middle, replacing each item to an item in the other side of the array, for example, replace the first by the last and the last by the first, the second by the last but one and so on.</p><p>Also, you could use the native method <strong>reverse()</strong> to do the same thing:</p><pre>const animals = [&quot;elephant&quot;, &quot;monkey&quot;, &quot;snake&quot;, &quot;lion&quot;, &quot;zebra&quot;];</pre><pre><strong>animals.reverse();</strong></pre><pre><em>console</em>.log(animals); <br>// will return [ &#39;zebra&#39;, &#39;lion&#39;, &#39;snake&#39;, &#39;monkey&#39;, &#39;elephant&#39; ]</pre><p>The only difference is the reverse method run inside the current array, while the first approach generates a new reversed array.</p><h3>Searching an array</h3><h4>Method indexOf</h4><p>There are many ways to search an array in Javascript, let’s start with indexOf:</p><pre>const animals = [&quot;elephant&quot;, &quot;monkey&quot;, &quot;snake&quot;, &quot;lion&quot;];</pre><pre>const haveMonkeyInList = <strong>animals.indexOf(&quot;monkey&quot;) &gt; -1</strong>;<br>const positionWhereMonkeyWasFound = <strong>animals.indexOf(&quot;monkey&quot;);</strong></pre><pre><em>console</em>.log({ haveMonkeyInList, positionWhereMonkeyWasFound });<br>// will output: { haveMonkeyInList: true, positionWhereMonkeyWasFound: 1 }</pre><p>When <strong>indexOf</strong> founds the searched element it returns the position where this element was found when <strong>indexOf</strong> doesn’t found the search element, it returns -1.</p><h4>Method filter</h4><p>The main idea of the <strong>filter method</strong> is to create a new array following some given condition but is also possible to use this to return a new array with searched items:</p><pre>const animals = [&quot;elephant&quot;, &quot;monkey&quot;, &quot;snake&quot;, &quot;lion&quot;];</pre><pre><strong>const animalsWithLetterE = <br>  animals.filter(<br>   <em>animal</em> =&gt;<br>    animal.indexOf(&quot;e&quot;) &gt; -1<br>  );</strong></pre><pre><em>console</em>.log(animalsWithLetterE);</pre><pre>// will output: [ &#39;elephant&#39;, &#39;monkey&#39;, &#39;snake&#39; ]</pre><p>In the example above we mixed the <strong>indexOf</strong> with <strong>filter method</strong>, but in this case, we are using <strong>indexOf</strong> to search a substring inside a string.</p><h4><strong>Method Includes</strong></h4><p>The ES7 spec brought to us the <strong>includes method</strong> that reduces this:</p><pre>const haveMonkeyInList = animals.indexOf(&#39;monkey&#39;) &gt; -1</pre><p>To this:</p><pre>const haveMonkeyInList = animals.includes(&#39;monkey&#39;)</pre><p>Also, is possible to send an additional parameter defining from what position do you want to start the search:</p><pre>const animals = [&quot;elephant&quot;, &quot;snake&quot;, &quot;monkey&quot;, &quot;lion&quot;];</pre><pre><em>console</em>.log(animals.includes(&#39;monkey&#39;, 1));<br>// will return true because exists an element called &#39;monkey&#39; from  the item with index 1</pre><pre><em>console</em>.log(animals.includes(&#39;elephant&#39;, 1));<br>// will return false because doesn&#39;t exists an element called &#39;elephant&#39; from the item with index 1</pre><h3>Other arrays methods</h3><h4>toString()</h4><p>Allows output the array content in string format:</p><pre>const animals = [&quot;elephant&quot;, &quot;snake&quot;, &quot;monkey&quot;, &quot;lion&quot;];<br><strong>console.log(animals.toString());</strong><br>// will output: &quot;elephant,snake,monkey,lion&quot;</pre><h4>join()</h4><p>Like toString method allows us to output the array content in string format, but is possible define a different delimiter than a comma:</p><pre>const animals = [&quot;elephant&quot;, &quot;snake&quot;, &quot;monkey&quot;, &quot;lion&quot;];<br><strong>console.log(animals.join(&#39;-&#39;));</strong><br>// will output: &quot;elephant-snake-monkey-lion&quot;</pre><h4><strong>fill()</strong></h4><p>Allows replace the content of strings in an array with a new content</p><pre>const animals = [&quot;elephant&quot;, &quot;snake&quot;, &quot;monkey&quot;, &quot;lion&quot;];<br><strong>console.log(animals.fill(&#39;animals&#39;));</strong><br>// will output: [&quot;animals&quot;, &quot;animals&quot;, &quot;animals&quot;, &quot;animals&quot;]</pre><p>Also is possible to define the start index and the final index of items that will be filled</p><pre>const animals = [&quot;elephant&quot;, &quot;snake&quot;, &quot;monkey&quot;, &quot;lion&quot;];<br><strong>console.log(animals.fill(&#39;animals&#39;, 2, 3));</strong><br>// will output: [&quot;elephant&quot;, &quot;snake&quot;, &quot;animals&quot;, &quot;lion&quot;]</pre><h4>from()</h4><p>Allows create a new array using an old one:</p><pre>const animals = [&quot;elephant&quot;, &quot;snake&quot;, &quot;monkey&quot;, &quot;lion&quot;];<br><strong>const animalsCopy = Array.from(animals);</strong></pre><pre>animals[0] = &#39;zebra&#39;;</pre><pre>console.log(animalsCopy);<br>// will output: [&quot;elephant&quot;, &quot;snake&quot;, &quot;monkey&quot;, &quot;lion&quot;]</pre><p>If you to want to know more about <strong>Javascript and Data Structures</strong> I recommend these books:</p><ul><li><strong>You Don’t Know JS Serie by Kyle Simpson (My favourite)</strong></li><li><strong>Eloquent JS by Marijn Haverbeke</strong></li><li><strong>Head First Javascript by Michael Morrison</strong></li><li><strong>Secrets of the JavaScript Ninja by Bear Bibeault and John Resig</strong></li><li><strong>Learning JavaScript Data Structures and Algorithms by Loiane Groner</strong></li></ul><p>If you are a Portuguese speaker check out my Youtube videos about <strong>Data Structures in Javascript</strong>:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2Fvideoseries%3Flist%3DPLMUwPz4ef-OxZKod3obJzefm44ZqtIDL1&amp;url=https%3A%2F%2Fwww.youtube.com%2Fplaylist%3Flist%3DPLMUwPz4ef-OxZKod3obJzefm44ZqtIDL1%26disable_polymer%3Dtrue&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2Fkx650uMAhuw%2Fhqdefault.jpg%3Fsqp%3D-oaymwEWCKgBEF5IWvKriqkDCQgBFQAAiEIYAQ%3D%3D%26rs%3DAOn4CLDhCNISPbomvIyh0f69q37r6vPG6A&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="853" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/feaf0bd1afd5329347b5db12bfca7b58/href">https://medium.com/media/feaf0bd1afd5329347b5db12bfca7b58/href</a></iframe><p><strong><em>Thanks for reading! Feel free to hit the recommend button below if you found this piece helpful, also, </em>please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.</strong></p><p><a href="https://twitter.com/_rxluz">Ricardo Luz (@_rxluz) | Twitter</a></p><blockquote>If this post was helpful, please click the clap 👏 button below to show your support! ⬇⬇</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e1bc57bda950" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[#10 JS Basics: The different loops and examples]]></title>
            <link>https://medium.com/@_rxluz/10-js-basics-the-different-loops-and-examples-cd871895d2aa?source=rss-892e3096e4fa------2</link>
            <guid isPermaLink="false">https://medium.com/p/cd871895d2aa</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[loop]]></category>
            <category><![CDATA[code]]></category>
            <category><![CDATA[tips]]></category>
            <dc:creator><![CDATA[Ricardo Luz]]></dc:creator>
            <pubDate>Wed, 15 Aug 2018 08:29:24 GMT</pubDate>
            <atom:updated>2019-01-28T08:47:39.878Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fbsaopoUhrJZZGKMGGCNog.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/photos/LDTPjSlWeNY?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Travis Yewell</a> on <a href="https://unsplash.com/search/photos/loop?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p>Javascript language has different ways to get items from an array, some of them are faster and others more elegant, in this article, we will analyse them and compare with different examples and applications.</p><h3>1. THE CLASSIC: FOR</h3><p>This method is the classic for loops items inside arrays, also the fastest, its syntax is very famous, and probably you already know:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4f8c75c2b4f135c7835b9b19f2e6ceb6/href">https://medium.com/media/4f8c75c2b4f135c7835b9b19f2e6ceb6/href</a></iframe><p>In possible using FOR structure with more than one variable and increment, some developers don’t know all things that are possible with FOR, most people only know this:</p><pre>for(let index = 0; index &lt; 10; index++){<br>   ...some code here<br>}</pre><p>However is possible to create as well as to increment more than one variable when you create the FOR loop, like this example:</p><pre>for(<br>  let index = 0, myVar = &#39;&#39;; <strong><em>// you could define more than one initial variable, separing with comma</em></strong><br>  index &lt; 10; <br>  index++,myVar=index*2 <strong><em>// you could increment more than one variable, separing them with comma</em></strong><br>){<br>  console.log(index, myVar);<br>}</pre><pre><em>/* will output:<br>  0, &quot;&quot;<br>  1, 2<br>  2, 4<br>  3, 6<br>  4, 8<br>  5, 10<br>  6, 12<br>  7, 14<br>  8, 16<br>  9, 18<br> 10, 20<br>*/</em></pre><h3>2. FOR … IN</h3><p>This method remembers the classic for, but you don’t need to increment your x, take a look in the example below:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/87fc3c67037a824f2faeda1baffd9c37/href">https://medium.com/media/87fc3c67037a824f2faeda1baffd9c37/href</a></iframe><p>I don’t like because other alternatives could reduce the code amount comparing with this.</p><h3>3. FOR … OF</h3><p>This method gets the elements in an array without needs increment, and your code is smaller when you use this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4f8c75c2b4f135c7835b9b19f2e6ceb6/href">https://medium.com/media/4f8c75c2b4f135c7835b9b19f2e6ceb6/href</a></iframe><h3>4. forEach</h3><p>This loop is the best for when you don’t need to create a new array and get the values in the current array because it reduces your code to this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/afaa4384de6213bdcc882f31ec5e654c/href">https://medium.com/media/afaa4384de6213bdcc882f31ec5e654c/href</a></iframe><p>Cool right? Now with only one single line, you have everything that you need!</p><h3>5. MAP</h3><p>We use the map when we need to create a mutated copy from the original array.</p><p>Let’s suppose that you have a collection with name, age, and gender and you want to create a new array only with gender, map will be useful in this case or you when you want to create a new array with some new field, or when you need to normalize your database, take a look at these examples:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/333698924e160dd3eb52ad4d31cca7c7/href">https://medium.com/media/333698924e160dd3eb52ad4d31cca7c7/href</a></iframe><p>If you don’t know how destructuring works, take a look at this article:</p><p><a href="https://medium.com/@_rxluz/8-functional-approach-destructuring-b39dcbb40683">#8 Functional Approach: Destructuring</a></p><p>Now, let’s create a new array with all the current fields and one more called isAdult, take a look:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a7c90b912f44903154d1123158786084/href">https://medium.com/media/a7c90b912f44903154d1123158786084/href</a></iframe><p>Or you could remove sensitive data like passwords, there a lot of applications to map method!</p><h3>6. REDUCE</h3><p>Reduce is an excellent method that is possible to do all the things that you do with for, for..in, for..of, forEach or map! Also, you could create an entirely different array or even output a string from an array, take a look in this example:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/42047df0c4fdb81bd106282644c04c7c/href">https://medium.com/media/42047df0c4fdb81bd106282644c04c7c/href</a></iframe><p>I wrote a previous article about reduce with more example and an in-depth explanation.</p><p><a href="https://medium.com/@_rxluz/2-functional-approach-reduce-c882c68c4cdf">#2 Functional approach: Reduce</a></p><p>Ok, now you know the basic loop methods; I only use in my code forEach, map and reduce, because these three methods are enough to all I need and its syntax is minimal and elegant!</p><p>If you to want to know more about Javascript I recommend these books:</p><ul><li><strong>You Don’t Know JS Serie by Kyle Simpson (My favourite)</strong></li><li><strong>Eloquent JS by Marijn Haverbeke</strong></li><li><strong>Head First Javascript by Michael Morrison</strong></li><li><strong>Secrets of the JavaScript Ninja by Bear Bibeault and John Resig</strong></li></ul><p><strong><em>Thanks for reading! Feel free to hit the recommend button below if you found this piece helpful, also, </em>please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.</strong></p><p><a href="https://twitter.com/_rxluz">Ricardo Luz (@_rxluz) | Twitter</a></p><blockquote>If this post was helpful, please click the clap 👏 button below to show your support! ⬇⬇</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cd871895d2aa" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[#9 Big O with JS examples: The basic that you need to know]]></title>
            <link>https://medium.com/front-end-weekly/big-o-in-js-the-basic-that-you-need-to-know-a5abb45570fa?source=rss-892e3096e4fa------2</link>
            <guid isPermaLink="false">https://medium.com/p/a5abb45570fa</guid>
            <category><![CDATA[data-structures]]></category>
            <category><![CDATA[binary-search]]></category>
            <category><![CDATA[algorithms]]></category>
            <category><![CDATA[big-o-notation]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Ricardo Luz]]></dc:creator>
            <pubDate>Tue, 07 Aug 2018 10:57:47 GMT</pubDate>
            <atom:updated>2021-09-27T05:28:15.833Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4lmhUrOQl9np5CJ-UZyLQw.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/photos/UIvRqbmtlFU?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Esteban Lopez</a> on <a href="https://unsplash.com/trending?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p>There are many ways to analyse how good is a code that you have written, some people believe that beautiful code is better and others prefer a code with fewer lines, but there a <strong>universal way to analyse</strong> that help you to understand <strong>how fast</strong> your approach is and <strong>how sustainable</strong> your system is when running millions of operations.</p><blockquote>Its a common mistake to think that performance doesn’t matter anymore once the servers and devices processing capacity are increasing every year, we always should to remember that there are a considerable number of users using old devices or low power devices like smartphones, even updated smartphones reduce its processing capacity when the battery is running low, and powerful devices running low when dozen of tabs is running at the same time or several apps running together.</blockquote><p>So, remember, <strong>performance matters, always matters</strong>.</p><p><strong>Big O Notation</strong> is a way to measure how well a computer algorithm scales as the number of data increases, so when you have to choose an approach to create your system <strong>Big O Notation will help you to select the most efficient solution</strong>, let’s take some examples:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a1fe6e031410dcff8940d93dfe2f1945/href">https://medium.com/media/a1fe6e031410dcff8940d93dfe2f1945/href</a></iframe><p>In the example above is possible execute this operation using precisely the same time regardless the number of items inside People object, it always takes the same time, in <strong>Big O Notation</strong> its called <strong>O(1) or constant</strong>.</p><p><strong>Usually, O(1) is the best scenario</strong>, always when is possible you should try to look for a way to use functions that have <strong>O(1) Notation</strong>.</p><p>But in the example below the situation changes, take a look:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/eab184fdb07a0142ab35b8ca5c9050da/href">https://medium.com/media/eab184fdb07a0142ab35b8ca5c9050da/href</a></iframe><p><strong><em>If you don’t know how destructuring works, </em></strong><a href="https://medium.com/@_rxluz/8-functional-approach-destructuring-b39dcbb40683"><strong><em>take a look in this article</em></strong></a><strong><em>:</em></strong></p><p><a href="https://medium.com/@_rxluz/8-functional-approach-destructuring-b39dcbb40683">#8 Functional Approach: Destructuring</a></p><p>Now the number of operations will increase according to the items inside the array, it is called <strong>O(n) or Linear</strong>, this approach is one of the best that you could take when you’re coding something new, however, there a lot of situations that aren’t possible use functions with <strong>O(n)</strong>, but sometimes we merely decide to use an approach that will spend more processing.</p><p>When you create a loop inside another loop you have worst performance than <strong>O(1) </strong>and<strong> O(n)</strong>, like below:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/92532914e425d77722a0f80afaec4182/href">https://medium.com/media/92532914e425d77722a0f80afaec4182/href</a></iframe><p>This case is called <strong>O(n²) or quadratic</strong>, depending on the number of items inside your array this operation will take a very long time, and sometimes is possible to do the same using <strong>O(n)</strong>, you could convert this example to this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/10a5bf3c687910c9169be5badceefd2e/href">https://medium.com/media/10a5bf3c687910c9169be5badceefd2e/href</a></iframe><p>When you have inside an algorithm more than one <strong>O(x)</strong> you will always consider that have the worst <strong>O(x)</strong>:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f7772726beedabc37275fc46efd7b4bd/href">https://medium.com/media/f7772726beedabc37275fc46efd7b4bd/href</a></iframe><p>In this case, your algorithm has:</p><ol><li>A constant operation <strong>O(1)</strong>:</li></ol><pre><strong>const</strong> total = people.length;</pre><p>2. A Linear operation <strong>O(n)</strong></p><pre><strong>const</strong> names = people.map(({ name }) <strong>=&gt;</strong> name);</pre><p>3. A Quadratic operation <strong>O(n²)</strong></p><pre><strong>const</strong> peopleWithSameAge = people.filter<br>(<br> ({ age }) <strong>=&gt;</strong>   <br>   people.filter(person <strong>=&gt;</strong> person.age == age)<br>   .length &gt; 1<br>);</pre><p>In this case, we could think in this way <strong><em>O(1) + O(n) + O(n²), </em></strong>right? Nope, is more simple than that, <strong>you ignore the faster operations and consider only the slower operation</strong>, in this case, <strong>O(n²)</strong>, so this is an algorithm with <strong>O(n²) </strong>notation.</p><p>You’ll use this same approach when you have more than one operation with the same type:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/32d83c3dcbd82a4b7ed53eca83b5cfd3/href">https://medium.com/media/32d83c3dcbd82a4b7ed53eca83b5cfd3/href</a></iframe><p>No, this isn’t O(2n²), <strong>it’s merely O(n²)</strong>, when you have constants like this you ignore the constant and use only the original notation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7tM4xVRR1ZLiAEGNWBx7vg.png" /><figcaption>Source: <a href="http://bigocheatsheet.com/">http://bigocheatsheet.com/</a></figcaption></figure><p>There are a lot of other examples of Big O Notation that you could discover, beyond that I showed here one that I really like called <strong>logarithmic notation or O(log(n))</strong>, this is very common in divide and conquer algorithms type, take a look in this famous example called binary search:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5831dd0080d4211c26852e0c3b4f16a2/href">https://medium.com/media/5831dd0080d4211c26852e0c3b4f16a2/href</a></iframe><p><a href="https://medium.com/employbl/implement-linear-and-binary-search-algorithms-with-javascript-2149997588f0">Implement linear and binary search algorithms with Javascript</a></p><p>In this case the operations that you need to get the number that you’re searched increase less than in a quadratic or linear way, for example, <strong>to search for 4096 items you need only 12 operations</strong>! Cool right?</p><p>This article was an initial approach about Big O Notation. I recommend you study more about this because this will help you to code better and make the best decisions about how you write your code! I read a book called <a href="https://www.amazon.com/Learning-JavaScript-Data-Structures-Algorithms/dp/1783554878"><strong>Data Structures and Algorithms in Javascript</strong></a> written by <a href="https://medium.com/@loiane"><strong>Loiane Groiner</strong></a> that helps me a lot to understand better how Big O Notation works.</p><p><strong><em>Thanks for reading! Feel free to hit the recommend button below if you found this helpful.</em></strong></p><p><a href="https://twitter.com/_rxluz">Ricardo Luz (@_rxluz) | Twitter</a></p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fupscri.be%2Ff%2F788447%3Fas_embed%3Dtrue&amp;dntp=1&amp;display_name=Upscribe&amp;url=https%3A%2F%2Fupscri.be%2F788447%2F&amp;type=text%2Fhtml&amp;schema=upscri" width="800" height="400" frameborder="0" scrolling="no"><a href="https://medium.com/media/18214d8333adbb5668f31791a3202b60/href">https://medium.com/media/18214d8333adbb5668f31791a3202b60/href</a></iframe><blockquote>If this post was helpful, please click the clap 👏 button below to show your support! ⬇⬇</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a5abb45570fa" width="1" height="1" alt=""><hr><p><a href="https://medium.com/front-end-weekly/big-o-in-js-the-basic-that-you-need-to-know-a5abb45570fa">#9 Big O with JS examples: The basic that you need to know</a> was originally published in <a href="https://medium.com/front-end-weekly">Frontend Weekly</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[#8 Functional Approach: Destructuring]]></title>
            <link>https://medium.com/@_rxluz/8-functional-approach-destructuring-b39dcbb40683?source=rss-892e3096e4fa------2</link>
            <guid isPermaLink="false">https://medium.com/p/b39dcbb40683</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[rxluz]]></category>
            <category><![CDATA[functional-programming]]></category>
            <category><![CDATA[destructuring]]></category>
            <dc:creator><![CDATA[Ricardo Luz]]></dc:creator>
            <pubDate>Thu, 19 Apr 2018 19:25:02 GMT</pubDate>
            <atom:updated>2019-01-17T01:31:50.838Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cl_6pWesKPPAzWsyxXOPVA.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/photos/OAWZetHVB-8?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Ian Froome</a> on <a href="https://unsplash.com/?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p>When we call a JS function we have problems to identify the parameters name, once we only send the argument, like in the example below:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2294a9d1496360319e941e22b23138a6/href">https://medium.com/media/2294a9d1496360319e941e22b23138a6/href</a></iframe><p>The problem is, the arguments have no name, but they have a specific order, depending on your code this is a door to create bugs once is easy to put this parameter in a different order.</p><p>This case is only one of the things that destructuring helps you to solve! Using destructuring you could nominate your parameters using a simple array, like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2b71256e1ec34998e96ce7199e3566d8/href">https://medium.com/media/2b71256e1ec34998e96ce7199e3566d8/href</a></iframe><p>Cool right? Now the order doesn’t matter anymore, and you only needed to add “{“ before your parameters and “}” after.</p><p>But there is more, using this technique you could define a default value for your parameters like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/88686dec9df442a44202ab21475d4c9e/href">https://medium.com/media/88686dec9df442a44202ab21475d4c9e/href</a></iframe><p>Also, you can use destructuring to extract from a long array only the keys that you want to use and transform this keys into a new variable, like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6707030691030a274cb480478f87dc15/href">https://medium.com/media/6707030691030a274cb480478f87dc15/href</a></iframe><p>If you to want to know more about Javascript I recommend these books:</p><ul><li><strong>You Don’t Know JS Serie by Kyle Simpson (My favourite)</strong></li><li><strong>Eloquent JS by Marijn Haverbeke</strong></li><li><strong>Head First Javascript by Michael Morrison</strong></li><li><strong>Secrets of the JavaScript Ninja by Bear Bibeault and John Resig</strong></li></ul><p><strong><em>Thanks for reading! Feel free to hit the recommend button below if you found this piece helpful.</em></strong></p><p><strong><em>You can connect with me on Twitter: </em></strong><a href="https://twitter.com/_rxluz"><strong><em>@_rxluz</em></strong></a><strong><em> or in my </em></strong><a href="https://helloricardo.in/"><strong><em>Website</em></strong></a><strong><em>.</em></strong></p><blockquote>If this post was helpful, please click the clap 👏 button below to show your support! ⬇⬇</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b39dcbb40683" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>