<?xml version="1.0" encoding="UTF-8"?><rss version="2.0" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom"><channel><title>SmellyCode&apos;s RSS Feed</title><description>Ramblings of a software engineer.</description><link>https://smellycode.com/</link><atom:link href="https://smellycode.com/rss.xml" rel="self" type="application/rss+xml"/><item><title>How to &quot;require&quot; with aliases 🔁</title><link>https://smellycode.com/require-with-aliases/</link><guid isPermaLink="false">https://smellycode.com/require-with-aliases/</guid><description>An tutorial to setup aliased for a NodeJs applications.</description><pubDate>Sat, 08 May 2021 13:15:46 GMT</pubDate><content:encoded>&lt;p&gt;I recently worked on a NodeJs based command-line app. The app had
significant depth in its directory structure. The depth in directory structure
unintentionally added a wild amount of relativeness to &lt;a href=&quot;https://nodejs.org/en/knowledge/getting-started/what-is-require/&quot;&gt;require&lt;/a&gt; statements.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;const { utils } = require(&apos;../../../../lib&apos;);
const commands = require(&apos;../../../commands&apos;);
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;When I encountered these statements, I realized the need of aliases. I search for &lt;a href=&quot;https://www.google.com/search?q=nodejs+require+alias&amp;amp;rlz=1C5CHFA_enIN836IN837&amp;amp;oq=nodejs&amp;amp;aqs=chrome.0.69i59l3j69i57j69i65l3j69i60.2162j0j1&amp;amp;sourceid=chrome&amp;amp;ie=UTF-8&quot;&gt;nodejs require aliases&lt;/a&gt; and landed on the gist: &lt;a href=&quot;https://gist.github.com/branneman/8048520&quot;&gt;Better local require() paths for Node.js&lt;/a&gt;. It recommended almost 8 different solutions. I found &lt;a href=&quot;https://gist.github.com/branneman/8048520#0-the-alias&quot;&gt;the alias&lt;/a&gt; approach more promising and convincing because of following reasons:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;Clean &lt;em&gt;cross platform&lt;/em&gt; solution.&lt;/li&gt;
&lt;li&gt;Uses a well maintained popular npm package: &lt;a href=&quot;https://www.npmjs.com/package/module-alias&quot;&gt;module-alias&lt;/a&gt;.&lt;/li&gt;
&lt;li&gt;Aliases can be prefixed with symbols(such as &lt;code&gt;@&lt;/code&gt;) to tip off fellow developers.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;The alias approach had a few downsides which could be resolved easily.&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;Littering &lt;code&gt;package.json&lt;/code&gt; with aliases(can be avoided by &lt;a href=&quot;https://github.com/ilearnio/module-alias#advanced-usage&quot;&gt;manually adding aliases&lt;/a&gt;).&lt;/li&gt;
&lt;li&gt;Requires additional steps for linter and editor.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;After evaluating trade offs, I installed &lt;a href=&quot;https://www.npmjs.com/package/module-alias&quot;&gt;module-alias&lt;/a&gt; and added aliases in &lt;code&gt;package.json&lt;/code&gt;.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;{
  &quot;_moduleAliases&quot;: {
    &quot;@lib&quot;: &quot;lib&quot;,
    &quot;@constants&quot;: &quot;constants&quot;,
    &quot;@commands&quot;: &quot;commands&quot;
  }
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;I also replaced relative require statements with aliases and tested the change.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;const { utils } = require(&apos;@lib&apos;);
const commands = require(&apos;@commands&apos;);
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Things were working as expected. But gradually ESLint started &lt;em&gt;screaming&lt;/em&gt;:&lt;/p&gt;
&lt;p&gt;&lt;img src=&quot;https://smellycode.com/_astro/es-lint-import-no-resolve.BHrWI4w_.png&quot; alt=&quot;&quot; /&gt;&lt;/p&gt;
&lt;p&gt;It was expected because EsLint can not resolve the path aliases. I pacified ESLint using &lt;a href=&quot;https://www.npmjs.com/package/eslint-import-resolver-alias&quot;&gt;eslint-import-resolver-alias&lt;/a&gt; with below config:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;{
  &quot;import/resolver&quot;: {
    &quot;alias&quot;: [
      [&quot;@lib&quot;, &quot;./lib&quot;],
      [&quot;@constants&quot;, &quot;./constants&quot;],
      [&quot;@commands&quot;, &quot;./commands&quot;]
    ]
  }
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;After a while, I found that features such as IntelliSense, quick navigation between modules, etc. stopped working for aliased paths. It’s because VS Code was not aware of the aliased path mappings. I added the aliased path mappings to &lt;a href=&quot;https://code.visualstudio.com/docs/languages/jsconfig#_using-webpack-aliases&quot;&gt;compilerOptions&lt;/a&gt; of &lt;a href=&quot;https://code.visualstudio.com/docs/languages/jsconfig&quot;&gt;jsconfig.json&lt;/a&gt; for VS Code.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;{
  &quot;compilerOptions&quot;: {
    &quot;baseUrl&quot;: &quot;./&quot;,
    &quot;paths&quot;: {
      &quot;@lib&quot;: [&quot;./lib&quot;],
      &quot;@constants&quot;: [&quot;./constants&quot;],
      &quot;@commands&quot;: [&quot;./commands&quot;]
    }
  }
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;It started working as usual. &lt;em&gt;Tada&lt;/em&gt; 🎉! I was happy. EsLint was happy. VS Code was happy. &lt;em&gt;Everyone was happy&lt;/em&gt;.&lt;/p&gt;
</content:encoded><category>JavaScript</category><category>NodeJs</category><category>VS Code</category><category>ESLint</category></item><item><title>A bit about Binary Heap 🌳</title><link>https://smellycode.com/binary-heap/</link><guid isPermaLink="false">https://smellycode.com/binary-heap/</guid><description>An overview of binary heap with words, code and diagrams.</description><pubDate>Sat, 20 Jun 2020 13:15:46 GMT</pubDate><content:encoded>&lt;p&gt;We learned about trees and binary trees in posts &lt;a href=&quot;https://smellycode.com/trees/&quot;&gt;A Gentle Introduction to Trees 🌳&lt;/a&gt; and &lt;a href=&quot;https://smellycode.com/binary-tree/&quot;&gt;A Bit about Binary Tree 🌳&lt;/a&gt;. In this post, we&apos;ll learn about a special type of binary tree called &lt;em&gt;binary heap&lt;/em&gt;. A binary heap is a binary tree with following properties:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;A binary heap is &lt;strong&gt;a complete binary tree&lt;/strong&gt;. In a complete binary tree, all levels are filled completely, except possibly the last level, and all nodes are as far left as possible.&lt;/li&gt;
&lt;/ul&gt;
&lt;figure class=&quot;invert-on-dark&quot;&gt;
&lt;p&gt;&lt;img src=&quot;https://smellycode.com/_astro/complete-binary-tree.D7UEnnji.png&quot; alt=&quot;A complete binary tree&quot; /&gt;&lt;/p&gt;
&lt;/figure&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;The root element of a binary heap is minimum/maximum amongst other elements of the tree&lt;/strong&gt;. This property makes a binary heap either min heap or max heap. &lt;strong&gt;The heap property is recursively true for all the subtrees in a binary heap&lt;/strong&gt;.&lt;/li&gt;
&lt;/ul&gt;
&lt;figure class=&quot;invert-on-dark&quot;&gt;
&lt;p&gt;&lt;img src=&quot;https://smellycode.com/_astro/min-max-binary-heap.CsJS87Gc.png&quot; alt=&quot;Min Heap and Max Heap&quot; /&gt;&lt;/p&gt;
&lt;/figure&gt;
&lt;p&gt;A binary heap is typically implemented using an &lt;em&gt;array&lt;/em&gt;. For an element at &lt;em&gt;i&lt;/em&gt;&lt;sup&gt;th&lt;/sup&gt; position in array:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;parent =&amp;gt; (i - 1) / 2
left   =&amp;gt; 2 * i + 1
right  =&amp;gt; 2 * i + 2
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Let&apos;s quickly define operations for a binary heap.&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;code&gt;insert(item)&lt;/code&gt;: inserts &lt;code&gt;item&lt;/code&gt; to the heap.&lt;/li&gt;
&lt;li&gt;&lt;code&gt;remove(i)&lt;/code&gt;: removes the i&lt;sup&gt;th&lt;/sup&gt; item.&lt;/li&gt;
&lt;li&gt;&lt;code&gt;getRoot()&lt;/code&gt;: returns the root element of the heap. It is &lt;code&gt;getMin&lt;/code&gt; for MinHeap and &lt;code&gt;getMax&lt;/code&gt; for MaxHeap.&lt;/li&gt;
&lt;li&gt;&lt;code&gt;updateValue(i, value)&lt;/code&gt;: updates the value of i&lt;sup&gt;th&lt;/sup&gt; item. It is &lt;code&gt;decreaseValue&lt;/code&gt; for MinHeap and &lt;code&gt;increaseValue&lt;/code&gt; for MaxHeap.&lt;/li&gt;
&lt;li&gt;&lt;code&gt;size()&lt;/code&gt;: returns the size of heap.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;We&apos;ll use inheritance here, instead of composition because of &lt;strong&gt;&lt;em&gt;is a relationship&lt;/em&gt;&lt;/strong&gt;. We&apos;ll define these methods in a base class &lt;code&gt;BinaryHeap&lt;/code&gt;, which &lt;code&gt;MinBinaryHeap&lt;/code&gt; and &lt;code&gt;MaxBinaryHeap&lt;/code&gt; heap will extend. We&apos;ll also make &lt;code&gt;BinaryHeap&lt;/code&gt; class an abstract class with a &lt;code&gt;comparator&lt;/code&gt; abstract method.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;class BinaryHeap {
  constructor() {
    if (this.constructor === BinaryHeap) {
      throw new Error(
        `BinaryHeap is an abstract class. It can&apos;t be instantiated.`
      );
    }
    this._arr = [];
  }

  _swap(i, j) {
    [this._arr[i], this._arr[j]] = [this._arr[j], this._arr[i]];
  }

  _parent(index) {
    return Math.floor((index - 1) / 2);
  }

  _left(index) {
    return 2 * index + 1;
  }

  _right(index) {
    return 2 * index + 2;
  }

  _heapify() {
    // TODO: Provide stub.
  }

  comparator() {
    throw new Error(&apos;comparator method must be implemented&apos;);
  }

  insert(item) {
    // TODO: Provide stub.
  }

  remove(index, signedInfinity) {
    // TODO: Provide stub.
  }

  // Min heap -&amp;gt; `decreaseValue`
  // Max heap -&amp;gt; `increaseValue`.
  updateValue(index, value) {
    // TODO: Provide stub.
  }

  // Min heap -&amp;gt; `extractMin`
  // Max heap -&amp;gt; `extractMax`.
  extractRoot() {
    // TODO: Provide stub.
  }

  getRoot() {
    return this._arr[0];
  }

  size() {
    return this._arr.length;
  }
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;A &lt;code&gt;MinBinaryHeap&lt;/code&gt; class which extends &lt;code&gt;BinaryHeap&lt;/code&gt;.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;class MinBinaryHeap extends BinaryHeap {
  constructor(comparator) {
    super();
    this.comparator = comparator || this.comparator;
  }

  comparator(a, b) {
    return a &amp;lt; b;
  }

  getMin() {
    return this.getRoot();
  }

  extractMin() {
    return this.extractRoot();
  }

  remove(index) {
    return super.remove(index, Number.NEGATIVE_INFINITY);
  }

  decreaseValue(index, value) {
    return this.updateValue(index, value);
  }
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;A &lt;code&gt;MaxBinaryHeap&lt;/code&gt; class which extends &lt;code&gt;BinaryHeap&lt;/code&gt;.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;class MaxBinaryHeap extends BinaryHeap {
  constructor(comparator) {
    super();
    this.comparator = comparator || this.comparator;
  }

  comparator(a, b) {
    return a &amp;gt; b;
  }

  getMax() {
    return this.getRoot();
  }

  extractMax() {
    return this.extractRoot();
  }

  increaseValue(index, value) {
    return this.updateValue(index, value);
  }

  remove(index) {
    return super.remove(index, Number.POSITIVE_INFINITY);
  }
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Let&apos;s implement each operation for a min heap. Implementations of these operations for a max heap more or less remain same except the comparison of elements.&lt;/p&gt;
&lt;h3&gt;Insert&lt;/h3&gt;
&lt;p&gt;Insertion in binary heap is straight forward. We push the &lt;code&gt;element&lt;/code&gt; to the array and swap it with its &lt;code&gt;parent&lt;/code&gt; element until the heap property is satisfied.&lt;/p&gt;
&lt;figure class=&quot;invert-on-dark&quot;&gt;
&lt;p&gt;&lt;img src=&quot;https://smellycode.com/_astro/binary-heap-insert.DftgdC9m.gif&quot; alt=&quot;Binary Heap Insertion&quot; /&gt;&lt;/p&gt;
&lt;/figure&gt;
&lt;p&gt;For a min binary heap, one can use following steps for insertion:&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;Push &lt;code&gt;element&lt;/code&gt; to the array.&lt;/li&gt;
&lt;li&gt;While &lt;code&gt;element&lt;/code&gt; is smaller than &lt;code&gt;parent&lt;/code&gt;, swap &lt;code&gt;parent&lt;/code&gt; and &lt;code&gt;element&lt;/code&gt;.&lt;/li&gt;
&lt;/ol&gt;
&lt;pre&gt;&lt;code&gt;class BinaryHeap {
  // other useful method
  // ...
  // ...

  insert(item) {
    let pos = this._arr.length;
    let parPos = this._parent(pos);
    this._arr.push(item);
    while (pos !== 0 &amp;amp;&amp;amp; this.comparator(item, this._arr[parPos])) {
      this._swap(parPos, pos);
      pos = parPos;
      parPos = this._parent(pos);
    }
    return this;
  }

  // other useful methods
  // ...
  // ...
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;In the worst case scenario, the &lt;code&gt;element&lt;/code&gt; moves from &lt;code&gt;leaf&lt;/code&gt; to &lt;code&gt;root&lt;/code&gt; of the binary heap. Consequently, the time complexity equals to the height of the heap i.e. &lt;em&gt;O(logn)&lt;/em&gt;.&lt;/p&gt;
&lt;h3&gt;Update&lt;/h3&gt;
&lt;p&gt;The update operation decreases/increases the value of a node for a min/max binary heap.&lt;/p&gt;
&lt;figure class=&quot;invert-on-dark&quot;&gt;
&lt;p&gt;&lt;img src=&quot;https://smellycode.com/_astro/binary-heap-update.DaGFYHMr.gif&quot; alt=&quot;Binary heap update&quot; /&gt;&lt;/p&gt;
&lt;/figure&gt;
&lt;p&gt;To update the value of node at position &lt;code&gt;index&lt;/code&gt;, we replace it&apos;s value with the new value and swap it with its &lt;code&gt;parent&lt;/code&gt; element until the heap property is satisfied.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;class BinaryHeap {
  // other useful method
  // ...
  // ...

  // Min heap -&amp;gt; `decreaseValue`
  // Max heap -&amp;gt; `increaseValue`.
  updateValue(index, value) {
    this._arr[index] = value;
    let pIndex = this._parent(index);
    while (pIndex &amp;gt;= 0 &amp;amp;&amp;amp; this.comparator(value, this._arr[pIndex])) {
      this._swap(pIndex, index);
      index = pIndex;
      pIndex = this._parent(index);
    }
    return this;
  }

  // other useful methods
  // ...
  // ...
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;The time complexity for update operation is &lt;em&gt;O(logn)&lt;/em&gt;&lt;/p&gt;
&lt;h3&gt;Extract Root&lt;/h3&gt;
&lt;p&gt;The root element in the binary heap represents the maximum/minimum element. That&apos;s why a min/max binary heap has an &lt;code&gt;extractMin&lt;/code&gt; or &lt;code&gt;extractMax&lt;/code&gt; method. Once the root is extracted, the elements of heap are rearranged or &lt;em&gt;heapified&lt;/em&gt; to maintain the heap property.&lt;/p&gt;
&lt;p&gt;To extract the root of a min binary heap, we replace the root with the farthest right leaf and heapify it.&lt;/p&gt;
&lt;figure class=&quot;invert-on-dark&quot;&gt;
&lt;p&gt;&lt;img src=&quot;https://smellycode.com/_astro/min-binary-heap-extract-min.Xs319jdK.gif&quot; alt=&quot;Min binary heap extract min&quot; /&gt;&lt;/p&gt;
&lt;/figure&gt;
&lt;p&gt;To heapify a min heap, we find the minimum amongst the root and it&apos;s children(left and right). If root is not the minimum element, then we swap it with the minimum element. We recursively follow this process till the heap property is satisfied.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;class BinaryHeap {
  // other useful method
  // ...
  // ...

  _heapify(index) {
    if (index &amp;gt;= this._arr.length) {
      return;
    }
    let left = this._left(index);
    let right = this._right(index);
    let target = index;
    if (
      left &amp;lt; this._arr.length &amp;amp;&amp;amp;
      this.comparator(this._arr[left], this._arr[target])
    ) {
      target = left;
    }
    if (
      right &amp;lt; this._arr.length &amp;amp;&amp;amp;
      this.comparator(this._arr[right], this._arr[target])
    ) {
      target = right;
    }
    if (target !== index) {
      this._swap(target, index);
      this._heapify(target);
    }
  }

  // Min heap -&amp;gt; `extractMin`
  // Max heap -&amp;gt; `extractMax`.
  extractRoot() {
    if (this._arr.length === 0) {
      return null;
    }
    if (this._arr.length === 1) {
      return this._arr.pop();
    }
    const value = this._arr[0];
    this._arr[0] = this._arr.pop();
    this._heapify(0);
    return value;
  }

  // other useful methods
  // ...
  // ...
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;The time complexity to extract root is &lt;em&gt;O(logn)&lt;/em&gt;&lt;/p&gt;
&lt;h3&gt;Delete/Remove&lt;/h3&gt;
&lt;p&gt;To delete an element from a binary heap, we update it&apos;s value with maximum/minimum value i.e. &lt;code&gt;Infinity&lt;/code&gt; and &lt;code&gt;-Infinity&lt;/code&gt; and extract the root.&lt;/p&gt;
&lt;figure class=&quot;invert-on-dark&quot;&gt;
&lt;p&gt;&lt;img src=&quot;https://smellycode.com/_astro/binary-heap-cover-img.-LGNaVwe.gif&quot; alt=&quot;Min binary heap delete&quot; /&gt;&lt;/p&gt;
&lt;/figure&gt;
&lt;pre&gt;&lt;code&gt;class BinaryHeap {
  // other useful method
  // ...
  // ...

  remove(pos, signedInfinity) {
    const v = this._arr[pos];
    this.updateValue(pos, signedInfinity);
    this.extractRoot();
    return v;
  }

  // other useful methods
  // ...
  // ...
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;The time complexity for deletion is &lt;em&gt;O(logn)&lt;/em&gt;.&lt;/p&gt;
&lt;h3&gt;Summary&lt;/h3&gt;
&lt;p&gt;Binary heaps are complete binary trees. Each node in a binary heap is minimum/maximum amongst its children(also known as heap property). Consequently, a binary heap can be either a min binary heap or a max binary heap.&lt;/p&gt;
&lt;p&gt;A binary heap is typically implemented using an array. The parent, left and child element of the i&lt;sup&gt;th&lt;/sup&gt; element in array are present at &lt;code&gt;(i - 1) / 2&lt;/code&gt;, &lt;code&gt;2 * i + 1&lt;/code&gt;, and &lt;code&gt;2 * i + 2&lt;/code&gt; positions.&lt;/p&gt;
&lt;p&gt;For a binary heap, basic operations like deletion, insertion, root extraction, etc take &lt;em&gt;O(logn)&lt;/em&gt; time.&lt;/p&gt;
</content:encoded><category>JavaScript</category><category>Data Structures</category><category>Algorithms</category><category>Trees</category></item><item><title>JavaScript and Bit-hacks 🧙🏻‍♂️</title><link>https://smellycode.com/js-bithacks/</link><guid isPermaLink="false">https://smellycode.com/js-bithacks/</guid><description>An overview of bitwise operators in JavaScript with bit-hacks.</description><pubDate>Fri, 01 May 2020 13:15:46 GMT</pubDate><content:encoded>&lt;p&gt;Bitwise operators operate on binary numbers. If the operands of a bitwise operator are not binary, then they are converted into binary before the operation.&lt;/p&gt;
&lt;p&gt;In JavaScript, bitwise operators convert their operand(s) into &lt;strong&gt;32-bit signed integers in two&apos;s complement format&lt;/strong&gt;. However, the results are standard numbers. This post elaborates on bitwise operators available in JavaScript and explores a few popular bitwise tricks/hacks.&lt;/p&gt;
&lt;p&gt;Before we jump into bitwise operators, let&apos;s take a gander at the two&apos;s complement.&lt;/p&gt;
&lt;p&gt;There are many ways to compute two&apos;s complement of a number. Here&apos;s a &lt;a href=&quot;https://stackoverflow.com/questions/1049722/what-is-2s-complement&quot; target=&quot;_blank&quot; rel=&quot;noreferrer noopener&quot;&gt;one&lt;/a&gt; I like to use:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;1. Convert the magnitude of the number to binary.
2. If the number is positive, then we are done.
3. If the number is negative:
   a. Find the one&apos;s complement of binary by inverting 0&apos;s and 1&apos;s.
   b. Add 1 to the one&apos;s complement.
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Let&apos;s find two&apos;s complement of 5 and -5 with the method above. We&apos;ll use a nibble(4 bits) for the same.&lt;/p&gt;
&lt;p&gt;Finding two&apos;s complement of 5 is straightforward. It&apos;s a positive number. Therefore it&apos;s two&apos;s complement is &lt;code&gt;0101&lt;/code&gt;.&lt;/p&gt;
&lt;p&gt;Finding two&apos;s complement of -5 includes the following steps:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;1. The magnitude of -5 is 5. 5 in binary is `0101`.
2. -5 is a negative number:
   1. The one&apos;s complement of `0101` is `1010`.
   2. The complement after adding 1: `1011`.
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;The two&apos;s complement of -5 is &lt;code&gt;1011&lt;/code&gt;.&lt;/p&gt;
&lt;p&gt;Converting &lt;strong&gt;two&apos;s complement to decimal&lt;/strong&gt; involves similar steps.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;1. If the two&apos;s complement of the number starts with `1`:
   a. Find the one&apos;s complement by inverting 0&apos;s and 1&apos;s.
   b. Add one to the one&apos;s complement.
2. Convert the binary to decimal.
3. If two&apos;s complement starts with one, add minus sign to decimal.
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Let&apos;s consider two&apos;s complement &lt;code&gt;0101&lt;/code&gt; and &lt;code&gt;1011&lt;/code&gt; and find their decimal values.&lt;/p&gt;
&lt;p&gt;&lt;code&gt;0101&lt;/code&gt; starts with zero. It doesn&apos;t require any additional steps. The decimal value of &lt;code&gt;0101&lt;/code&gt; is 5.&lt;/p&gt;
&lt;p&gt;The two&apos;s complement to decimal conversion for &lt;code&gt;1011&lt;/code&gt; requires the below steps:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;1. One&apos;s complement of `1011` is `0100`.
2. After adding 1: `0101`.
3. The decimal equivalent of `0101` is 5.
4. `1011` starts with one. Therefore, -5.
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;The decimal value of &lt;code&gt;1011&lt;/code&gt; is -5.&lt;/p&gt;
&lt;p&gt;In two&apos;s complement format, the leftmost bit acts as a sign bit. It means an n-bit layout can &lt;em&gt;safely&lt;/em&gt; represent numbers from -2&lt;sup&gt;n - 1&lt;/sup&gt; to 2&lt;sup&gt;n - 1&lt;/sup&gt; - 1 in two&apos;s complement format. For example, a nibble(4 bits layout) can represent number from -8 to 7 without any precision loss.&lt;/p&gt;
&lt;p&gt;JavaScript uses a 32-bit layout for bitwise operations. Therefore, the range is -2&lt;sup&gt;31&lt;/sup&gt; to 2&lt;sup&gt;31&lt;/sup&gt; - 1(equivalent to &lt;em&gt;-2147483648 to 2147483647&lt;/em&gt;).&lt;/p&gt;
&lt;p&gt;Two’s complement of some numbers in 32 bits:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;-1&lt;/li&gt;
&lt;/ul&gt;
&lt;pre&gt;&lt;code&gt;          1 =&amp;gt; 00000000000000000000000000000001
 Complement =&amp;gt; 11111111111111111111111111111110
                                             +1
-----------------------------------------------
2&apos;s complement 11111111111111111111111111111111
-----------------------------------------------
&lt;/code&gt;&lt;/pre&gt;
&lt;ul&gt;
&lt;li&gt;2147483647&lt;/li&gt;
&lt;/ul&gt;
&lt;pre&gt;&lt;code&gt; 2147483647 =&amp;gt; 01111111111111111111111111111111
-----------------------------------------------
2&apos;s complement 01111111111111111111111111111111
-----------------------------------------------
&lt;/code&gt;&lt;/pre&gt;
&lt;ul&gt;
&lt;li&gt;-2147483648&lt;/li&gt;
&lt;/ul&gt;
&lt;pre&gt;&lt;code&gt; 2147483648 =&amp;gt; 10000000000000000000000000000000
 Complement =&amp;gt; 01111111111111111111111111111111
                                             +1
-----------------------------------------------
2&apos;s complement 10000000000000000000000000000000
-----------------------------------------------
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;If a number has more than 32-bits, it looses its significant bits. For example, the below statement logs zero.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;console.log((2 ** 32) &amp;gt;&amp;gt; 0);
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;It is because the 2&apos;s complement of 2&lt;sup&gt;32&lt;/sup&gt; is zero in 32-bits. We shift zero by zero bits and end up with zero.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;    4294967296 =&amp;gt; 100000000000000000000000000000000 (33 bits)
    4294967296 =&amp;gt;  00000000000000000000000000000000 (32 bits)
-------------------------------------------------------------
2&apos;s complement =&amp;gt;  00000000000000000000000000000000 (32 bits)
-------------------------------------------------------------
&lt;/code&gt;&lt;/pre&gt;
&lt;h2&gt;Bitwise Logical Operators&lt;/h2&gt;
&lt;p&gt;Bitwise logical operators pair each bit of one operand with another operand and perform logical operations on these pairs. That&apos;s why these operations are called &lt;em&gt;bitwise operations&lt;/em&gt;.&lt;/p&gt;
&lt;h3&gt;&amp;amp; (Bitwise AND)&lt;/h3&gt;
&lt;p&gt;&lt;strong&gt;&amp;amp;&lt;/strong&gt; operator performs &lt;strong&gt;AND&lt;/strong&gt; operation. It yields 1 if both operands are 1, else 0.&lt;/p&gt;
&lt;table&gt;
   &lt;thead&gt;
      &lt;tr&gt;
         &lt;th&gt;x&lt;/th&gt;
         &lt;th&gt;y&lt;/th&gt;
         &lt;th&gt;x &amp;amp; y&lt;/th&gt;
      &lt;/tr&gt;
   &lt;/thead&gt;
   &lt;tbody&gt;
      &lt;tr&gt;
         &lt;td&gt;0&lt;/td&gt;
         &lt;td&gt;0&lt;/td&gt;
         &lt;td&gt;0&lt;/td&gt;
      &lt;/tr&gt;
      &lt;tr&gt;
         &lt;td&gt;0&lt;/td&gt;
         &lt;td&gt;1&lt;/td&gt;
         &lt;td&gt;0&lt;/td&gt;
      &lt;/tr&gt;
      &lt;tr&gt;
         &lt;td&gt;1&lt;/td&gt;
         &lt;td&gt;0&lt;/td&gt;
         &lt;td&gt;0&lt;/td&gt;
      &lt;/tr&gt;
      &lt;tr&gt;
         &lt;td&gt;1&lt;/td&gt;
         &lt;td&gt;1&lt;/td&gt;
         &lt;td&gt;1&lt;/td&gt;
      &lt;/tr&gt;
   &lt;/tbody&gt;
&lt;/table&gt;
&lt;pre&gt;&lt;code&gt;     1 =&amp;gt; 00000000000000000000000000000001
     2 =&amp;gt; 00000000000000000000000000000010
------------------------------------------
 1 &amp;amp; 2 =&amp;gt; 00000000000000000000000000000000  =&amp;gt; 0
------------------------------------------
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;strong&gt;For any number x, &lt;code&gt;x &amp;amp; 0&lt;/code&gt; always yields 0&lt;/strong&gt;.&lt;/p&gt;
&lt;h3&gt;| (Bitwise OR)&lt;/h3&gt;
&lt;p&gt;&lt;strong&gt;|&lt;/strong&gt; operator performs &lt;strong&gt;OR&lt;/strong&gt; operation. It yields 1 if one of the operand is 1, else 0.&lt;/p&gt;
&lt;table&gt;
   &lt;thead&gt;
      &lt;tr&gt;
         &lt;th&gt;x&lt;/th&gt;
         &lt;th&gt;y&lt;/th&gt;
         &lt;th&gt;x | y&lt;/th&gt;
      &lt;/tr&gt;
   &lt;/thead&gt;
   &lt;tbody&gt;
      &lt;tr&gt;
         &lt;td&gt;0&lt;/td&gt;
         &lt;td&gt;0&lt;/td&gt;
         &lt;td&gt;0&lt;/td&gt;
      &lt;/tr&gt;
      &lt;tr&gt;
         &lt;td&gt;0&lt;/td&gt;
         &lt;td&gt;1&lt;/td&gt;
         &lt;td&gt;1&lt;/td&gt;
      &lt;/tr&gt;
      &lt;tr&gt;
         &lt;td&gt;1&lt;/td&gt;
         &lt;td&gt;0&lt;/td&gt;
         &lt;td&gt;1&lt;/td&gt;
      &lt;/tr&gt;
      &lt;tr&gt;
         &lt;td&gt;1&lt;/td&gt;
         &lt;td&gt;1&lt;/td&gt;
         &lt;td&gt;1&lt;/td&gt;
      &lt;/tr&gt;
   &lt;/tbody&gt;
&lt;/table&gt;
&lt;pre&gt;&lt;code&gt;     1 =&amp;gt; 00000000000000000000000000000001
     2 =&amp;gt; 00000000000000000000000000000010
------------------------------------------
 1 | 2 =&amp;gt; 00000000000000000000000000000011  =&amp;gt; 3
------------------------------------------
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;strong&gt;For any number x, &lt;code&gt;x | 0&lt;/code&gt; always yields x&lt;/strong&gt;.&lt;/p&gt;
&lt;h3&gt;^ (Bitwise XOR)&lt;/h3&gt;
&lt;p&gt;&lt;strong&gt;^&lt;/strong&gt; operator performs &lt;strong&gt;XOR&lt;/strong&gt; operation. It yields 1, if both operands are different, else 0.&lt;/p&gt;
&lt;table&gt;
   &lt;thead&gt;
      &lt;tr&gt;
         &lt;th&gt;x&lt;/th&gt;
         &lt;th&gt;y&lt;/th&gt;
         &lt;th&gt;x ^ y&lt;/th&gt;
      &lt;/tr&gt;
   &lt;/thead&gt;
   &lt;tbody&gt;
      &lt;tr&gt;
         &lt;td&gt;0&lt;/td&gt;
         &lt;td&gt;0&lt;/td&gt;
         &lt;td&gt;0&lt;/td&gt;
      &lt;/tr&gt;
      &lt;tr&gt;
         &lt;td&gt;0&lt;/td&gt;
         &lt;td&gt;1&lt;/td&gt;
         &lt;td&gt;1&lt;/td&gt;
      &lt;/tr&gt;
      &lt;tr&gt;
         &lt;td&gt;1&lt;/td&gt;
         &lt;td&gt;0&lt;/td&gt;
         &lt;td&gt;1&lt;/td&gt;
      &lt;/tr&gt;
      &lt;tr&gt;
         &lt;td&gt;1&lt;/td&gt;
         &lt;td&gt;1&lt;/td&gt;
         &lt;td&gt;0&lt;/td&gt;
      &lt;/tr&gt;
   &lt;/tbody&gt;
&lt;/table&gt;
&lt;pre&gt;&lt;code&gt;     1 =&amp;gt; 00000000000000000000000000000001
     2 =&amp;gt; 00000000000000000000000000000010
------------------------------------------
 1 ^ 2 =&amp;gt; 00000000000000000000000000000011  =&amp;gt; 3
------------------------------------------
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;strong&gt;For any number x, &lt;code&gt;x ^ 0&lt;/code&gt; always yields x&lt;/strong&gt;.&lt;/p&gt;
&lt;h3&gt;~ (Bitwise NOT)&lt;/h3&gt;
&lt;p&gt;&lt;strong&gt;~&lt;/strong&gt; operator performs &lt;strong&gt;NOT&lt;/strong&gt; operation. It inverts bits of the operands.&lt;/p&gt;
&lt;table&gt;
   &lt;thead&gt;
      &lt;tr&gt;
         &lt;th&gt;x&lt;/th&gt;
         &lt;th&gt;~x&lt;/th&gt;
      &lt;/tr&gt;
   &lt;/thead&gt;
   &lt;tbody&gt;
      &lt;tr&gt;
         &lt;td&gt;0&lt;/td&gt;
         &lt;td&gt;1&lt;/td&gt;
      &lt;/tr&gt;
      &lt;tr&gt;
         &lt;td&gt;1&lt;/td&gt;
         &lt;td&gt;0&lt;/td&gt;
      &lt;/tr&gt;
   &lt;/tbody&gt;
&lt;/table&gt;
&lt;pre&gt;&lt;code&gt;    -1 =&amp;gt; 11111111111111111111111111111111
------------------------------------------
 ~(-1) =&amp;gt; 00000000000000000000000000000000 =&amp;gt; 0
------------------------------------------
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;strong&gt;For any number x, &lt;code&gt;~x&lt;/code&gt; always yields -(x + 1)&lt;/strong&gt;.&lt;/p&gt;
&lt;h2&gt;Bitwise shift operators&lt;/h2&gt;
&lt;p&gt;Bitwise shift operators work with two operands--left and right. The operator shifts the left operand by certain bit positions--defined by the right operand. The operator controls the direction of the shifting.&lt;/p&gt;
&lt;p&gt;Bitwise shift operators convert their left and right operands into 32-bit signed integers in two&apos;s complement format. Only &lt;em&gt;the least significant 5-bits of the right operand are used&lt;/em&gt; cause the operator can shift 32 bits at max.&lt;/p&gt;
&lt;h3&gt;&amp;lt;&amp;lt; (Left Shift)&lt;/h3&gt;
&lt;p&gt;As the name suggests, the left shift operator shifts the first operand to the left by the specified number of bits. The operator discards bits from left and fills zero from the right.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;               2 =&amp;gt; 00000000000000000000000000000010
----------------------------------------------------
          2 &amp;lt;&amp;lt; 5 =&amp;gt; 00000000000000000000000001000000 =&amp;gt; 64
----------------------------------------------------
&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;     -2147483648 =&amp;gt; 10000000000000000000000000000000
----------------------------------------------------
-2147483648 &amp;lt;&amp;lt; 1 =&amp;gt; 00000000000000000000000000000000 =&amp;gt; 0
----------------------------------------------------
&lt;/code&gt;&lt;/pre&gt;
&lt;h3&gt;&amp;gt;&amp;gt; (Sign-propagating Right Shift)&lt;/h3&gt;
&lt;p&gt;Sign-propagating right shift operator shifts the first operand to the right by the specified number of bits. It discards bits from the right and copies the leftmost bit on the left.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;               2 =&amp;gt; 00000000000000000000000000000010
----------------------------------------------------
          2 &amp;gt;&amp;gt; 1 =&amp;gt; 00000000000000000000000000000001 =&amp;gt; 1
----------------------------------------------------
&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;     -2147483648 =&amp;gt; 10000000000000000000000000000000
----------------------------------------------------
-2147483648 &amp;gt;&amp;gt; 4 =&amp;gt; 11111000000000000000000000000000 =&amp;gt; -134217728
----------------------------------------------------
&lt;/code&gt;&lt;/pre&gt;
&lt;h3&gt;&amp;gt;&amp;gt;&amp;gt; (Zero-fill Right Shift)&lt;/h3&gt;
&lt;p&gt;Zero-fill right shift operator is quite akin to sign-propagating right shift operator. Instead of propagating the sign bit, it fills zeros in the left while shifting the operand to the right.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Unlike other bitwise operators, zero-fill right shift operator returns a 32-bit unsigned integer.&lt;/strong&gt; Therefore, the return value is converted directly from binary to decimal.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;      -2147483648 =&amp;gt; 10000000000000000000000000000000
-----------------------------------------------------
-2147483648 &amp;gt;&amp;gt;&amp;gt; 2 =&amp;gt; 00100000000000000000000000000000 =&amp;gt; 536870912
-----------------------------------------------------
&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;      -2147483648 =&amp;gt; 10000000000000000000000000000000
-----------------------------------------------------
-2147483648 &amp;gt;&amp;gt;&amp;gt; 0 =&amp;gt; 10000000000000000000000000000000 =&amp;gt; 2147483648
-----------------------------------------------------
&lt;/code&gt;&lt;/pre&gt;
&lt;h2&gt;Bitmask&lt;/h2&gt;
&lt;p&gt;A bitmask or mask is a variable that is used in bitwise operations to set/unset the bits of another variable. For example, let’s say we need to check if a variable is odd. &lt;em&gt;How do we find it using bitwise operators?&lt;/em&gt; We know that the lowest bit of an odd number is always 1. The below function leverages this fact.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;function isOdd(x) {
  return x &amp;amp; 1;
}
console.log(isOdd(5)); // 1
console.log(isOdd(4)); // 0
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;The function &lt;code&gt;isOdd&lt;/code&gt; unsets bits of &lt;code&gt;x&lt;/code&gt; by ANDing &lt;code&gt;x&lt;/code&gt; with 1.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;   5 =&amp;gt; 0000000000000000000000000000101
   1 =&amp;gt; 0000000000000000000000000000001
---------------------------------------
   &amp;amp; =&amp;gt; 0000000000000000000000000000001 =&amp;gt; 1
---------------------------------------
&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;   4 =&amp;gt; 0000000000000000000000000000100
   1 =&amp;gt; 0000000000000000000000000000001
---------------------------------------
   &amp;amp; =&amp;gt; 0000000000000000000000000000000 =&amp;gt; 0
---------------------------------------
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Here, we can say that &lt;code&gt;1&lt;/code&gt; is acting as a mask/bitmask. Therefore, &lt;code&gt;isOdd&lt;/code&gt; can be written as:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;function isOdd(x) {
  const mask = 1;
  return x &amp;amp; mask;
}
console.log(isOdd(5)); // 1
console.log(isOdd(4)); // 0
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;You can read more about bitmask &lt;a href=&quot;https://stackoverflow.com/questions/10493411/what-is-bit-masking&quot; rel=&quot;noreferrer noopener&quot; target=&quot;_blank&quot;&gt;here&lt;/a&gt;.&lt;/p&gt;
&lt;h2&gt;Tricks&lt;/h2&gt;
&lt;p&gt;Bitwise tricks feel like the &lt;em&gt;dark magic&lt;/em&gt; of computer programming 🔮. They are less intuitive and hard to understand. That&apos;s because they operate on binary, and binary is made for machines, not for humans. I&apos;ll do my best to explain each trick as simple as possible. Please feel free to correct/add if there&apos;s any gap.&lt;/p&gt;
&lt;p&gt;⚠️ &lt;em&gt;Tricks below are demonstrated only for learning purposes. One should vet them thoroughly before using them in a project. Also, these tricks might have integer overflow if there’s a need for more than 32-bits.&lt;/em&gt;&lt;/p&gt;
&lt;h3&gt;Truncate Integer&lt;/h3&gt;
&lt;pre&gt;&lt;code&gt;function truncate(x) {
  // Double tilde(~)
  return ~~x;
}
truncate(-1234.12); // -1234
truncate(1234.12); // 1234
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;The method above truncates the integer part of a number. It exploits the fact that JavaScript converts the operands of a bitwise operator into 32-bit signed integers in two’s complement format.&lt;/p&gt;
&lt;p&gt;You may want to use &lt;a href=&quot;https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/trunc&quot; target=&quot;_blank&quot; rel=&quot;noreferrer noopener&quot;&gt;Math.trunc()&lt;/a&gt; in your project.&lt;/p&gt;
&lt;h3&gt;Flip sign of an integer&lt;/h3&gt;
&lt;p&gt;For any integer &lt;em&gt;x&lt;/em&gt;, &lt;code&gt;~x&lt;/code&gt; yields &lt;code&gt;-(x + 1)&lt;/code&gt;. Therefore,&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;~x + 1 =&amp;gt; -(x + 1) + 1 =&amp;gt; -x - 1 + 1 =&amp;gt; -x
&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;function negate(x) {
  return ~x + 1;
}
&lt;/code&gt;&lt;/pre&gt;
&lt;h3&gt;Increment/decrement by 1&lt;/h3&gt;
&lt;pre&gt;&lt;code&gt;function add1(x) {
  // -~x =&amp;gt; -(-(x + 1)) =&amp;gt; x + 1
  return -~x;
}

function subtract1(x) {
  // ~-x =&amp;gt; -(-x + 1) =&amp;gt; x - 1
  return ~-x;
}
&lt;/code&gt;&lt;/pre&gt;
&lt;h3&gt;Swapping values&lt;/h3&gt;
&lt;p&gt;Values of two variables can be swapped using XOR operator.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;function swap(x, y) {
  x ^= y;
  y = x ^ y;
  x ^= y;
}
&lt;/code&gt;&lt;/pre&gt;
&lt;h3&gt;Power of two&lt;/h3&gt;
&lt;p&gt;If &lt;em&gt;x&lt;/em&gt; is a power of 2, then for &lt;em&gt;x - 1&lt;/em&gt; only the right most bits will be on. Therefore, ANDing &lt;em&gt;x&lt;/em&gt; with &lt;em&gt;x - 1&lt;/em&gt; will yield zero if &lt;em&gt;x&lt;/em&gt; is a power of 2. For example&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;      4  =&amp;gt; 00000000000000000000000000000100
  4 - 1  =&amp;gt; 00000000000000000000000000000011 =&amp;gt; 3
--------------------------------------------
    &amp;amp;    =&amp;gt; 00000000000000000000000000000000 =&amp;gt; 0
--------------------------------------------
&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;function isPowerOf2(x) {
  if (x === 0) {
    return false;
  }
  return (x &amp;amp; (x - 1)) === 0;
}

isPowerOf2(2); // true
isPowerOf2(3); // false
&lt;/code&gt;&lt;/pre&gt;
&lt;h3&gt;Absolute Value&lt;/h3&gt;
&lt;p&gt;Let&apos;s we want to find the absolute value of -5 &lt;em&gt;without branching&lt;/em&gt;. As we know, for any &lt;em&gt;x&lt;/em&gt;, &lt;code&gt;~x&lt;/code&gt; yields &lt;code&gt;-(x + 1)&lt;/code&gt;. So we can do &lt;code&gt;~(-5) + 1&lt;/code&gt; to get 5.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;   -5  =&amp;gt; 11111111111111111111111111111011
 ~(-5) =&amp;gt; 00000000000000000000000000000100
                                        +1
 -----------------------------------------
          00000000000000000000000000000101 =&amp;gt; 5
 -----------------------------------------
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;We need to negate the number and add 1 only when the the number is negative. We can use below algorithm:&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;Create a &lt;em&gt;bitmask&lt;/em&gt; for a number &lt;em&gt;x&lt;/em&gt; by &lt;code&gt;x &amp;gt;&amp;gt; 31&lt;/code&gt;. The bitmask will be zero for positive &lt;em&gt;x&lt;/em&gt; and -1 for negative &lt;em&gt;x&lt;/em&gt;.&lt;/li&gt;
&lt;/ol&gt;
&lt;pre&gt;&lt;code&gt; 5 &amp;gt;&amp;gt; 31 =&amp;gt; 00000000000000000000000000000000 =&amp;gt; 0
&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;-5 &amp;gt;&amp;gt; 31 =&amp;gt; 11111111111111111111111111111111 =&amp;gt; -1
&lt;/code&gt;&lt;/pre&gt;
&lt;ol&gt;
&lt;li&gt;XOR &lt;em&gt;bitmask&lt;/em&gt; with &lt;em&gt;x&lt;/em&gt; to find negation.&lt;/li&gt;
&lt;/ol&gt;
&lt;pre&gt;&lt;code&gt;x ^ 0 =&amp;gt; x
x ^ -1 =&amp;gt; ~x
&lt;/code&gt;&lt;/pre&gt;
&lt;ol&gt;
&lt;li&gt;Subtract &lt;em&gt;bitmask&lt;/em&gt;.&lt;/li&gt;
&lt;/ol&gt;
&lt;pre&gt;&lt;code&gt;(x ^ 0) - 0 =&amp;gt; x;
(x ^ -1) =&amp;gt; ~x - (-1) =&amp;gt; ~x + 1
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Above steps in JS code.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;function abs(x) {
  const mask = x &amp;gt;&amp;gt; 31;
  return (x ^ mask) - mask;
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;You may want to use &lt;a href=&quot;https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/abs&quot; target=&quot;_blank&quot; rel=&quot;noreferrer noopener&quot;&gt;Math.abs()&lt;/a&gt; in your project.&lt;/p&gt;
&lt;h3&gt;Division/Multiply by 2&lt;/h3&gt;
&lt;p&gt;Division/multiplication by 2 can be achieved by shifting left/right by 1 bit.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;function double(x) {
  return x &amp;lt;&amp;lt; 1;
}

function half(x) {
  return x &amp;gt;&amp;gt; 1;
}

double(5); // 10
half(10); // 5
&lt;/code&gt;&lt;/pre&gt;
&lt;h3&gt;Detect sign&lt;/h3&gt;
&lt;pre&gt;&lt;code&gt;function hasSameSign(x, y) {
  return (x ^ y) &amp;lt; 0;
}

hasSameSign(-1, 1); // false;
hasSameSign(-1, -2); // true;
hasSameSign(2, 1); // true
&lt;/code&gt;&lt;/pre&gt;
&lt;h3&gt;Min and max of two integers&lt;/h3&gt;
&lt;p&gt;We can find min and max of two integers using XOR and comparison operator. For integers &lt;em&gt;x&lt;/em&gt; and &lt;em&gt;y&lt;/em&gt;, expression &lt;code&gt;x &amp;lt; y&lt;/code&gt; evaluates to &lt;code&gt;1&lt;/code&gt; if x is greater, otherwise &lt;code&gt;0&lt;/code&gt; which means:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;when &lt;em&gt;x&lt;/em&gt; is greater.&lt;/li&gt;
&lt;/ul&gt;
&lt;pre&gt;&lt;code&gt;-(x &amp;lt; y) =&amp;gt; 0

// AND with 0.
(x ^ y) &amp;amp; -(x &amp;lt; y) =&amp;gt; (x ^ y) &amp;amp; 0 =&amp;gt; 0

// XOR with 0.
y ^ ((x ^ y) &amp;amp; -(x &amp;lt; y)) =&amp;gt; y ^ ((x ^ y) &amp;amp; 0)  =&amp;gt; y ^ 0 =&amp;gt; y
&lt;/code&gt;&lt;/pre&gt;
&lt;ul&gt;
&lt;li&gt;when &lt;em&gt;y&lt;/em&gt; is greater&lt;/li&gt;
&lt;/ul&gt;
&lt;pre&gt;&lt;code&gt;-(x &amp;lt; y) =&amp;gt; -1

// AND with -1.
(x ^ y) &amp;amp; -(x &amp;lt; y) =&amp;gt; (x ^ y) &amp;amp; (-1) =&amp;gt; x ^ y

// XOR with (x ^ y)
y ^ ((x ^ y) &amp;amp; -(x &amp;lt; y)) =&amp;gt; y ^ ((x ^ y) &amp;amp; (-1)) =&amp;gt; y ^ x ^ y =&amp;gt; x
&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;function min(x, y) {
  // If x is greater `mask` will be 0 otherwise -1
  const mask = -(x &amp;lt; y);

  return y ^ ((x ^ y) &amp;amp; mask);
}

function max(x, y) {
  // If x is greater `mask` will be 0 otherwise -1
  const mask = -(x &amp;lt; y);

  return x ^ ((x ^ y) &amp;amp; mask);
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Alternate method. It uses the right shift operator and the difference in numbers.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;function min(x, y) {
  // If x is greater `mask` will be 0 otherwise -1
  const mask = (x - y) &amp;gt;&amp;gt; 31;

  // (x - y) &amp;amp; 0 =&amp;gt; 0
  // (x - y) &amp;amp; -1 =&amp;gt; x - y
  return y + ((x - y) &amp;amp; mask);
}

function max(x, y) {
  // If x greater mask will be 0 otherwise -1
  const mask = (x - y) &amp;gt;&amp;gt; 31;

  // (x - y) &amp;amp; 0 =&amp;gt; 0
  // (x - y) &amp;amp; -1 =&amp;gt; x - y
  return x - ((x - y) &amp;amp; mask);
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;You may want to use &lt;a href=&quot;https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/min&quot; target=&quot;_blank&quot; rel=&quot;noreferrer noopener&quot;&gt;Math.min()&lt;/a&gt; and &lt;a href=&quot;https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/max&quot; target=&quot;_blank&quot; rel=&quot;noreferrer noopener&quot;&gt;Math.max()&lt;/a&gt; in your project.&lt;/p&gt;
&lt;h3&gt;Reverse bits of an unsinged integer&lt;/h3&gt;
&lt;pre&gt;&lt;code&gt;function reverseBits(number) {
  const size = 31; // 2&apos;s complement size.
  let result = 0;
  for (let i = 1; i &amp;lt;= 31; i += 1) {
    // Add the left most bit to `result`
    result |= number &amp;amp; 1;

    // Discard the added bit.
    number &amp;gt;&amp;gt;= i;

    // Make space for the new bit.
    result &amp;lt;&amp;lt;= 1;
  }
  return result;
}

console.log(reverseBits(1)); // -2147483648
&lt;/code&gt;&lt;/pre&gt;
&lt;h3&gt;RGB Values from color code&lt;/h3&gt;
&lt;pre&gt;&lt;code&gt;function hexToRgb(color) {
  const r = (color &amp;amp; 0xff0000) &amp;gt;&amp;gt;&amp;gt; 16;
  const g = (color &amp;amp; 0x00ff00) &amp;gt;&amp;gt;&amp;gt; 8;
  const b = color &amp;amp; 0x0000ff;
  return [r, g, b].join(&apos;, &apos;);
}

console.log(hexToRgb(0x010203)); // 1, 2, 3
&lt;/code&gt;&lt;/pre&gt;
&lt;h2&gt;Final Thoughts:&lt;/h2&gt;
&lt;p&gt;In a high-level language like JavaScript, bitwise operators are relatively &lt;a href=&quot;https://stackoverflow.com/questions/1523061/performance-of-bitwise-operators-in-javascript&quot; target=&quot;_blank&quot; rel=&quot;noreferrer noopener&quot;&gt;slow&lt;/a&gt;. The main reason for the slowness is the two&apos;s complement conversion of the operands. Also, bitwise operators take a toll on the legibility of the code. Their less intuitiveness creates mental overhead of decimal to binary conversion and vice versa. One should use them sparingly.&lt;/p&gt;
&lt;p&gt;Having said that, if the situation demands, don&apos;t hesitate to &lt;em&gt;shake some bits!&lt;/em&gt;&lt;/p&gt;
</content:encoded><category>JavaScript</category><category>Bitwise Operators</category><category>Binary</category></item><item><title>Building an Accordion with React Hooks.</title><link>https://smellycode.com/accordion-in-reactjs/</link><guid isPermaLink="false">https://smellycode.com/accordion-in-reactjs/</guid><description>A tutorial to build a reusable accordion component with React Hooks.</description><pubDate>Wed, 26 Feb 2020 10:09:19 GMT</pubDate><content:encoded>&lt;p&gt;According to &lt;a href=&quot;https://semantic-ui.com/modules/accordion.html&quot; target=&quot;_blank&quot; rel=&quot;noreferrer noopener&quot;&gt;Sematic UI&lt;/a&gt;, &lt;em&gt;an accordion allows users to toggle the display of sections of content&lt;/em&gt;. In this post, we&apos;ll build a highly reusable accordion component from scratch. We will use React and its hooks api.&lt;/p&gt;
&lt;figure class=&quot;text-center&quot;&gt;
&lt;p&gt;&lt;img src=&quot;https://smellycode.com/_astro/accordion-in-reactjs-cover-img.CELDbkyz.gif&quot; alt=&quot;Accordion Image&quot; /&gt;&lt;/p&gt;
  &lt;figcaption&gt;
    A sample accordion (
      &lt;a href=&quot;https://codesandbox.io/s/sample-accordion-ld0vm&quot; rel=&quot;noopener noreferrer&quot; target=&quot;_blank&quot;&gt;Codesandbox&lt;/a&gt;
      )
  &lt;/figcaption&gt;
&lt;/figure&gt;
&lt;p&gt;An accordion component can be broken-down in following components:&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;A toggle component to show and hide the content.&lt;/li&gt;
&lt;li&gt;A collapse component to wrap the content.&lt;/li&gt;
&lt;li&gt;And, a root component to glue everything.&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;Let&apos;s name the root component &lt;code&gt;&amp;lt;Accordion /&amp;gt;&lt;/code&gt;. &lt;code&gt;Accordion&lt;/code&gt; will be responsible for rendering its children with necessary data. It can be implemented using &lt;a href=&quot;https://reactjs.org/docs/render-props.html&quot; rel=&quot;noreferrer noopener&quot; target=&quot;_blank&quot;&gt;render props&lt;/a&gt; or &lt;a href=&quot;https://kentcdodds.com/blog/compound-components-with-react-hooks&quot; target=&quot;_blank&quot; rel=&quot;noreferrer noopener&quot;&gt;compound components&lt;/a&gt;. We&apos;ll use the compound component pattern because it makes &lt;code&gt;Accordion&lt;/code&gt; easy to reason about. Also, with the compound component pattern, our JSX is semantically more meaningful and beautiful 🙂.&lt;/p&gt;
&lt;p&gt;The sample accordion JSX.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;&amp;lt;Accordion&amp;gt;
  &amp;lt;Accordion.Toggle&amp;gt;Click Me&amp;lt;/Accordion.Toggle&amp;gt;
  &amp;lt;Accordion.Collapse&amp;gt;Some collapsable text&amp;lt;/Accordion.Collapse&amp;gt;
&amp;lt;/Accordion&amp;gt;
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Let&apos;s design each of the accordion components.&lt;/p&gt;
&lt;h3&gt;&amp;lt;Accordion /&amp;gt;&lt;/h3&gt;
&lt;p&gt;The &lt;code&gt;Accordion&lt;/code&gt; component acts as a container. The &lt;code&gt;element&lt;/code&gt; prop is used as the container element/component. The default value of the &lt;code&gt;element&lt;/code&gt; is set to &lt;code&gt;div&lt;/code&gt;. &lt;code&gt;Accordion&lt;/code&gt; also receives a few other props: &lt;code&gt;onToggle&lt;/code&gt;, &lt;code&gt;activeEventKey&lt;/code&gt;, etc.&lt;/p&gt;
&lt;p&gt;Note: &lt;a href=&quot;https://www.npmjs.com/package/prop-types&quot; target=&quot;_blank&quot; rel=&quot;noopener noreferrer&quot;&gt;PropTypes&lt;/a&gt; package is used for type checking.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;const Accordion = ({
  element: Component,
  activeEventKey,
  onToggle,
  children,
  ...otherProps
}) =&amp;gt; {
  return &amp;lt;Component {...otherProps}&amp;gt;{children}&amp;lt;/Component&amp;gt;;
};

Accordion.propTypes = {
  // Element or Component to be rendered as a parent for accordion.
  element: PropTypes.oneOfType([PropTypes.string, PropTypes.func]),

  // `eventKey` of the accordion/section which is active/open
  activeEventKey: PropTypes.oneOfType([PropTypes.string, PropTypes.number]),

  // onToggle callback. (eventKey) =&amp;gt; void
  onToggle: PropTypes.func
};

Accordion.defaultProps = {
  // default render as div
  element: &apos;div&apos;
};
&lt;/code&gt;&lt;/pre&gt;
&lt;h3&gt;&amp;lt;Accordion.Toggle /&amp;gt;&lt;/h3&gt;
&lt;p&gt;As the name suggests, &lt;code&gt;Accordion.Toggle&lt;/code&gt; toggles the content. It also receives the &lt;code&gt;element&lt;/code&gt; prop just like the &lt;code&gt;Accordion&lt;/code&gt; component. It takes an &lt;code&gt;eventKey&lt;/code&gt; prop mapped to a &lt;code&gt;Accordion.Collapse&lt;/code&gt; component.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;const Toggle = ({
  element: Component,
  eventKey,
  onClick,
  children,
  ...otherProps
}) =&amp;gt; {
  return &amp;lt;Component {...otherProps}&amp;gt;{children}&amp;lt;/Component&amp;gt;;
};

Toggle.propTypes = {
  // Element or Component to be rendered as a toggle.
  element: PropTypes.oneOfType([PropTypes.string, PropTypes.func]),

  // `eventKey` of the content to be controlled.
  eventKey: PropTypes.oneOfType([PropTypes.string, PropTypes.number])
};

Toggle.defaultProps = {
  element: &apos;div&apos;
};
&lt;/code&gt;&lt;/pre&gt;
&lt;h3&gt;&amp;lt;Accordion.Collapse /&amp;gt;&lt;/h3&gt;
&lt;p&gt;The &lt;code&gt;Accordion.Collapse&lt;/code&gt; component conditionally renders the content. Just like other components, it also receives an &lt;code&gt;element&lt;/code&gt; prop.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;const Collapse = ({
  element: Component,
  eventKey,
  children,
  ...otherProps
}) =&amp;gt; {
  return &amp;lt;Component {...otherProps}&amp;gt;{children}&amp;lt;/Component&amp;gt;;
};

Collapse.propTypes = {
  // Wrapper for target content.
  element: PropTypes.oneOfType([PropTypes.string, PropTypes.func]),

  // Event key for the content.
  eventKey: PropTypes.oneOfType([PropTypes.string, PropTypes.number])
};

Collapse.defaultProps = {
  element: &apos;div&apos;
};
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;We&apos;ll export both &lt;code&gt;Toggle&lt;/code&gt; and &lt;code&gt;Collapse&lt;/code&gt; with &lt;code&gt;Accordion&lt;/code&gt; namespace.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;// ...
// Accordion&apos;s code
// ...

Accordion.Toggle = Toggle;
Accordion.Collapse = Collapse;
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;We have laid out the foundation. Let&apos;s introduce other concepts.&lt;/p&gt;
&lt;h3&gt;useAccordionContext&lt;/h3&gt;
&lt;p&gt;Each accordion component needs some data from the &lt;code&gt;Accordion&lt;/code&gt; component. eg. &lt;code&gt;Accordion.Collapse&lt;/code&gt; needs to know the &lt;code&gt;activeEventKey&lt;/code&gt; to conditionally display content. &lt;code&gt;Accordion.Toggle&lt;/code&gt; needs to know the &lt;code&gt;activeEventKey&lt;/code&gt; to invoke the toggle callback with appropriate params.&lt;/p&gt;
&lt;p&gt;We can manually pass the data as &lt;code&gt;props&lt;/code&gt; to each accordion component. But that will require the knowledge of their positions in the &lt;code&gt;Accordion&lt;/code&gt; component tree. React provides a better alternative for such uses cases: &lt;a href=&quot;https://reactjs.org/docs/context.html&quot; rel=&quot;noopener noreferrer&quot; target=&quot;_blank&quot;&gt;React Context&lt;/a&gt;. Context APIs help us to &lt;em&gt;pass data through the component tree without having to pass props down manually at every level&lt;/em&gt;.&lt;/p&gt;
&lt;p&gt;Let&apos;s create a context for accordion.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;AccordionContext.js&lt;/strong&gt;&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;import React from &apos;react&apos;;

export default React.createContext(null);
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Hook to access the accordion context.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;import { useContext } from &apos;react&apos;;
import AccordionContext from &apos;../AccordionContext&apos;;

const useAccordionContext = () =&amp;gt; {
  const context = useContext(AccordionContext);
  if (!context) {
    throw new Error(
      &apos;Accordion components are compound component. Must be used inside Accordion.&apos;
    );
  }
  return context;
};

export default useAccordionContext;
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;code&gt;Accordion&lt;/code&gt; initializes the &lt;code&gt;AccordionContext&lt;/code&gt; with an &lt;code&gt;activeEventKey&lt;/code&gt; attribute and an &lt;code&gt;onToggle&lt;/code&gt; method.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;const Accordion = ({
  element: Component,
  activeEventKey,
  onToggle,
  children,
  ...otherProps
}) =&amp;gt; {
  const context = useMemo(() =&amp;gt; {
    return { activeEventKey, onToggle };
  }, [activeEventKey, onToggle]);

  return (
    &amp;lt;AccordionContext.Provider value={context}&amp;gt;
      &amp;lt;Component {...otherProps}&amp;gt;{children}&amp;lt;/Component&amp;gt;
    &amp;lt;/AccordionContext.Provider&amp;gt;
  );
};
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;code&gt;Accordion.Collapse&lt;/code&gt; reads the &lt;code&gt;activeEventKey&lt;/code&gt; from the context. It renders its content if &lt;code&gt;activeEventKey&lt;/code&gt; equals to &lt;code&gt;eventKey&lt;/code&gt;.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;import { useAccordionContext } from &apos;../hooks&apos;;

const Collapse = ({
  element: Component,
  eventKey,
  children,
  ...otherProps
}) =&amp;gt; {
  const { activeEventKey } = useAccordionContext();

  return activeEventKey === eventKey ? (
    &amp;lt;Component {...otherProps}&amp;gt;{children}&amp;lt;/Component&amp;gt;
  ) : null;
};
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;code&gt;Accordion.Toggle&lt;/code&gt; invokes the &lt;code&gt;onToggle&lt;/code&gt; function from context on click of the toggle component/element.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;import { useAccordionContext } from &apos;../hooks&apos;;

const useAccordionClick = (eventKey, onClick) =&amp;gt; {
  const { onToggle, activeEventKey } = useAccordionContext();
  return event =&amp;gt; {
    onToggle(eventKey === activeEventKey ? null : eventKey);

    if (onClick) {
      onClick(event);
    }
  };
};

const Toggle = ({
  element: Component,
  eventKey,
  onClick,
  children,
  ...otherProps
}) =&amp;gt; {
  const accordionClick = useAccordionClick(eventKey, onClick);

  return (
    &amp;lt;Component onClick={accordionClick} {...otherProps}&amp;gt;
      {children}
    &amp;lt;/Component&amp;gt;
  );
};
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;After plugging everything together in &lt;code&gt;App&lt;/code&gt; with a &lt;code&gt;Card&lt;/code&gt; component:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;import Accordion from &apos;./Accordion&apos;;

import Card from &apos;./Card&apos;;

const content = [
  // items in {question, answer} format
  // ...
  // ...
];

export default function App() {
  const [activeEventKey, setActiveEventKey] = useState(0);

  return (
    &amp;lt;div className=&quot;App&quot;&amp;gt;
      &amp;lt;Accordion activeEventKey={activeEventKey} onToggle={setActiveEventKey}&amp;gt;
        {content.map(({ question, answer }, index) =&amp;gt; (
          &amp;lt;Card key={index}&amp;gt;
            &amp;lt;Accordion.Toggle element={Card.Header} eventKey={index}&amp;gt;
              {question}
              {activeEventKey !== index &amp;amp;&amp;amp; &amp;lt;span&amp;gt;👇🏻&amp;lt;/span&amp;gt;}
              {activeEventKey === index &amp;amp;&amp;amp; &amp;lt;span&amp;gt;👆🏻&amp;lt;/span&amp;gt;}
            &amp;lt;/Accordion.Toggle&amp;gt;
            &amp;lt;Accordion.Collapse eventKey={index} element={Card.Body}&amp;gt;
              {answer}
            &amp;lt;/Accordion.Collapse&amp;gt;
          &amp;lt;/Card&amp;gt;
        ))}
      &amp;lt;/Accordion&amp;gt;
    &amp;lt;/div&amp;gt;
  );
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;▶ &lt;a href=&quot;https://codesandbox.io/s/sample-accordion-ld0vm?codemirror=1&amp;amp;fontsize=14&amp;amp;hidenavigation=1&amp;amp;theme=dark&amp;amp;view=preview&quot; rel=&quot;noopener&quot;&gt;sample-accordion&lt;/a&gt;&lt;/p&gt;
&lt;hr /&gt;
&lt;h3&gt;Controllability&lt;/h3&gt;
&lt;p&gt;The &lt;code&gt;Accordion&lt;/code&gt; component is a &lt;a href=&quot;https://reactjs.org/docs/forms.html#controlled-components&quot; rel=&quot;noopener noreferrer&quot; target=&quot;_blank&quot;&gt;controlled component&lt;/a&gt;. It doesn&apos;t own any state. It receives needed data as props(eg. active section key &lt;code&gt;activeEventKey&lt;/code&gt;, toggle handler &lt;code&gt;onToggle&lt;/code&gt;, etc). The controlled nature of &lt;code&gt;Accordion&lt;/code&gt; makes it very flexible but it has a downside. Consumer components have to explicitly manage their &lt;code&gt;Accordion&lt;/code&gt;&apos;s state even when they don&apos;t need it. Explicit state management can be tedious sometimes and may cause boilerplate.&lt;/p&gt;
&lt;p&gt;We&apos;ll add uncontrolled behavior to the accordion. In real-world apps, you might want to use &lt;a href=&quot;https://github.com/jquense/uncontrollable&quot; target=&quot;_blank&quot; rel=&quot;noreferrer noopener&quot;&gt;uncontrollable&lt;/a&gt;.&lt;/p&gt;
&lt;p&gt;To make &lt;code&gt;Accordion&lt;/code&gt; uncontrollable/controllable, we&apos;ll introduce a local state in the accordion. We&apos;ll keep it in sync with &lt;code&gt;activeEventKey&lt;/code&gt; prop. We&apos;ll use &lt;a href=&quot;https://reactjs.org/docs/hooks-reference.html#uselayouteffect&quot; target=&quot;_blank&quot; rel=&quot;noopener noreferrer&quot;&gt;useLayoutEffect&lt;/a&gt; instead of &lt;a href=&quot;https://reactjs.org/docs/hooks-reference.html#useeffect&quot; target=&quot;_blank&quot; rel=&quot;noopener noreferrer&quot;&gt;useEffect&lt;/a&gt; for syncing to avoid flickering(&lt;a href=&quot;https://kentcdodds.com/blog/useeffect-vs-uselayouteffect&quot; target=&quot;_blank&quot;&gt;useEffect vs useLayoutEffect&lt;/a&gt;).&lt;/p&gt;
&lt;p&gt;Enhanced &lt;code&gt;Accordion&lt;/code&gt; component with local state.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;const useEventKey = (eventKey, onToggle) =&amp;gt; {
  const [activeEventKey, setActiveEventKey] = useState(eventKey);

  useLayoutEffect(() =&amp;gt; {
    setActiveEventKey(eventKey);
  }, [eventKey, onToggle]);

  return [activeEventKey, setActiveEventKey];
};

const Accordion = ({
  element: Component,
  activeEventKey,
  onToggle,
  children,
  ...otherProps
}) =&amp;gt; {
  const [eventKey, setEventKey] = useEventKey(activeEventKey, onToggle);

  const handleToggle = useCallback(
    eventKey =&amp;gt; {
      if (activeEventKey !== undefined) {
        onToggle(eventKey);
        return;
      }
      setEventKey(eventKey);
    },
    [activeEventKey, onToggle, setEventKey]
  );

  const context = useMemo(() =&amp;gt; {
    return {
      activeEventKey: eventKey,
      onToggle: handleToggle
    };
  }, [eventKey, handleToggle]);

  return (
    &amp;lt;AccordionContext.Provider value={context}&amp;gt;
      &amp;lt;Component {...otherProps}&amp;gt;{children}&amp;lt;/Component&amp;gt;
    &amp;lt;/AccordionContext.Provider&amp;gt;
  );
};

Accordion.defaultProps = {
  // default render as div
  element: &apos;div&apos;,

  onToggle: () =&amp;gt; {}
};
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Finally, &lt;code&gt;App&lt;/code&gt; component with both controlled and uncontrolled forms of the &lt;code&gt;Accordion&lt;/code&gt;.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;export default function App() {
  const [activeEventKey, setActiveEventKey] = useState(0);
  return (
    &amp;lt;div className=&quot;App&quot;&amp;gt;
      &amp;lt;h3&amp;gt;Uncontrolled Accordion&amp;lt;/h3&amp;gt;
      &amp;lt;Accordion&amp;gt;
        {content.map(({ question, answer }, index) =&amp;gt; (
          &amp;lt;Card key={index}&amp;gt;
            &amp;lt;Accordion.Toggle element={Card.Header} eventKey={index}&amp;gt;
              {index + 1}. {question}
            &amp;lt;/Accordion.Toggle&amp;gt;
            &amp;lt;Accordion.Collapse eventKey={index} element={Card.Body}&amp;gt;
              {answer}
            &amp;lt;/Accordion.Collapse&amp;gt;
          &amp;lt;/Card&amp;gt;
        ))}
      &amp;lt;/Accordion&amp;gt;

      &amp;lt;h3&amp;gt;Controlled Accordion&amp;lt;/h3&amp;gt;
      &amp;lt;Accordion activeEventKey={activeEventKey} onToggle={setActiveEventKey}&amp;gt;
        {content.map(({ question, answer }, index) =&amp;gt; (
          &amp;lt;Card key={index}&amp;gt;
            &amp;lt;Accordion.Toggle element={Card.Header} eventKey={index}&amp;gt;
              {index + 1}. {question}
              {activeEventKey !== index &amp;amp;&amp;amp; &amp;lt;span&amp;gt;👇🏻&amp;lt;/span&amp;gt;}
              {activeEventKey === index &amp;amp;&amp;amp; &amp;lt;span&amp;gt;👆🏻&amp;lt;/span&amp;gt;}
            &amp;lt;/Accordion.Toggle&amp;gt;
            &amp;lt;Accordion.Collapse eventKey={index} element={Card.Body}&amp;gt;
              {answer}
            &amp;lt;/Accordion.Collapse&amp;gt;
          &amp;lt;/Card&amp;gt;
        ))}
      &amp;lt;/Accordion&amp;gt;
    &amp;lt;/div&amp;gt;
  );
}
&lt;/code&gt;&lt;/pre&gt;
&lt;hr /&gt;

&lt;p&gt;Thanks for the reading 🙏🏻.&lt;/p&gt;
</content:encoded><category>ReactJs</category></item><item><title>Variable Scope in Catch Block ~ JavaScript</title><link>https://smellycode.com/catch-block-varible-scope/</link><guid isPermaLink="false">https://smellycode.com/catch-block-varible-scope/</guid><description>A quick write up about variable scope in catch block.</description><pubDate>Fri, 02 Aug 2019 08:41:36 GMT</pubDate><content:encoded>&lt;p&gt;Variable scope and hoisting are notorious in JavaScript land. Both newbies and seasoned programmers have difficulties to wrap their head around these when they encounter certain quirks. A few weeks ago, Kyle Simpson &lt;a href=&quot;https://twitter.com/getify/status/1150686674139189248&quot; target=&quot;_blank&quot; rel=&quot;noreferrer noopener&quot;&gt;tweeted&lt;/a&gt; below code snippet with TIL caption.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;function foo() {
  &apos;use strict&apos;;
  err = 1;
  try {
    throw &apos;hello&apos;;
  } catch (err) {
    console.log(err);
    var err = 2;
  }
  console.log(err);
}
foo();
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;When I interpreted the code, I concluded the output below.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;hello
2
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Sadly my &lt;em&gt;interpretation&lt;/em&gt; was incorrect. The actual output is.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;hello
1
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;The enigma of variables within the catch block made me curious to take a gander at the &lt;a href=&quot;https://www.ecma-international.org/ecma-262/10.0/index.html#sec-variablestatements-in-catch-blocks&quot;&gt;spec&lt;/a&gt;. I found this note:&lt;/p&gt;
&lt;blockquote&gt;
&lt;p&gt;The Block of a Catch clause may contain &lt;strong&gt;var declarations that bind a name that is also bound by the CatchParameter&lt;/strong&gt;. At runtime, such bindings are instantiated in the &lt;strong&gt;VariableDeclarationEnvironment&lt;/strong&gt;. &lt;strong&gt;They do not shadow the same-named bindings introduced by the CatchParameter&lt;/strong&gt; and hence the &lt;strong&gt;Initializer for such var declarations will assign to the corresponding catch parameter rather than the var binding&lt;/strong&gt;.&lt;/p&gt;
&lt;/blockquote&gt;
&lt;p&gt;In simple words, the catch parameter is block-scoped--can not be accessed outside the block. And, it overrides/shadows variables with the same name.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;function foo() {
  &apos;use strict&apos;;
  try {
    throw &apos;hello&apos;;
  } catch (err) {
    console.log(err); // hello
  }
  // `err` block scoped. Does not exist outside the catch block.
  console.log(err); // throws `err` is not defined.
}
foo();
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Since the catch parameter overrides variables with the same name in the current execution context--enclosing function or global context--any initializer for the catch parameter does not affect those variables.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;function foo() {
  let err = 0;
  try {
    throw &apos;hello&apos;;
  } catch (err) {
    console.log(err);
    err = 10;
  }
  console.log(err);
}

foo();
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Of course, if we declare a block scope variable same as catch parameter inside the catch block, then Js will complain.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;function foo() {
  try {
    throw &apos;hello&apos;;
  } catch (err) {
    console.log(err);
    let err = 2; // will throw an error.
  }
  console.log(err);
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Declarations with &lt;code&gt;var&lt;/code&gt; are not block-scoped and hoisted to the top of the function. Also, JavaScript is more forgiving towards re-declaration of variables with &lt;code&gt;var&lt;/code&gt;. That&apos;s why no error is raised even in the &apos;strict&apos; mode.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;function foo() {
  &apos;use strict&apos;;
  err = 1;
  try {
    throw &apos;hello&apos;;
  } catch (err) {
    console.log(err); // hello
    var err = 2;
  }
  console.log(err); // 1
}
foo();
&lt;/code&gt;&lt;/pre&gt;
</content:encoded><category>JavaScript</category></item><item><title>Component Glossary 📖</title><link>https://smellycode.com/component-glossary/</link><guid isPermaLink="false">https://smellycode.com/component-glossary/</guid><description>Explanation of various types of components with words and code.</description><pubDate>Tue, 25 Jun 2019 12:59:23 GMT</pubDate><content:encoded>&lt;p&gt;&lt;img src=&quot;https://smellycode.com/_astro/component-glossary-cover-img.DQFQzZXY.jpeg&quot; alt=&quot;&quot; /&gt;&lt;/p&gt;
&lt;p&gt;Components are basic building blocks of modern web applications. They help web developers to break complex user interfaces into independent smaller blocks or pieces which can be reused and plugged with other pieces or components as is. In general a component is&lt;/p&gt;
&lt;blockquote&gt;
&lt;p&gt;&quot;a part or element of a larger whole, especially a part of a machine or vehicle.&quot; ~ &lt;a href=&quot;https://www.google.com/search?rlz=1C5CHFA_enIN836IN837&amp;amp;ei=stAJXdmCIsX1vgSa7YmYDA&amp;amp;q=define%3Acomponent&amp;amp;oq=define%3Acomponent&amp;amp;gs_l=psy-ab.3...126435.129603..129948...3.0..0.165.2102.7j12......0....1..gws-wiz.......0i71j0i67j35i39.a9m9W10kFE8&quot; target=&quot;_blank&quot;&gt;Google&lt;/a&gt;&lt;/p&gt;
&lt;/blockquote&gt;
&lt;p&gt;This article explains various types of components with words and code.&lt;/p&gt;
&lt;h3&gt;Function Components&lt;/h3&gt;
&lt;p&gt;Function Components are JavaScript functions which take inputs known as &lt;em&gt;props&lt;/em&gt; and returns a &lt;a href=&quot;https://reactjs.org/docs/rendering-elements.html&quot; target=&quot;_blank&quot;&gt;React Element&lt;/a&gt; as output. Here&apos;s a simple &lt;code&gt;Greetings&lt;/code&gt; function component to greet.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;function Greetings(props) {
  return &amp;lt;h1&amp;gt;Hello {props.name}&amp;lt;/h1&amp;gt;;
}

// With arrow function
// const Greetings = props =&amp;gt; &amp;lt;h1&amp;gt;Hello {props.name}&amp;lt;/h1&amp;gt;;
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;People often mix up function components with &quot;Functional Components&quot;. &lt;strong&gt;Every component is a functional component if it is functioning or working fine&lt;/strong&gt;. 😀&lt;/p&gt;
&lt;p&gt;React does not &lt;a href=&quot;https://javascript.info/constructor-new&quot; target=&quot;_blank&quot;&gt;instantiate&lt;/a&gt; function components. It means they can not be accessed with the &lt;a href=&quot;https://reactjs.org/docs/refs-and-the-dom.html&quot; target=&quot;_blank&quot;&gt;ref attribute&lt;/a&gt;. Lack of instantiation also makes the &lt;a href=&quot;https://reactjs.org/docs/state-and-lifecycle.html#adding-lifecycle-methods-to-a-class&quot; target=&quot;_blank&quot;&gt;life-cycle hooks&lt;/a&gt; inaccessible to function components.&lt;/p&gt;
&lt;p&gt;Function components don&apos;t have any state unless they are &lt;a href=&quot;https://reactjs.org/docs/hooks-intro.html&quot;&gt;hooked&lt;/a&gt;.&lt;/p&gt;
&lt;h3&gt;&lt;a name=&quot;classComponents&quot;&gt;&lt;/a&gt; Class Components&lt;/h3&gt;
&lt;p&gt;Components created with &lt;a href=&quot;https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes&quot; target=&quot;_blank&quot;&gt;ES6 Classes&lt;/a&gt; are known as &lt;em&gt;Class Components&lt;/em&gt;. Class components extend the base class &lt;a href=&quot;https://reactjs.org/docs/react-component.html&quot; target=&quot;_blank&quot;&gt;React.Component&lt;/a&gt;. Unlike function components, class components can have state and access the life-cycle methods. Class Components define a &lt;code&gt;render&lt;/code&gt; method which returns a react element as output. Here&apos;s a simple &lt;code&gt;Clock&lt;/code&gt; component to display time.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;class Clock extends React.Component {
  state = { now: new Date() };

  intervalId = null;

  updateTime = () =&amp;gt; this.setState({ now: new Date() });

  componentDidMount() {
    this.intervalId = setInterval(() =&amp;gt; this.updateTime(), 1000);
  }

  componentWillUnmount() {
    clearInterval(this.intervalId);
  }

  render() {
    return &amp;lt;p&amp;gt;{this.state.now.toLocaleTimeString({}, { hour12: true })}&amp;lt;/p&amp;gt;;
  }
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Instances of class components can be accessed with the &lt;em&gt;ref attribute&lt;/em&gt;.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;class App extends React.Component {
  clockRef = React.createRef();

  componentDidMount() {
    // instance of the clock component
    console.log(this.clockRef.current);
  }

  render() {
    return &amp;lt;Clock ref={this.clockRef} /&amp;gt;;
  }
}
&lt;/code&gt;&lt;/pre&gt;
&lt;h3&gt;Pure Components&lt;/h3&gt;
&lt;p&gt;Let&apos;s discuss a simple &lt;code&gt;Greetings&lt;/code&gt; &lt;a href=&quot;https://reactjs.org/docs/react-component.html&quot; target=&quot;_blank&quot;&gt;React.Component&lt;/a&gt; first.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;class Greetings extends React.Component {
  render() {
    console.count(&apos;Greetings --&amp;gt; render&apos;);
    return &amp;lt;p&amp;gt;Hello {this.props.name}!&amp;lt;/p&amp;gt;;
  }
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;It greets with a &lt;code&gt;name&lt;/code&gt; passed as props. An additional &lt;a href=&quot;https://developer.mozilla.org/en-US/docs/Web/API/Console/count&quot; target=&quot;_blank&quot;&gt;console.count&lt;/a&gt; statement is added to &lt;code&gt;render&lt;/code&gt; method to count executions.&lt;/p&gt;
&lt;p&gt;The &lt;code&gt;App&lt;/code&gt; component below takes &lt;code&gt;name&lt;/code&gt; from a form input control and passes it to the &lt;code&gt;Greetings&lt;/code&gt; component.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;class App extends React.Component {
  state = { name: &apos;Sheldon&apos;, text: &apos;&apos; };

  handleChange = event =&amp;gt; {
    this.setState({ text: event.target.value });
  };

  handleSubmit = event =&amp;gt; {
    event.preventDefault();
    this.setState({ text: &apos;&apos;, name: this.state.text });
  };

  render() {
    return (
      &amp;lt;div&amp;gt;
        &amp;lt;form onSubmit={this.handleSubmit}&amp;gt;
          &amp;lt;input
            type=&quot;text&quot;
            value={this.state.text}
            required
            onChange={this.handleChange}
          /&amp;gt;
          &amp;lt;input type=&quot;submit&quot; value=&quot;Greet&quot; /&amp;gt;
        &amp;lt;/form&amp;gt;
        &amp;lt;Greetings name={this.state.name} /&amp;gt;
      &amp;lt;/div&amp;gt;
    );
  }
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;When a user interacts with the input control, it updates the state of the &lt;code&gt;App&lt;/code&gt; component. React invokes the &lt;code&gt;render&lt;/code&gt; method--with the updated state and props--of the &lt;code&gt;App&lt;/code&gt; component and &lt;em&gt;its children&lt;/em&gt; to &lt;a href=&quot;https://reactjs.org/docs/reconciliation.html&quot; target=&quot;_blank&quot;&gt;create a new React Element tree for diffing&lt;/a&gt;. Although, the state and props of the &lt;code&gt;Greetings&lt;/code&gt; component are not changed, still React calls the &lt;code&gt;render&lt;/code&gt; method of the &lt;code&gt;Greetings&lt;/code&gt; component.&lt;/p&gt;
&lt;p&gt;In large applications, such &lt;strong&gt;unnecessary executions of &lt;code&gt;render&lt;/code&gt; methods create performance issues and bog down user interfaces&lt;/strong&gt;. The &lt;a href=&quot;https://reactjs.org/docs/react-component.html#shouldcomponentupdate&quot;&gt;&lt;em&gt;shouldComponentUpdate&lt;/em&gt;&lt;/a&gt; life-cycle method is used to avoid these unnecessary re-renderings of the component. By default, &lt;code&gt;shouldComponentUpdate&lt;/code&gt; return true, but its implementation can be easily overridden. Let&apos;s override &lt;code&gt;shouldComponentUpdate&lt;/code&gt; for the &lt;code&gt;Greetings&lt;/code&gt; component.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;class Greetings extends React.Component {
  shouldComponentUpdate(nextProps) {
    // Re-render only when the `name` prop changes.
    return this.props.name !== nextProps.name;
  }

  render() {
    console.count(&apos;Greetings --&amp;gt; render&apos;);
    return &amp;lt;p&amp;gt;Hello {this.props.name}!&amp;lt;/p&amp;gt;;
  }
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;After the very first render, &lt;code&gt;Greetings&lt;/code&gt; component is re-rendered only when the &lt;code&gt;name&lt;/code&gt; prop changes.&lt;/p&gt;
&lt;p&gt;To solve the same problem, React introduces a variant of React.Component called &lt;a href=&quot;https://reactjs.org/docs/react-api.html#reactpurecomponent&quot; target=&quot;_blank&quot;&gt;React.PureComponent&lt;/a&gt; which implicitly implements &lt;code&gt;shouldComponentUpdate&lt;/code&gt;. &lt;strong&gt;The implicit implementation compares props and state by reference(shallow comparison)&lt;/strong&gt;. Let&apos;s write the pure version of &lt;code&gt;Greetings&lt;/code&gt;.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;class PureGreetings extends React.PureComponent {
  render() {
    console.count(&apos;Pure Greetings --&amp;gt; render&apos;);
    return &amp;lt;span&amp;gt;Hello {this.props.name}!&amp;lt;/span&amp;gt;;
  }
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Here&apos;s the &lt;a href=&quot;https://codepen.io/smellycode/pen/QXgjzq?editors=0010&quot; target=&quot;_blank&quot;&gt;pen&lt;/a&gt; with full code.&lt;/p&gt;
&lt;h3&gt;Controlled/Uncontrolled Components&lt;/h3&gt;
&lt;p&gt;Working with form elements is a tad tedious. It requires a lot of malarky to get data from the form elements. That&apos;s because form elements maintain their own state internally. Developers have to throw a few lines to JavaScript to get the job done. Form elements in React are no exception. The way developers deal with a form element determines whether that element is a &lt;em&gt;Controlled or Uncontrolled&lt;/em&gt; Element/Component. If the value of a form element is controlled by React then it&apos;s called a &quot;Controlled Component&quot; otherwise &quot;Uncontrolled Component&quot;.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Controlled Components don&apos;t change their state on user interaction&lt;/strong&gt;. State changes happen only when the parent component decides eg. the &lt;code&gt;SubscriptionForm&lt;/code&gt; component below doesn&apos;t honor user inputs (&lt;a href=&quot;https://codepen.io/smellycode/pen/LKbEoX?editors=0010&quot; target=&quot;_blank&quot;&gt;Codepen&lt;/a&gt;).&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;class SubscriptionForm extends React.Component {
  handleSubmit = event =&amp;gt; {
    event.preventDefault();
  };
  render() {
    return (
      &amp;lt;form onSubmit={this.handleSubmit}&amp;gt;
        &amp;lt;input type=&quot;email&quot; value=&quot;smelly@smellycode.com&quot; /&amp;gt;
        &amp;lt;input type=&quot;submit&quot; value=&quot;Subscribe&quot; /&amp;gt;
      &amp;lt;/form&amp;gt;
    );
  }
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;em&gt;Why changes are not honored?&lt;/em&gt; That&apos;s because the &lt;code&gt;value&lt;/code&gt; attribute for the email input is set to &lt;code&gt;smelly@smellycode.com&lt;/code&gt;. When React runs &lt;a href=&quot;https://reactjs.org/docs/reconciliation.html&quot; target=&quot;_blank&quot;&gt;the diffing algorithm&lt;/a&gt; on the render tree. It always gets the email input as &lt;code&gt;smelly@smellycode.com&lt;/code&gt; so it ends up rendering the same value regardless of inputs entered by the user. Let&apos;s fix it by setting up an event listener which will update the state on &lt;code&gt;change&lt;/code&gt; event(&lt;a href=&quot;https://codepen.io/smellycode/pen/wLoKRR?editors=0010&quot; target=&quot;_blank&quot;&gt;Codepen&lt;/a&gt;).&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;class SubscriptionForm extends React.Component {
  state = { email: &apos;&apos; };

  handleSubmit = event =&amp;gt; {
    event.preventDefault();
    console.log(&apos;Values --&amp;gt; &apos;, this.state);
  };

  handleChange = event =&amp;gt; this.setState({ email: event.target.value });

  render() {
    return (
      &amp;lt;form onSubmit={this.handleSubmit}&amp;gt;
        &amp;lt;input
          type=&quot;email&quot;
          value={this.state.email}
          onChange={this.handleChange}
        /&amp;gt;
        &amp;lt;input type=&quot;submit&quot; value=&quot;Subscribe&quot; /&amp;gt;
      &amp;lt;/form&amp;gt;
    );
  }
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Everything that goes into the input form elements is controlled by React here. That&apos;s why it is called &quot;Controlled Component&quot;.&lt;/p&gt;
&lt;p&gt;For &quot;Uncontrolled Component&quot;, form data is not handled by React. DOM takes care of them. Here&apos;s an uncontrolled version of the &lt;code&gt;SubscriptionForm&lt;/code&gt;.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;class SubscriptionForm extends React.Component {
  inputRef = React.createRef();

  handleSubmit = event =&amp;gt; {
    event.preventDefault();
    console.log(&apos;Value --&amp;gt;&apos;, this.inputRef.current.value);
  };

  render() {
    return (
      &amp;lt;form onSubmit={this.handleSubmit}&amp;gt;
        &amp;lt;input type=&quot;email&quot; ref={this.inputRef} /&amp;gt;
        &amp;lt;input type=&quot;submit&quot; value=&quot;Subscribe&quot; /&amp;gt;
      &amp;lt;/form&amp;gt;
    );
  }
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;For elaborative comparison please refer &lt;a href=&quot;https://goshakkk.name/controlled-vs-uncontrolled-inputs-react/&quot; target=&quot;_blank&quot;&gt;the article&lt;/a&gt;.&lt;/p&gt;
&lt;h3&gt;Higher Order Components&lt;/h3&gt;
&lt;p&gt;Suppose there&apos;s an application which has a few malformed components--&lt;em&gt;components whose elements/children are invalid react elements&lt;/em&gt;. Rendering of these components breaks the user interface.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;// A sample malformed component.
class MalformedComponent extends React.Component {
  render() {
    // {new Date()} is not a valid react element. Rendering it will throw an error.
    return &amp;lt;p&amp;gt;Now:{new Date()}&amp;lt;/p&amp;gt;;
  }
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;We need to implement an error handling mechanism to avoid crashes. React provides &lt;a href=&quot;https://reactjs.org/docs/error-boundaries.html&quot; target=&quot;_blank&quot;&gt;error boundary apis&lt;/a&gt; to handle such errors. So we refactor &lt;code&gt;MalformedComponent&lt;/code&gt; as:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;class MalformedComponent extends React.Component {
  state = {
    error: null
  };

  static getDerivedStateFromError(error) {
    // Update state so the next render will show the fallback UI.
    return { error };
  }

  render() {
    if (this.state.error) {
      return (
        &amp;lt;details&amp;gt;
          &amp;lt;summary&amp;gt;Ouch! Things are messed up. We are sorry. 👾&amp;lt;/summary&amp;gt;
          &amp;lt;pre style={{ color: `red` }}&amp;gt;{this.state.error.stack}&amp;lt;/pre&amp;gt;
        &amp;lt;/details&amp;gt;
      );
    }
    return &amp;lt;WrappedComponent {...this.props} /&amp;gt;;
  }
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Adding error boundaries only fixes the &lt;code&gt;MalformedComponent&lt;/code&gt;. We need to fix the other components too, means we need to add error boundaries to other components.&lt;/p&gt;
&lt;p&gt;&lt;em&gt;How do we do it?&lt;/em&gt; Hmm, One way is to add the error handling code in every malformed component the way we did above. But it will make our component a bit cumbersome to maintain and less DRY.&lt;/p&gt;
&lt;p&gt;&lt;em&gt;What if we write a function to fill in the error handling code?&lt;/em&gt; Well, we can write but we &lt;em&gt;shouldn&apos;t&lt;/em&gt; because we&apos;ll be modifying the existing component which is not recommended and may lead to unexpected behavior.&lt;/p&gt;
&lt;p&gt;&lt;em&gt;What if we write a function which takes a malformed component and returns a new component which wraps the malformed component with error boundaries?&lt;/em&gt; Interesting! Only thing is, it will add a new wrapper component in our component tree, but we can live with it. Let&apos;s code it.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;const withErrorBoundaries = WrappedComponent =&amp;gt; props =&amp;gt; {
  return class extends React.Component {
    state = {
      error: null
    };

    static getDerivedStateFromError(error) {
      // Update state so the next render will show the fallback UI.
      return { error };
    }

    render() {
      if (this.state.error) {
        // Fallback ui.
        return (
          &amp;lt;details&amp;gt;
            &amp;lt;summary&amp;gt;Ouch! Things are messed up. We are sorry. 👾&amp;lt;/summary&amp;gt;
            &amp;lt;pre style={{ color: `red` }}&amp;gt;{this.state.error.stack}&amp;lt;/pre&amp;gt;
          &amp;lt;/details&amp;gt;
        );
      }
      return &amp;lt;WrappedComponent {...this.props} /&amp;gt;;
    }
  };
};
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;code&gt;withErrorBoundaries&lt;/code&gt; can be used with any malformed component.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;const SafeComponent = withErrorBoundaries(MalformedComponent);
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;▶ &lt;a href=&quot;https://codepen.io/smellycode/pen/mZMPBL/?height=265&amp;amp;theme-id=dark&amp;amp;default-tab=result&quot; rel=&quot;noopener&quot;&gt;Higher Order Component Example&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;That&apos;s what precisely a higher order component is all about. It&apos;s a pattern which facilitates component logic reusability. You can think of a HOC as &lt;strong&gt;a function that takes a component and returns a new component&lt;/strong&gt;. An in-depth explanation of HOCs is available &lt;a href=&quot;https://reactjs.org/docs/higher-order-components.html&quot; target=&quot;_blank&quot;&gt;here&lt;/a&gt;.&lt;/p&gt;
&lt;h3&gt;Dumb Components&lt;/h3&gt;
&lt;p&gt;Dumb components are also known as &lt;em&gt;presentational&lt;/em&gt; or &lt;em&gt;stateless&lt;/em&gt; components. They mostly contain HTML and styles. The purpose of dumb components is to &lt;strong&gt;render the DOM using &lt;em&gt;props&lt;/em&gt;&lt;/strong&gt;. Dumb Components don&apos;t load or mutate any data. Data required by dumb components are passed as input/props along with the actions. That&apos;s why dumb components don&apos;t have any state related to data. It makes them more reusable and manageable. Here is a very basic &lt;code&gt;Greetings&lt;/code&gt; dumb component :&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;function Greetings(props) {
  return &amp;lt;h1&amp;gt;Hello {props.name}&amp;lt;/h1&amp;gt;;
}
&lt;/code&gt;&lt;/pre&gt;
&lt;h3&gt;Smart/Container Components&lt;/h3&gt;
&lt;p&gt;Smart components are also known as &lt;em&gt;Container Components&lt;/em&gt;. Smart Components know how to load and mutate data. Sometimes smart components mere act as a container and pass data to child components as props. Smart Components can also have state and logic to update the state. A simple &lt;code&gt;Clock&lt;/code&gt; component with state and logic.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;class Clock extends React.Component {
  state = { now: new Date() };

  intervalId = null;

  tick = () =&amp;gt; this.setState({ now: new Date() });

  componentDidMount() {
    this.intervalId = setInterval(() =&amp;gt; this.tick(), 1000);
  }

  componentWillUnmount() {
    clearInterval(this.intervalId);
  }

  render() {
    return &amp;lt;p&amp;gt;{this.state.now.toLocaleTimeString()}&amp;lt;/p&amp;gt;;
  }
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;You can read more about &lt;a href=&quot;https://www.shade.codes/dumb-components-and-smart-components/&quot; target=&quot;_blank&quot;&gt;Dumb Components and Smart components on Shade.codes&lt;/a&gt;.&lt;/p&gt;
</content:encoded><category>ReactJs</category><category>Almanac</category></item><item><title>CSRF in Action 🎭</title><link>https://smellycode.com/csrf-in-action/</link><guid isPermaLink="false">https://smellycode.com/csrf-in-action/</guid><description>Demonstration of Cross Site Request Forgery(CSRF) with a simple todo app.</description><pubDate>Mon, 10 Jun 2019 10:09:19 GMT</pubDate><content:encoded>&lt;p&gt;&lt;a href=&quot;https://en.wikipedia.org/wiki/Cross-site_request_forgery&quot; target=&quot;_blank&quot;&gt;Cross-Site Request Forgery(CSRF/XSRF)&lt;/a&gt; is one of the most popular ways of exploiting a server. It attacks the server by forcing the client to perform an unwanted action. This attack targets applications where the client/user is already logged in. It mainly changes the state of the server by making inadvertent updates or transfer of data. For example, updating vital information like emails contact numbers, etc. or transferring data from one entity to another.&lt;/p&gt;
&lt;p&gt;&lt;img src=&quot;https://smellycode.com/_astro/csrf-in-action-cover-img.b-6GTMxQ.jpeg&quot; alt=&quot;&quot; /&gt;&lt;/p&gt;
&lt;p&gt;This post demonstrates CSRF attack and elaborates concepts linger around it. It uses a simple todo app and an evil client--which updates the state of todos--for demonstration. Technologies used:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;a href=&quot;https://reactjs.org/&quot; target=&quot;_blank&quot;&gt;ReactJs&lt;/a&gt; for client.&lt;/li&gt;
&lt;li&gt;&lt;a href=&quot;https://expressjs.com/&quot; target=&quot;_blank&quot; rel=&quot;noreferrer noopener&quot;&gt;ExpressJs&lt;/a&gt; and a couple of middlewares(&lt;a href=&quot;https://github.com/expressjs/cors&quot; target=&quot;_blank&quot; rel=&quot;noreferrer noopener&quot;&gt;CORS&lt;/a&gt;, &lt;a href=&quot;https://github.com/expressjs/body-parser&quot; target=&quot;_blank&quot; rel=&quot;noreferrer noopener&quot;&gt;body-parser&lt;/a&gt;, &lt;a href=&quot;https://github.com/expressjs/cookie-parser&quot; target=&quot;_blank&quot; rel=&quot;noreferrer noopener&quot;&gt;cookie-parser&lt;/a&gt;, etc) for server.&lt;/li&gt;
&lt;li&gt;&lt;a href=&quot;https://www.mongodb.com/&quot; target=&quot;_blank&quot; rel=&quot;noreferrer noopener&quot;&gt;MongoDb&lt;/a&gt; as database and &lt;a href=&quot;https://mongoosejs.com/&quot; target=&quot;_blank&quot; rel=&quot;noreferrer noopener&quot;&gt;Mongoose&lt;/a&gt; for data modeling.&lt;/li&gt;
&lt;li&gt;&lt;a href=&quot;https://jwt.io/&quot; target=&quot;_blank&quot; rel=&quot;noreferrer noopener&quot;&gt;JWT&lt;/a&gt; for stateless session management.&lt;/li&gt;
&lt;li&gt;and a few other stuff.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;The sample todo app uses JSON Web Token for stateless session management and authentication. It stores the token in a cookie with &lt;code&gt;httpOnly&lt;/code&gt; flag to make the token &lt;a href=&quot;https://developer.mozilla.org/en-US/docs/Web/HTTP/Cookies#Secure_and_HttpOnly_cookies&quot;&gt;inaccessible to the JavaScript running on the client&lt;/a&gt;. Picture below depicts the auth flow of the app&lt;a name=&quot;basicAuthFlow&quot;&gt;&lt;/a&gt;.&lt;/p&gt;
&lt;p&gt;&lt;img src=&quot;https://smellycode.com/_astro/basic-auth-flow.C_V3TJBn.jpg&quot; alt=&quot;App auth flow without CSRF token&quot; /&gt;&lt;/p&gt;
&lt;p&gt;Let&apos;s take a gander at the code organization of the app. The &lt;a href=&quot;https://github.com/hk-skit/csrf-in-action&quot; target=&quot;_blank&quot;&gt;codebase&lt;/a&gt; has three actors -- a server, a client, and an evil client.&lt;/p&gt;
&lt;p&gt;The &lt;strong&gt;server&lt;/strong&gt; exposes a few endpoints for CRUD operations on both user(&lt;code&gt;/users&lt;/code&gt;) and todo(&lt;code&gt;/todos&lt;/code&gt;). It uses &lt;strong&gt;mongoose&lt;/strong&gt; to store data in &lt;strong&gt;MongoDB&lt;/strong&gt;. It also supports &lt;a href=&quot;https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS&quot; target=&quot;_blank&quot;&gt;cross-origin requests&lt;/a&gt; from a client running at &lt;code&gt;localhost:3001&lt;/code&gt;(middleware &lt;a href=&quot;https://github.com/expressjs/cors&quot; target=&quot;_blank&quot;&gt;cors&lt;/a&gt; is used to enable cross-origin resource sharing). The server runs at &lt;a href=&quot;http://localhost:3000&quot;&gt;http://localhost:3000&lt;/a&gt;.&lt;/p&gt;
&lt;p&gt;The &lt;strong&gt;client&lt;/strong&gt; has a simple &lt;em&gt;login form&lt;/em&gt; and a &lt;em&gt;todo list&lt;/em&gt;. It uses ReactJs to build the UI and &lt;a href=&quot;https://github.com/axios/axios&quot; target=&quot;_blank&quot;&gt;axios&lt;/a&gt; for ajax calls. When the client is loaded, it fetches todos(GET, &lt;code&gt;/todos&lt;/code&gt;) of the logged in user. If there&apos;s an authentication error(status code is 401), it directs the user to login. Todos are successfully fetched only when the user is logged in.&lt;/p&gt;
&lt;p&gt;&lt;img src=&quot;https://smellycode.com/_astro/sample-todo-app.BMrKJJK0.gif&quot; alt=&quot;Simple todo app in action&quot; /&gt;&lt;/p&gt;
&lt;p&gt;The &lt;strong&gt;evil client&lt;/strong&gt; runs at &lt;a href=&quot;http://locahost:3002&quot;&gt;http://locahost:3002&lt;/a&gt; with the help of the package &lt;a href=&quot;https://www.npmjs.com/package/http-server&quot; target=&quot;_blank&quot;&gt;http-server&lt;/a&gt;. It has a plain HTML page and a &lt;em&gt;form&lt;/em&gt;. The form opens its action in a hidden &lt;em&gt;iframe&lt;/em&gt; for &lt;a href=&quot;https://stackoverflow.com/questions/17940811/example-of-silently-submitting-a-post-form-csrf&quot; target=&quot;_blank&quot; rel=&quot;noreferrer noopener&quot;&gt;silent submission&lt;/a&gt;. The app lures the user to click on a button which stimulates the form submission. Form submission makes a &lt;strong&gt;post&lt;/strong&gt; call to &lt;a href=&quot;http://localhost:3000/todos/complete&quot;&gt;http://localhost:3000/todos/complete&lt;/a&gt; which marks todos belonging to the logged in user as complete.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;&amp;lt;!DOCTYPE html&amp;gt;
&amp;lt;html&amp;gt;
  &amp;lt;body&amp;gt;
    &amp;lt;h1&amp;gt;Hey There!&amp;lt;/h1&amp;gt;
    &amp;lt;p
      &amp;gt;Having a rough day! Don&apos;t worry, I have got a picture of a cute cat to
      cheer you up. &amp;lt;button id=&quot;btn_cat&quot;&amp;gt;Show me 🐱&amp;lt;/button&amp;gt;
    &amp;lt;/p&amp;gt;
    &amp;lt;iframe style=&quot;display:none&quot; name=&quot;csrf-frame&quot;&amp;gt;&amp;lt;/iframe&amp;gt;
    &amp;lt;form
      method=&quot;POST&quot;
      action=&quot;http://localhost:3000/todos/complete&quot;
      target=&quot;csrf-frame&quot;
      id=&quot;csrf-form&quot;
    &amp;gt;
    &amp;lt;/form&amp;gt;
    &amp;lt;script type=&quot;text/javascript&quot;&amp;gt;
      document.getElementById(&apos;btn_cat&apos;).addEventListener(&apos;click&apos;, () =&amp;gt; {
        document.getElementById(&apos;csrf-form&apos;).submit();
      });
    &amp;lt;/script&amp;gt;
  &amp;lt;/body&amp;gt;
&amp;lt;/html&amp;gt;
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Evil client in action:&lt;/p&gt;
&lt;p&gt;&lt;img src=&quot;https://smellycode.com/_astro/evil-client-in-action.KgHX4Ohz.gif&quot; alt=&quot;Evil client in action&quot; /&gt;&lt;/p&gt;
&lt;p&gt;Let&apos;s address questions which create confusion.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Q: Why no authentication error?&lt;/strong&gt; 🤔&lt;/p&gt;
&lt;p&gt;The server does not throw any authentication error cause the request contains a valid JWT token. The request gets the token from cookies.&lt;/p&gt;
&lt;blockquote&gt;
&lt;p&gt;When receiving an HTTP request, a server can send a &lt;code&gt;Set-Cookie&lt;/code&gt; header with the response. The cookie is usually stored by the browser, and then the cookie is sent with requests made to the same server inside a &lt;code&gt;Cookie&lt;/code&gt; HTTP header. ~ &lt;a href=&quot;https://developer.mozilla.org/en-US/docs/Web/HTTP/Cookies&quot;&gt;Mozila&lt;/a&gt;&lt;/p&gt;
&lt;/blockquote&gt;
&lt;p&gt;When the user logs in, the JWT is stored in an &lt;code&gt;httpOnly&lt;/code&gt; cookie(see &lt;a href=&quot;https://smellycode.com/csrf-in-action/#basicAuthFlow&quot;&gt;auth flow&lt;/a&gt;). &lt;em&gt;Cookies are sent with every request to the same server&lt;/em&gt;. Because of that, the JWT becomes part of every request 🤖.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Q: Shouldn&apos;t the CORS setup help here?&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;Let&apos;s talk about &lt;a href=&quot;https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS&quot; target=&quot;_blank&quot;&gt;CORS&lt;/a&gt; before jumping to the answer. Browsers limit the interaction of scripts or document loaded on one origin(a tuple of protocol, domain, and port) with another origin to avoid Jungle Raj. The mechanism used for imposing such limitations is known as &lt;a href=&quot;https://developer.mozilla.org/en-US/docs/Web/Security/Same-origin_policy&quot;&gt;Same Origin Policy&lt;/a&gt;. It ensures that applications are running in isolated environments. Sometimes, developers need to relax the same-origin policy so that applications can interact with each other. That&apos;s what originates the idea of &lt;strong&gt;C&lt;/strong&gt;ross-&lt;strong&gt;O&lt;/strong&gt;rigin &lt;strong&gt;R&lt;/strong&gt;esource &lt;strong&gt;S&lt;/strong&gt;haring(CORS). CORS allows &lt;code&gt;site-a&lt;/code&gt; to interact with &lt;code&gt;site-b&lt;/code&gt; only if &lt;code&gt;site-b&lt;/code&gt; agrees--by responding with appropriate HTTP headers. To enable CORS, the server needs a tad of work(the sample todo app uses &lt;a href=&quot;https://github.com/expressjs/cors&quot; target=&quot;_blank&quot;&gt;cors&lt;/a&gt; middleware for the same).&lt;/p&gt;
&lt;p&gt;In the browser world, ajax requests are classified into three categories:&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;Simple Request&lt;/li&gt;
&lt;li&gt;Non-simple request&lt;/li&gt;
&lt;li&gt;Preflight request ✈️.&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;More details on these can be found &lt;a href=&quot;https://frontendian.co/cors&quot; target=&quot;_blank&quot;&gt;here&lt;/a&gt;.&lt;/p&gt;
&lt;p&gt;Whenever a cross-origin resource is requested using a non-simple request, the browser makes a pre-flight &lt;code&gt;OPTIONS&lt;/code&gt; request. The server responds to the pre-flight request with appropriate response headers. If the origin and the request method are present in &lt;code&gt;Access-Control-Allow-Origin&lt;/code&gt; and &lt;code&gt;Access-Control-Allow-Methods&lt;/code&gt;, the browser originates the main request. Otherwise, a cors error is thrown with a pertinent message.&lt;/p&gt;
&lt;p&gt;&lt;img src=&quot;https://smellycode.com/_astro/preflight_.BwnfUzAt.png&quot; alt=&quot;Preflight request&quot; /&gt;&lt;/p&gt;
&lt;p&gt;Network logs of the todo app with preflight requests.&lt;/p&gt;
&lt;p&gt;&lt;img src=&quot;https://smellycode.com/_astro/prefligh_request_logs.JXPcTims.png&quot; alt=&quot;Network logs of preflight request&quot; /&gt;&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;For simple requests, the browser doesn&apos;t intiate any preflgiht request.&lt;/strong&gt; The malicious client leverages this fact to bypass the Same Origin Policy with the help of an HTML form. That&apos;s why CORS set up doesn&apos;t help here 🤯.&lt;/p&gt;
&lt;p&gt;&lt;img src=&quot;https://smellycode.com/_astro/simple_req.AGKbAoNI.png&quot; alt=&quot;simple request&quot; /&gt;&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Q: What if WebStorage is used to store JWT instead of httpOnly cookie?&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;Storing JWT in the &lt;a href=&quot;https://developer.mozilla.org/en-US/docs/Web/API/Web_Storage_API&quot; target=&quot;_blank&quot;&gt;Web Storage&lt;/a&gt; will make the app less vulnerable for CSRF attacks. But it spikes the chances of the token being compromised. That&apos;s because any JavaScript running on the client has access to the web storage. It&apos;s DANGEROUS 🛑.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Q: How to prevent CSRF?&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;The challenge for the server is to validate both the token and the source of the request i.e. origin. The token validation is already implemented. The server needs to verify the source of the request for CSRF protection. The source can either be verified with the help of &lt;strong&gt;CORS Origin Header&lt;/strong&gt; or an &lt;strong&gt;XSRF Token&lt;/strong&gt;. Shielding server with XSRF token(CSRF token) is more reliable and popular than &lt;a href=&quot;https://stackoverflow.com/questions/24680302/csrf-protection-with-cors-origin-header-vs-csrf-token&quot; target=&quot;_blank&quot;&gt;CORS Origin Header&lt;/a&gt;.&lt;/p&gt;
&lt;p&gt;The implementation of the XSRF token is straight forward. When the client represents valid credentials, the server generates a random unguessable unique string named as &lt;code&gt;xsrfToken&lt;/code&gt;. It puts the &lt;code&gt;xsrfToken&lt;/code&gt; in JWT along with other claims. The server also adds an &lt;code&gt;xsrfToken&lt;/code&gt; in a cookie(why cookie? cause &lt;em&gt;cookies are limited by same-origin policy&lt;/em&gt;). Here&apos;s a sample JWT payload with &lt;code&gt;xsrfToken&lt;/code&gt;:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;{
  &quot;sub&quot;: &quot;hk&quot;,
  &quot;xsrfToken&quot;: &quot;cjwt3tcmt00056tnvcfvnh4n1&quot;,
  &quot;iat&quot;: 1560336079
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;The client reads the token from cookies and adds the token to request headers as &lt;code&gt;X-XSRF-TOKEN&lt;/code&gt; before making requests. When the server receives a request, it reads &lt;code&gt;xsrfToken&lt;/code&gt; from JWT payload and compares with the &lt;code&gt;X-XSRF-TOKEN&lt;/code&gt; header. If both are same then the request is further processed otherwise it is terminated with status code 401. This technique is also known as &lt;strong&gt;Double Submit Cookies&lt;/strong&gt; method.&lt;/p&gt;
&lt;p&gt;The auth flow with XSRF token:&lt;/p&gt;
&lt;p&gt;&lt;img src=&quot;https://smellycode.com/_astro/auth-flow-csrf.SZtXtzKl.jpg&quot; alt=&quot;JWT auth flow with CSRF&quot; /&gt;&lt;/p&gt;
&lt;p&gt;Code version of the same with &lt;a href=&quot;https://github.com/auth0/express-jwt&quot; target=&quot;_blank&quot;&gt;express-jwt&lt;/a&gt;:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;const expressJwt = require(&apos;express-jwt&apos;);

// Paths without token.
const publicRoutes = [&apos;/users/register&apos;, &apos;/users/authenticate&apos;];

const isRevoked = async (req, payload, done) =&amp;gt; {
  const { xsrfToken } = payload;
  done(null, xsrfToken !== req.get(&apos;X-XSRF-TOKEN&apos;));
};

module.exports = () =&amp;gt;
  expressJwt({
    secret: process.env.JWT_SECRET,

    getToken: req =&amp;gt;
      req.get(&apos;X-XSRF-TOKEN&apos;) &amp;amp;&amp;amp; req.cookies.jwtToken
        ? req.cookies.jwtToken
        : null,
    isRevoked
  }).unless({
    path: publicRoutes
  });
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Client side request interceptor with &lt;a href=&quot;https://github.com/axios/axios&quot; target=&quot;_blank&quot;&gt;axios&lt;/a&gt;:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;import axios from &apos;axios&apos;;

const getCookies = () =&amp;gt;
  document.cookie.split(&apos;;&apos;).reduce((cookies, item) =&amp;gt; {
    const [name, value] = item.split(&apos;=&apos;);
    cookies[name] = value;
    return cookies;
  }, {});

const baseURL = &apos;http://localhost:3000&apos;;

const ajax = axios.create({
  baseURL,
  timeout: 5000,
  withCredentials: true
});

// Add a request interceptor
ajax.interceptors.request.use(function(config) {
  const xsrfToken = getCookies()[&apos;xsrfToken&apos;];
  // CSRF Token.
  if (xsrfToken) config.headers[&apos;X-XSRF-TOKEN&apos;] = xsrfToken;
  return config;
});

export default ajax;
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Note: &lt;em&gt;Real-world applications require a more elegant mechanism for handling CSRF tokens. You may want to use the middleware &lt;a href=&quot;https://github.com/expressjs/csurf&quot; target=&quot;_blank&quot;&gt;csurf&lt;/a&gt;&lt;/em&gt;.&lt;/p&gt;
&lt;p&gt;The evil client after CSRF token:&lt;/p&gt;
&lt;p&gt;&lt;img src=&quot;https://smellycode.com/_astro/evil-client-after-csrf.DtgRDHnp.gif&quot; alt=&quot;Evil client after CSRF token&quot; /&gt;&lt;/p&gt;
&lt;p&gt;The final code of the sample app is uploaded &lt;a href=&quot;https://github.com/hk-skit/csrf-in-action&quot; target=&quot;_blank&quot;&gt;here&lt;/a&gt;. Thanks for reading 🙏🏻.&lt;/p&gt;
</content:encoded><category>CSRF</category><category>NodeJs</category><category>CORS</category><category>Express</category><category>JWT</category><category>JavaScript</category></item><item><title>NodeJs with(out) Express ~ Part 1</title><link>https://smellycode.com/node-express-part1/</link><guid isPermaLink="false">https://smellycode.com/node-express-part1/</guid><description>Peeling the layers of abstraction wrt NodeJs and Express.</description><pubDate>Mon, 27 May 2019 08:24:05 GMT</pubDate><content:encoded>&lt;p&gt;Learning a new tech stack is always challenging. It requires patience and a right set of materials. Material which not only scratches the surface but also helps people with relevant references to level up their skills. A few weeks ago, I started exploring NodeJs to learn server-side programming. I wanted to understand the underlying mechanics of basic stuff like authentication, session management, HTTP transactions, etc. So I googled keywords like &lt;em&gt;&quot;How to implement authentication in NodeJs&quot;&lt;/em&gt;, &lt;em&gt;&quot;Session Management in NodeJs&quot;&lt;/em&gt;, &lt;em&gt;&quot;Handle post request in NodeJs&quot;&lt;/em&gt;, etc. A large number of articles/links appeared respective to each of these. They all were using one framework or another. Most of them were using &lt;a href=&quot;https://expressjs.com/&quot; target=&quot;_blank&quot; rel=&quot;noopener noreferrer&quot;&gt;Express&lt;/a&gt;. I was looking for stuff with plain NodeJs. So I &lt;a href=&quot;https://twitter.com/_smellycode/status/1130368949575491584&quot; target=&quot;_blank&quot; rel=&quot;noreferrer noopener&quot;&gt;asked people&lt;/a&gt; if there&apos;s any source available which implements such stuff without any framework. I didn&apos;t get any response. So I decided to peel the layers of abstraction by myself and write one. This series of articles is all about how one can implement things without using any framework. It will parallelly demonstrate certain implementations in ExpressJs. Let&apos;s get started with a basic HTTP server and a few HTTP transactions.&lt;/p&gt;
&lt;h3&gt;HTTP Server&lt;/h3&gt;
&lt;p&gt;NodeJs has a native &lt;code&gt;http&lt;/code&gt; &lt;a href=&quot;https://nodejs.org/docs/latest-v9.x/api/http.html&quot; target=&quot;_blank&quot;&gt;module&lt;/a&gt; to create an HTTP server. It also provides modules for other protocols like &lt;a href=&quot;https://nodejs.org/docs/latest-v9.x/api/dgram.html&quot; target=&quot;_blank&quot;&gt;UDP&lt;/a&gt;(&lt;code&gt;dgram&lt;/code&gt;). For brevity, throughout this series we&apos;ll stick to HTTP. Here&apos;s a simple HTTP node server.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;// Importing http module to create a server.
const http = require(&apos;http&apos;);

// Host for our server.
const HOST = &apos;localhost&apos;;

// Port at which our server will run/listen.
const PORT = 3000;

// Creating a server with handler.
const server = http.createServer((req, res) =&amp;gt; {
  res.statusCode = 200;
  res.setHeader(&apos;Content-Type&apos;, &apos;text/plain&apos;);
  res.end(&apos;Hello Stranger!!&apos;);
});

// Setup server at PORT.
server.listen(PORT, HOST, () =&amp;gt; {
  console.log(`Server is running at http://${HOST}:${PORT}`);
});
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;To create a server, we have used the &lt;code&gt;http.createServer&lt;/code&gt; api with a request handler. After creating a server instance, we set it up to port &lt;code&gt;3000&lt;/code&gt; with hostname &lt;code&gt;localhost&lt;/code&gt;. All the request made to &lt;code&gt;localhost:3000&lt;/code&gt; will be handled by our server. The job of request handler is to receive and process the incoming requests and respond with appropriate data or message(s). In the snippet above, the request handler sets the status code to &lt;code&gt;200&lt;/code&gt; and sends &lt;code&gt;Hello Stranger!!&lt;/code&gt; greeting as plain text.&lt;/p&gt;
&lt;p&gt;Express version of the above snippet:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;// Importing express module.
const express = require(&apos;express&apos;);

// Port at which our server will listen.
const PORT = 3001;

// Creating an express app.
const app = express();

// Setting up request handler also known as middleware
app.use((req, res) =&amp;gt; {
  res.statusCode = 200;
  res.setHeader(&apos;Conent-Type&apos;, &apos;text/plain&apos;);
  res.send(&apos;Hello Stranger!!&apos;);
});

// Setup server at PORT.
app.listen(PORT, () =&amp;gt; {
  console.log(`Server is running at ${PORT}`);
});
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Express version more or less looks same as the native version. But a lot is happening under the hood. We&apos;ll keep peeking as we move forward. At this point, express has abstracted the server creation for us.&lt;/p&gt;
&lt;p&gt;Snapshot of the source code of &lt;code&gt;app.listen&lt;/code&gt; taken from the &lt;a href=&quot;https://github.com/expressjs/express/blob/master/lib/application.js#L616&quot; target=&quot;_blank&quot; rel=&quot;noreferrer noopener&quot;&gt;repo&lt;/a&gt;:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;app.listen = function listen() {
  var server = http.createServer(this);
  return server.listen.apply(server, arguments);
};
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;It has also introduces a new way of registering handlers/middlewares using &lt;code&gt;app.use&lt;/code&gt;. Middleware is basically a function which gets invoked with &lt;code&gt;request&lt;/code&gt;, &lt;code&gt;response&lt;/code&gt; and &lt;code&gt;next&lt;/code&gt; arguments in request-response cycle. You can read more on middlewares &lt;a href=&quot;https://expressjs.com/en/guide/writing-middleware.html&quot; target=&quot;_blank&quot;&gt;here&lt;/a&gt;.&lt;/p&gt;
&lt;p&gt;Here&apos;s the link for the &lt;a href=&quot;https://github.com/hk-skit/node-with-express/tree/master/part1&quot; rel=&quot;noreferrer noopener&quot; target=&quot;_blank&quot;&gt;repo&lt;/a&gt;, if you want to play with the code.&lt;/p&gt;
&lt;h3&gt;HTTP Transaction&lt;/h3&gt;
&lt;p&gt;Any call made by a client to a server with HTTP protocol is considered as &lt;a href=&quot;http://www.cs.cmu.edu/~aist/www_paper/transaction.html&quot;&gt;HTTP transaction&lt;/a&gt;. HTTP has various transaction types--widely known as &lt;a href=&quot;https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods&quot;&gt;HTTP Methods&lt;/a&gt;.&lt;/p&gt;
&lt;p&gt;When a server receives a request, it calls the request handler with &lt;code&gt;request&lt;/code&gt; and &lt;code&gt;response&lt;/code&gt; parameters.&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;
&lt;p&gt;&lt;code&gt;request&lt;/code&gt; is an instance of &lt;a href=&quot;https://nodejs.org/api/http.html#http_class_http_incomingmessage&quot; target=&quot;_blank&quot;&gt;IncomingMessage&lt;/a&gt; which is a &lt;code&gt;ReadableStream&lt;/code&gt;. It has all the neccessary inforamtion like method, url, path, parameter, etc.&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;&lt;code&gt;response&lt;/code&gt; is an instance of &lt;a href=&quot;https://nodejs.org/api/http.html#http_class_http_serverresponse&quot; target=&quot;_blank&quot;&gt;ServerResponse&lt;/a&gt; which is a &lt;code&gt;WritableStream&lt;/code&gt;. It helps us to send data back to the client.&lt;/p&gt;
&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;Let&apos;s quickly introduce a &lt;code&gt;/greet&lt;/code&gt; endpoint which will take a query param &lt;code&gt;name&lt;/code&gt; and return a greeting. eg. hitting &lt;code&gt;/greet?name=Sheldon&lt;/code&gt; will return &lt;code&gt;Hello Sheldon!!&lt;/code&gt;.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;//... other require statements.
const url = require(&apos;url&apos;);

// ...necessary variable decalrations
// ............

// Request handler for /greet end point.
const handleGreetRequest = (req, res) =&amp;gt; {
  const { method, url: reqUrl } = req;
  const urlParts = url.parse(reqUrl, true);
  if (method === &apos;GET&apos;) {
    const { query: queryParams } = urlParts;
    res.end(`Hello ${queryParams.name || &apos;Stranger&apos;}!`);
  } else {
    res.statusCode = 404;
    res.end(&apos;Not found.&apos;);
  }
};

// Generic request handler.
const onRequest = (req, res) =&amp;gt; {
  if (req.url.startsWith(&apos;/greet&apos;)) {
    handleGreetRequest(req, res);
  } else {
    res.statusCode = 404;
    res.end(&apos;Not found.&apos;);
  }
};

// Creating a server with handler.
const server = http.createServer(onRequest);

// ... server setup code
// ...............
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;We have defined the request handler as &lt;code&gt;onRequest&lt;/code&gt; function. It invokes the respective request handler depending on the URL. If the URL doesn&apos;t match to any handler then 404 is sent to the client. &lt;code&gt;onRequest&lt;/code&gt; function hands over requests made with &lt;code&gt;/greet&lt;/code&gt; endpoint to &lt;code&gt;handleGreetRequest&lt;/code&gt; function. &lt;code&gt;handleGreetRequest&lt;/code&gt; parses the url--using &lt;a href=&quot;https://nodejs.org/api/url.html&quot;&gt;url&lt;/a&gt; module--to get query params, creates a greeting with the value of &lt;code&gt;name&lt;/code&gt; param in query and sends it to the client. The full code for the above snippet can be found &lt;a href=&quot;https://github.com/hk-skit/node-with-express/blob/master/part1/simple-server-greet-api.js&quot; target=&quot;_blank&quot;&gt;here&lt;/a&gt;.&lt;/p&gt;
&lt;p&gt;Let&apos;s introduce another endpoint called &lt;code&gt;/echo&lt;/code&gt;. It will be POST call which will send the request body as is back to the client .&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;// .... require statements and some other declaration statements
// ........

const handleEchoRequest = (req, res) =&amp;gt; {
  if (req.method === &apos;POST&apos;) {
    let body = [];
    req
      .on(&apos;data&apos;, chunk =&amp;gt; {
        body.push(chunk);
      })
      .on(&apos;end&apos;, () =&amp;gt; {
        body = Buffer.concat(body);
        res.end(body);
      });
  } else {
    res.statusCode = 404;
    res.end(&apos;Not found.&apos;);
  }
};

const onRequest = (req, res) =&amp;gt; {
  if (req.url.startsWith(&apos;/echo&apos;)) {
    handleEchoRequest(req, res);
  } else {
    res.statusCode = 404;
    res.end(&apos;Not found.&apos;);
  }
};

// Creating a server with handler.
const server = http.createServer(onRequest);

// ... server setup code
// ...............
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;As we know that &lt;a href=&quot;https://developer.mozilla.org/en-US/docs/Learn/Getting_started_with_the_web/How_the_Web_works#Packets_explained&quot; target=&quot;_blank&quot;&gt;data are transferred as packages or chunks&lt;/a&gt; over the network, so we must set up an accumulator which collects the data as soon as they arrive. That&apos;s why we have set up a &lt;code&gt;data&lt;/code&gt; event listener which pushes chunks to &lt;code&gt;body&lt;/code&gt; array. We&apos;ve also added an &lt;code&gt;end&lt;/code&gt; event listener which gets triggered when all chunks are received. Here we collate chunks and send back to the client.&lt;/p&gt;
&lt;p&gt;If you look at the above snippets you might realize that we are doing so many other things instead of focusing on the core logic of endpoints. Also, the retrieval of data from the request is a tad tedious. That&apos;s why ExpressJs and many other frameworks/modules have got a lot of traction because they remove the clutter and let developers focus on core business logics.&lt;/p&gt;
&lt;p&gt;Let&apos;s write both &lt;code&gt;/greet&lt;/code&gt; and &lt;code&gt;/echo&lt;/code&gt; endpoint using Express.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;const express = require(&apos;express&apos;);
const bodyParser = require(&apos;body-parser&apos;);

const PORT = 3001;

const app = express();

app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());

app.get(&apos;/greet&apos;, (req, res) =&amp;gt; {
  const {
    query: { name }
  } = req;
  res.send(`Hello ${name || &apos;Stranger&apos;}!`);
});

app.post(&apos;/echo&apos;, (req, res) =&amp;gt; {
  res.send(req.body);
});

// Setup server at PORT.
app.listen(PORT, () =&amp;gt; {
  console.log(`Server is running at ${PORT}`);
});
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Express version looks much cleaner because has abstracted the nitty gritty of HTTP transactions and exposed apis relevant to HTTP methods. We have also used a &lt;a href=&quot;https://www.npmjs.com/package/body-parser&quot; target=&quot;_blank&quot;&gt;body-parser&lt;/a&gt; module which acts as a &lt;a href=&quot;https://expressjs.com/en/guide/writing-middleware.html&quot; target=&quot;_blank&quot;&gt;middleware&lt;/a&gt; to accumulates data from the request and make them available as &lt;code&gt;request.body&lt;/code&gt; to subsequent middlewares.&lt;/p&gt;
&lt;h3&gt;Conclusion&lt;/h3&gt;
&lt;p&gt;Creating applications with plain NodeJs requires a little extra effort cause we directly deal with native apis. Sometimes, it can be a bit overwhelming and tedious. Frameworks like ExpressJs remove these pain points and help us write applications in a more elegant way with seamless development experience. But it is also important to be familiar with things lying under the hood. So that frameworks can be leveraged!&lt;/p&gt;
</content:encoded><category>NodeJs</category><category>Express</category><category>JavaScript</category></item><item><title>React starter kit for Chrome Extensions with Live Reloading 🤓</title><link>https://smellycode.com/chrome-extension-live-reloading-with-react/</link><guid isPermaLink="false">https://smellycode.com/chrome-extension-live-reloading-with-react/</guid><description>I didn&apos;t find a react starter kit for chrome extensions which provides live reloading. So I created one 🙂.</description><pubDate>Tue, 07 May 2019 15:54:15 GMT</pubDate><content:encoded>&lt;p&gt;&lt;a href=&quot;https://twitter.com/ossia/status/993856509632303105&quot; target=&quot;_blank&quot; rel=&quot;noreferrer noopener&quot;&gt;Software is eating the world. And JavaScript is eating software&lt;/a&gt;. Chrome extensions are not an exception here. They are also built using JavaScript. A few days ago, I got an opportunity to work on a small side project which needed a chrome extension. Since I am new to ReactJs and want to tame it, so I decided to build the desired extension with it. Before I narrate the whole story, let&apos;s take a gander on how one develops a chrome extension.&lt;/p&gt;
&lt;h3&gt;Chrome extension overview&lt;/h3&gt;
&lt;p&gt;Every chrome extension starts with a &lt;code&gt;manifest.json&lt;/code&gt; file which provides an overview of the &lt;a target=&quot;_blank&quot; rel=&quot;noreferrer noopener&quot; href=&quot;https://developer.chrome.com/apps/permission_warnings&quot;&gt;permissions&lt;/a&gt;, &lt;a target=&quot;_blank&quot; rel=&quot;noreferrer noopener&quot; href=&quot;https://developer.chrome.com/extensions/background_pages&quot;&gt;background scripts&lt;/a&gt;, &lt;a href=&quot;https://developer.chrome.com/content_scripts.html&quot; target=&quot;_blank&quot; rel=&quot;noreferrer noopener&quot;&gt;content scripts&lt;/a&gt;, &lt;a href=&quot;https://developer.chrome.com/user_interface#popup&quot; target=&quot;_blank&quot; rel=&quot;noreferrer noopener&quot;&gt;popups&lt;/a&gt; and many other things used by the extension. Here&apos;s a sample manifest file.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;{
  &quot;name&quot;: &quot;Getting Started Example&quot;,
  &quot;version&quot;: &quot;1.0&quot;,
  &quot;description&quot;: &quot;Build an Extension!&quot;,
  &quot;permissions&quot;: [&quot;storage&quot;],
  &quot;background&quot;: {
    &quot;scripts&quot;: [&quot;background.js&quot;],
    &quot;persistent&quot;: false
  },
  &quot;page_action&quot;: {
    &quot;default_popup&quot;: &quot;popup.html&quot;,
    &quot;default_icon&quot;: {
      &quot;16&quot;: &quot;images/get_started16.png&quot;,
      &quot;32&quot;: &quot;images/get_started32.png&quot;,
      &quot;48&quot;: &quot;images/get_started48.png&quot;,
      &quot;128&quot;: &quot;images/get_started128.png&quot;
    }
  },
  &quot;manifest_version&quot;: 2
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Folder/bundle containing a manifest file, scripts, and other assets, is loaded into chrome from &lt;code&gt;chrome://extensions/&lt;/code&gt; page. Chrome reads the manifest file and installs the extension. &lt;em&gt;If any change is made in script or any other file, we reload the extension to install the latest change&lt;/em&gt;.&lt;/p&gt;
&lt;p&gt;Here&apos;s a link to the official &lt;a href=&quot;https://developer.chrome.com/extensions/getstarted&quot; rel=&quot;noreferrer noopener&quot; target=&quot;_blank&quot;&gt;documentation&lt;/a&gt; which elborates chrome extensions and their installations.&lt;/p&gt;
&lt;p&gt;After getting familiar with the basics of extension development, I put on my developer hat 🤠 and started building an extension with &lt;a href=&quot;https://github.com/facebook/create-react-app&quot; rel=&quot;noopener noreferrer&quot; target=&quot;_blank&quot;&gt;create-react-app&lt;/a&gt;. Here are the steps I followed:&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;Created a react app by runnning&lt;/li&gt;
&lt;/ol&gt;
&lt;pre&gt;&lt;code&gt;create-react-app hello-extensions
&lt;/code&gt;&lt;/pre&gt;
&lt;ol&gt;
&lt;li&gt;Replaced &lt;code&gt;manifest.json&lt;/code&gt; file with below content.&lt;/li&gt;
&lt;/ol&gt;
&lt;pre&gt;&lt;code&gt;{
  &quot;name&quot;: &quot;Hello Extension&quot;,
  &quot;description&quot;: &quot;My first chrome extension&quot;,
  &quot;version&quot;: &quot;1.0&quot;,
  &quot;manifest_version&quot;: 2,
  &quot;browser_action&quot;: {
    &quot;default_popup&quot;: &quot;index.html&quot;
  },
  &quot;content_security_policy&quot;: &quot;script-src &apos;self&apos; &apos;sha256-5As4+...&apos;; object-src &apos;self&apos;&quot;
}
&lt;/code&gt;&lt;/pre&gt;
&lt;ol&gt;
&lt;li&gt;Build the app using&lt;/li&gt;
&lt;/ol&gt;
&lt;pre&gt;&lt;code&gt;npm run build
&lt;/code&gt;&lt;/pre&gt;
&lt;ol&gt;
&lt;li&gt;Loaded the build in chrome.&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;...and it worked. &lt;em&gt;Yay!!&lt;/em&gt;&lt;/p&gt;
&lt;figure class=&quot;text-center&quot;&gt;
&lt;p&gt;&lt;img src=&quot;https://smellycode.com/_astro/hello-world-extension.Bz67oIld.gif&quot; alt=&quot;&quot; /&gt;&lt;/p&gt;
&lt;/figure&gt;
&lt;p&gt;My &quot;Hello World&quot; moment with extension made me happy but my happiness didn&apos;t last for long when I decided to change the background color. I found out that I have to build and reload the extension again 😩.&lt;/p&gt;
&lt;h3&gt;Build changes 🤖&lt;/h3&gt;
&lt;p&gt;Running an app(created by &lt;code&gt;create-react-app&lt;/code&gt;) in development mode with &lt;code&gt;npm run start&lt;/code&gt; doesn&apos;t write files to the disk. I needed files to be present on the disk so that they can be loaded in chrome. As we know, the &lt;code&gt;create-react-app&lt;/code&gt; utility uses webpack under the hood with a predefined configuration. And to customize that predefined config we must eject it first. So I ejected the config with the command &lt;code&gt;npm run eject&lt;/code&gt;. It generated some config files and scripts.&lt;/p&gt;
&lt;p&gt;&lt;img src=&quot;https://smellycode.com/_astro/yarn-eject-files.CXokBA3P.png&quot; alt=&quot;&quot; /&gt;&lt;/p&gt;
&lt;p&gt;After ejecting the configuration, I needed to find a way to write files to disk in development mode. I ran to the &lt;a href=&quot;https://webpack.js.org/configuration/dev-server/&quot; rel=&quot;noreferrer noopener&quot;&gt;webpack dev server&lt;/a&gt; api document for help and found an option &lt;code&gt;writeToDisk&lt;/code&gt;. As its name suggests, setting &lt;code&gt;writeToDisk&lt;/code&gt; true will write files to disk. So I set it &lt;code&gt;true&lt;/code&gt; in the dev server config. It helped but it took a toll on the dev server. Dev server became &lt;em&gt;sluggish&lt;/em&gt;. Its sluggishness convinced me to look for a better alternative.&lt;/p&gt;
&lt;p&gt;I thought for a while and realized that I didn&apos;t need a dev server. I needed a &quot;watch server&quot; 😅. A server to watch files and copy them--with the latest changes--to build directory on the &lt;code&gt;change&lt;/code&gt; event. I leveraged &lt;code&gt;webpack.watch&lt;/code&gt; api and ended up with the watch script below.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;// some neccessary setup code
...
...
...

// Webpack watch
webpack(config).watch({}, (err, stats) =&amp;gt; {
  if (err) {
    console.error(err);
  } else {
    copyPublicFolder();
  }
  console.error(
    stats.toString({
      chunks: false,
      colors: true
    })
  );
});

function copyPublicFolder() {
  fs.copySync(paths.appPublic, paths.appBuild, {
    dereference: true,
    filter: file =&amp;gt; file !== paths.appHtml
  });
}

&lt;/code&gt;&lt;/pre&gt;
&lt;h3&gt;Reload changes 🔄&lt;/h3&gt;
&lt;p&gt;After dealing with the build barrier, the next challenge was to automatically reload the extension. I found a supercool webpack plugin &lt;a href=&quot;https://medium.com/front-end-weekly/hot-reloading-extensions-using-webpack-cdfa0e4d5a08&quot; target=&quot;_blank&quot; rel=&quot;noopener noreferrer&quot;&gt;webpack-chrome-extension-reloader&lt;/a&gt; which reloads chrome extensions out of the box. A million thanks to &lt;a href=&quot;https://twitter.com/rubenspgc&quot; rel=&quot;noreferrer noopener&quot;&gt;Rubens&lt;/a&gt; for writing it. A sneak peek of config with the plugin.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;// Other configuration
...
...
...
...

  plugins: [
    // Other plugins
    ...
    ...
    ...
    // Chrome extension hot reloading.
      isEnvDevelopment &amp;amp;&amp;amp;
        new ChromeExtensionReloader({
          reloadPage: true // Force the reload of the page also
          entries: {
            // The entries used for the content/background scripts
            contentScript: &apos;content-script&apos;,
            background: &apos;app&apos; // *REQUIRED
          }
        })
  ].filter(Boolean),

&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Illustration of the starter kit with live reloading.&lt;/p&gt;
&lt;figure class=&quot;text-center&quot;&gt;
&lt;p&gt;&lt;img src=&quot;https://smellycode.com/_astro/chrome-extension-live-reloading-with-react-cover-img.DfucDc4Q.gif&quot; alt=&quot;&quot; /&gt;&lt;/p&gt;
&lt;/figure&gt;
&lt;hr /&gt;
&lt;p&gt;Here&apos;s the &lt;a href=&quot;https://github.com/hk-skit/chrome-extension-starter-kit&quot; rel=&quot;noreferrer noopener&quot;&gt;link&lt;/a&gt; to complete package/starter kit. I hope it will be helpful. If you have any idea/suggestion to make it better, please do share. Thanks 🙏🏻. Happy Coding!&lt;/p&gt;
</content:encoded><category>ReactJs</category><category>Chrome Extensions</category><category>Webpack</category></item><item><title>JS one-liners 😻</title><link>https://smellycode.com/js-oneliners/</link><guid isPermaLink="false">https://smellycode.com/js-oneliners/</guid><description>Collection of JS one-liners.</description><pubDate>Fri, 01 Mar 2019 18:30:00 GMT</pubDate><content:encoded>&lt;p&gt;I am a huge fan of &lt;a href=&quot;https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions&quot; target=&quot;_blank&quot;&gt;Arrow functions&lt;/a&gt;. They have changed the way we write code. They have cured the cloudy behaviour of &lt;code&gt;this&lt;/code&gt;. They let us define functions without &lt;code&gt;function&lt;/code&gt; keyword 😅. This article collates one-liners — written using arrow functions — with their explanations.&lt;/p&gt;
&lt;h3&gt;Remove Duplicates from Array&lt;/h3&gt;
&lt;p&gt;Interviewer often asks candidates to write a function which removes duplicates from an array. This can be done in many ways. We’ll discuss only those which are relevant to this post.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;const removeDuplicates = arr =&amp;gt;
  arr.filter((item, index) =&amp;gt; index === arr.indexOf(item));
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;As you can see we are using &lt;code&gt;filter&lt;/code&gt; and &lt;code&gt;indexOf&lt;/code&gt; methods of the Array class. We get the index of the &lt;code&gt;item&lt;/code&gt; using &lt;code&gt;indexOf&lt;/code&gt; method and compare it with the current index. If both are equal then the &lt;code&gt;item&lt;/code&gt; is unique else its repeated.&lt;/p&gt;
&lt;p&gt;To remove duplicates we can also use &lt;a href=&quot;https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set&quot; target=&quot;_blank&quot;&gt;Set&lt;/a&gt; data structures. We create a &lt;code&gt;set&lt;/code&gt; from the &lt;code&gt;array&lt;/code&gt; and then convert set back to the &lt;code&gt;array&lt;/code&gt; using &lt;a href=&quot;https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_syntax&quot; target=&quot;_blank&quot;&gt;spread operator&lt;/a&gt; or &lt;code&gt;Array.from&lt;/code&gt; method.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;// Using spread operator.
const removeDuplicates1 = array =&amp;gt; [...new Set(array)];
// Using Array.from method
const removeDuplicates2 = array =&amp;gt; Array.from(new Set(array));
&lt;/code&gt;&lt;/pre&gt;
&lt;h3&gt;Flatten Array&lt;/h3&gt;
&lt;p&gt;Flattening an array means converting a multi-dimension array to one-dimensional array. eg.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;// 2-dimensional array.
[[1, 2, 3], [4, 5, 6]]
// After flattening
[1, 2, 3, 4, 5, 6]
// Multi-dimentional array
[1, [2, [3, 4, [5], 6], 7], 8], 9]
// After flattening
[1, 2, 3, 4, 5, 6, 7, 8, 9]
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;We can use &lt;code&gt;Array.concat&lt;/code&gt; method with spread operator to flatten an array.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;// Flattens an array(doesn&apos;t flatten deeply).
const flatten = array =&amp;gt; [].concat(...array);
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;This approach flattens an array at only one level. Below function fully flattens an array.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;const flattenDeep = arr =&amp;gt;
  arr.reduce(
    (fArr, item) =&amp;gt; fArr.concat(Array.isArray(item) ? flatten(item) : item),
    []
  );
&lt;/code&gt;&lt;/pre&gt;
&lt;h3&gt;Merge Arrays&lt;/h3&gt;
&lt;p&gt;To merge arrays we can use &lt;code&gt;Array.concat&lt;/code&gt; method with spread operator.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;// Merge arrays
const merge = (...arrays) =&amp;gt; [].concat(...arrays);
&lt;/code&gt;&lt;/pre&gt;
&lt;h3&gt;Pipe (Function Composition)&lt;/h3&gt;
&lt;p&gt;We often need to “pipe” the output of one function as an input to another function. Here’s a simple implementation of the pipe function using Function Composition.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;// Pipe fn
const pipe = (...fns) =&amp;gt; arg =&amp;gt; fns.reduce((v, fn) =&amp;gt; fn(v), arg);

// Example
const addTwo = x =&amp;gt; x + 2;
const double = x =&amp;gt; x * 2;
const square = x =&amp;gt; x * x;
const fn = pipe(addTwo, double, square);
console.log(fn(1)); // square(double(addTwo(1))) -&amp;gt; 36
&lt;/code&gt;&lt;/pre&gt;
&lt;h3&gt;Compose(Pipe reverse)&lt;/h3&gt;
&lt;p&gt;Just like the &lt;code&gt;pipe&lt;/code&gt; function, &lt;code&gt;compose&lt;/code&gt; also supplies the output of one function as an input to another but it does it in reverse order.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;const compose = (...fns) =&amp;gt; fns.reduce((a, b) =&amp;gt; (...args) =&amp;gt; a(b(...args)));

// Example
const addTwo = x =&amp;gt; x + 2;
const double = x =&amp;gt; x * 2;
const square = x =&amp;gt; x * x;
const fn = compose(addTwo, double, square);
console.log(fn(1)); // -&amp;gt; 4 addTwo(double(square(1)))
&lt;/code&gt;&lt;/pre&gt;
&lt;h3&gt;Range Function&lt;/h3&gt;
&lt;p&gt;You might have used &lt;code&gt;range&lt;/code&gt; function of &lt;a href=&quot;https://lodash.com/docs/4.17.11#range&quot; target=&quot;_blank&quot;&gt;Lodash&lt;/a&gt;. Here’s a one-liner implementation of range using &lt;code&gt;Array.from&lt;/code&gt; method. It generate range from &lt;code&gt;start&lt;/code&gt; to &lt;code&gt;end&lt;/code&gt; (exclusive). It also takes an optional &lt;code&gt;step&lt;/code&gt; parameter.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;// Generates range [start, end) with step
const range = (start, end, step = 1) =&amp;gt;
  Array.from(
    { length: Math.ceil((end - start) / step) },
    (_, i) =&amp;gt; start + i * step
  );
&lt;/code&gt;&lt;/pre&gt;
&lt;h3&gt;Color Function&lt;/h3&gt;
&lt;p&gt;Generates a random hex color code.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;// Generates random hex color code.
const color = () =&amp;gt;
  &apos;#&apos; +
  Math.floor(Math.random() * 0xffffff)
    .toString(16)
    .padEnd(6, &apos;0&apos;);
&lt;/code&gt;&lt;/pre&gt;
&lt;hr /&gt;
&lt;h3&gt;Conclusion&lt;/h3&gt;
&lt;p&gt;Before we conclude there’s one thing that should be kept it mind while writing one-liners. One-liners do more things with less code, which tempts people to write more one-liners. But sometimes, writing less code makes it less readable and hard to debug. So if you are writing code which you feel should or can be broken into multiple lines. Just go ahead and do it. You’ll thank yourself later 🙂.&lt;/p&gt;
&lt;blockquote&gt;
&lt;p&gt;One liners are great but one should always make sure that they don’t take a toll on the legibility of code.&lt;/p&gt;
&lt;/blockquote&gt;
&lt;p&gt;Here’s the &lt;a href=&quot;https://gist.github.com/hk-skit/a82c4d9bf1c95f066e4f7e37edf3c81d&quot; target=&quot;_blank&quot;&gt;gist&lt;/a&gt; of all the one-liners used in this post. If there’s any one-liner which should be added to the list, please feel free to share. I’ll add it. Thanks for Reading 🙏🏻.&lt;/p&gt;
</content:encoded><category>JavaScript</category><category>Es5</category></item><item><title>Data Structures with Iterable Protocol</title><link>https://smellycode.com/data-structures-with-iterable-protocol/</link><guid isPermaLink="false">https://smellycode.com/data-structures-with-iterable-protocol/</guid><description>Iterating data structures with for-of loop and spreading them with spread operator(…).</description><pubDate>Sat, 26 Jan 2019 18:30:00 GMT</pubDate><content:encoded>&lt;p&gt;&lt;a href=&quot;https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Iterators_and_Generators&quot; target=&quot;_blank&quot; rel=&quot;noopener noreferrer&quot;&gt;Iterators and Generators&lt;/a&gt; have been around for a while. They have changed the way we loop through the values of an object. Earlier, we used to use the &lt;code&gt;for-in&lt;/code&gt; loop to iterate over the values, but there was no guarantee of the order in which values will be iterated. Also, it was quite cumbersome cause we had to use keys from the &lt;code&gt;for-in&lt;/code&gt; loop to get values. Generator and Iterators remove the pain of iterating objects. For an object to be iterable, it just needs to comply with &lt;a href=&quot;https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols&quot; target=&quot;_blank&quot; rel=&quot;noopener noreferrer&quot;&gt;iteration protocols&lt;/a&gt;. This post provides a quick overview of Generators and Iterators/Iterables and explains how common data structures can be made iterable.&lt;/p&gt;
&lt;h2&gt;Iteration Protocols&lt;/h2&gt;
&lt;p&gt;The advent of ES5 brought two iteration protocols to JavaScript: &lt;strong&gt;Iterable Protocol&lt;/strong&gt; and &lt;strong&gt;Iterator Protocol&lt;/strong&gt;.&lt;/p&gt;
&lt;h3&gt;Iterable Protocol&lt;/h3&gt;
&lt;p&gt;For an object to be &lt;strong&gt;iterable&lt;/strong&gt;, it must have an iterator method. An iterator method is defined using &lt;code&gt;@@iterator&lt;/code&gt; key i.e. the &lt;code&gt;Symbol.iterator&lt;/code&gt; constant. Iterator method can be any javascript function which takes zero arguments and returns an object conforming Iterator Protocol(will be discussing soon). Here’s the sample code, if you are lost in jargon.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;class IteratorDemo {
  // Iterator Method with @@iterator key
  // i.e. Symbol.iterator constant
  [Symbol.iterator]() {
    // Method stub which returns an iterator object.
  }
}
&lt;/code&gt;&lt;/pre&gt;
&lt;h3&gt;Iterator Protocol&lt;/h3&gt;
&lt;blockquote&gt;
&lt;p&gt;The iterator protocol defines a standard way to produce a sequence of values (either finite or infinite), and potentially a return value when all values have been generated. ~MDN&lt;/p&gt;
&lt;/blockquote&gt;
&lt;p&gt;For an object to be an &lt;strong&gt;iterator&lt;/strong&gt; object, it needs to implement a &lt;code&gt;next&lt;/code&gt; method which fulfils below criteria:&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;It should take zero arguments&lt;/strong&gt;. Although, you may pass arguments to next and there won’t be any error but you shouldn’t cause when your iterable object will be used with &lt;code&gt;spread&lt;/code&gt; operator or &lt;code&gt;for-of&lt;/code&gt; loop you won’t be able to pass any arguments.&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;It should return an object with at least one of the two properties.&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;code&gt;value&lt;/code&gt;: Any javascript value which we want to return from our iterator.&lt;/li&gt;
&lt;li&gt;&lt;code&gt;done&lt;/code&gt;: A boolean flag to indicate whether we reached the end of the sequence or not.&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;Here’s a quick range iterator example borrowed from MDN.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;class RangeIterator {
  constructor({ start = 0, end = 1000, step = 1 }) {
    this.start = start;
    this.end = end;
    this.step = step;
  }

  [Symbol.iterator]() {
    let start = this.start;
    const iterable = {
      // Next fn complying with Iterator protocol.
      next: () =&amp;gt; {
        if (start &amp;lt;= this.end) {
          const result = {
            value: start,
            done: false
          };
          start += this.step;
          return result;
        }

        return {
          done: true
        };
      }
    };
    return iterable;
  }
}

const range = new RangeIterator({
  start: 0,
  end: 20,
  step: 5
});
console.log(...range); // 0 5 10 15 20
&lt;/code&gt;&lt;/pre&gt;
&lt;h2&gt;Generators&lt;/h2&gt;
&lt;p&gt;Sometimes explicitly maintaining the internal state of iterators and returning an iterable object is too much of work. Generators reduce that amount of work and provide an alternate approach to make an object iterable with the help of &lt;code&gt;yield&lt;/code&gt; keyword. Generators functions have special syntax. They are written as &lt;code&gt;function *&lt;/code&gt;. You can read more on generators &lt;a href=&quot;https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Iterators_and_Generators&quot; target=&quot;_blank&quot; rel=&quot;noopener noreferrer&quot;&gt;here&lt;/a&gt;.&lt;/p&gt;
&lt;p&gt;Here’s our previous example re-written with the help of generators.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;class RangeGenerator {
  constructor({ start = 0, end = 1000, step = 1 }) {
    this.start = start;
    this.end = end;
    this.step = step;
  }

  *[Symbol.iterator]() {
    let start = this.start;
    while (start &amp;lt;= this.end) {
      yield start;
      start += this.step;
    }
  }
}

const range = new RangeGenerator({
  start: 0,
  end: 20,
  step: 5
});
console.log(...range); // 0 5 10 15 20
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Alright, enough about Iterators and Generators. Let’s use them with common data structures like LinkedList, Stack, BinaryTree.&lt;/p&gt;
&lt;h3&gt;LinkedList&lt;/h3&gt;
&lt;p&gt;&lt;a href=&quot;https://en.wikipedia.org/wiki/Linked_list&quot; target=&quot;_blank&quot; rel=&quot;noopener noreferrer&quot;&gt;LinkedList&lt;/a&gt; is a linear data structures where each node/element holds the data and pointer to the next node. The start and end of the list are called &lt;code&gt;head&lt;/code&gt; and &lt;code&gt;tail&lt;/code&gt;. Here’s an implementation of Linked List.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;class Node {
  constructor(value) {
    this.value = value;
    this.next = null;
  }
}

class LinkedList {
  constructor() {
    this.head = null;
    this.tail = null;
  }

  get isEmpty() {
    return this.head === null;
  }

  add(value) {
    const node = new Node(value);
    if (this.head === null) {
      this.head = this.tail = node;
      return this;
    }
    this.tail.next = node;
    this.tail = node;
    return this;
  }

  addHead(value) {
    const node = new Node(value);
    node.next = this.head;
    this.head = node;
  }

  removeHead() {
    if (this.isEmpty) {
      return null;
    }
    const head = this.head;
    this.head = this.head.next;
    return head.value;
  }

  removeTail() {
    if (this.isEmpty) {
      return null;
    }

    const { value } = this.tail;
    if (this.head === this.tail) {
      // List with single node.
      this.tail = this.head = null;
      return value;
    }

    let prev = null;
    let current = this.head;
    while (current.next !== null) {
      prev = current;
      current = current.next;
    }

    // Adjust tail pointer.
    prev.next = null;
    this.tail = prev;

    return value;
  }

  remove(x) {
    let prev = null;
    let current = this.head;
    while (current !== null) {
      const { value, next } = current;
      if (value !== x) {
        prev = current;
        current = next;
        continue;
      }
      // If value is at head.
      if (prev === null) {
        this.head = next;
      } else {
        prev.next = next;
      }
      return x;
    }
    return null;
  }
}

const list = [2, 1, 3, 4, 5].reduce(
  (list, value) =&amp;gt; list.add(value),
  new LinkedList()
);
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;We need to add an iterator to make the linked list iterable. Our iterator function will have an internal state variable called &lt;code&gt;current&lt;/code&gt; (which initially refers to &lt;code&gt;head&lt;/code&gt;) representing the current node we are at. Every &lt;code&gt;next&lt;/code&gt; call, will return the data of the &lt;code&gt;current&lt;/code&gt; node and move the current node to the &lt;code&gt;next&lt;/code&gt; node. Once the &lt;code&gt;next&lt;/code&gt; method is done traversing all nodes, it returns &lt;code&gt;done&lt;/code&gt; as &lt;code&gt;true&lt;/code&gt; to stop the iteration.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt; /**
   * Iterator function.
   *
   * @returns
   * @memberof LinkedList
   */
  [Symbol.iterator]() {
    let current = this.head;
    const iterable = {
      next: () =&amp;gt; {
        if (current === null) {
          return {
            done: true
          };
        }
        const {
          value,
          next
        } = current;
        current = next;
        return {
          value,
          done: false
        };
      }
    };
    return iterable;
  }
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Generator version of the above.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt; // Generator function.
  *[Symbol.iterator]() {
    let current = this.head;
    while (current !== null) {
      const { value } = current;
      current = current.next;
      yield value;
    }
  }
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;You can find the full code &lt;a href=&quot;https://github.com/hk-skit/iterable-data-structures/blob/master/src/LinkedList/LinkedList.js&quot; target=&quot;_blank&quot; rel=&quot;noopener noreferrer&quot;&gt;here&lt;/a&gt;.&lt;/p&gt;
&lt;h3&gt;Stack&lt;/h3&gt;
&lt;p&gt;A &lt;a href=&quot;https://en.wikipedia.org/wiki/Stack_%28abstract_data_type%29&quot; target=&quot;_blank&quot; rel=&quot;noopener noreferrer&quot;&gt;Stack&lt;/a&gt; is a linear data structure which follows Last In First Out(LIFO) pattern which means items inserted into the stack last will come off first. To keep things &lt;a href=&quot;https://en.wikipedia.org/wiki/Don%27t_repeat_yourself&quot; target=&quot;_blank&quot; rel=&quot;noopener noreferrer&quot;&gt;DRY&lt;/a&gt;, we’ll use our earlier Linked List data structure to implement Stack. We’ll also leverage its iterator method to make our stack iterable.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;class Stack {
  constructor() {
    this.list = new LinkedList();
  }

  get isEmpty() {
    return this.list.isEmpty;
  }

  /**
   * Iterator function.
   *
   * @returns
   * @memberof Stack
   */
  [Symbol.iterator]() {
    return this.list[Symbol.iterator]();
  }

  push(value) {
    this.list.addHead(value);
    return this;
  }

  pop() {
    if (this.isEmpty) {
      throw new Error(&apos;STACK_UNDERFLOW&apos;);
    }
    return this.list.removeHead();
  }
}

const stack = [1, 2, 3, 4, 5, 6].reduce(
  (stack, value) =&amp;gt; stack.push(value),
  new Stack()
);
console.log(...stack); // 6 5 4 3 2 1
&lt;/code&gt;&lt;/pre&gt;
&lt;h3&gt;Binary Tree&lt;/h3&gt;
&lt;p&gt;Binary Tree is a subclass of Tree data structure. In Binary Tree, each node can have maximum 2 children called &lt;code&gt;left&lt;/code&gt; and &lt;code&gt;right&lt;/code&gt;. You can read more about Binary Trees in my post &lt;a href=&quot;/binary-tree&quot;&gt;A Bit About Binary Tree&lt;/a&gt;. Since trees are non-linear data structure so they can be traversed in many ways. We’ll implement their Level Order or Breadth First Order traversal in our iterator method. Here’s the class which represents &lt;code&gt;BinaryTreeNode&lt;/code&gt; for our &lt;code&gt;BinaryTree&lt;/code&gt;.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;export class BinaryTreeNode {
  constructor(value) {
    this.value = value;
    this.left = null;
    this.right = null;
  }

  /**
   * Inserts node in level order.
   *
   * @param {*} x
   * @returns
   * @memberof BinaryTreeNode
   */
  add(x) {
    const queue = [this];
    const newNode = new BinaryTreeNode(x);

    while (true) {
      const node = queue.shift();
      if (node.left === null) {
        node.left = newNode;
        return this;
      }

      if (node.right === null) {
        node.right = newNode;
        return this;
      }
      queue.push(node.left);
      queue.push(node.right);
    }
    return this;
  }
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;And finally, &lt;code&gt;BinaryTree&lt;/code&gt; with iterator method.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;import { BinaryTreeNode } from &apos;./BinaryTreeNode&apos;;
export class BinaryTree {
  constructor() {
    this.root = null;
  }

  get isEmpty() {
    return this.root === null;
  }

  add(x) {
    if (this.isEmpty) {
      this.root = new BinaryTreeNode(x);
    } else {
      this.root.add(x);
    }
    return this;
  }

  /**
   * Iterator. Traverses in level order.
   *
   * @memberof BinaryTree
   */
  *[Symbol.iterator]() {
    const queue = this.isEmpty ? [] : [this.root];
    while (queue.length) {
      const { value, left, right } = queue.shift();
      if (left !== null) {
        queue.push(left);
      }

      if (right !== null) {
        queue.push(right);
      }
      yield value;
    }
  }
}
&lt;/code&gt;&lt;/pre&gt;
&lt;hr /&gt;
&lt;p&gt;Well, that’s all about Data Structures with Iterable Protocol. I have created a &lt;a href=&quot;https://github.com/hk-skit/iterable-data-structures&quot; target=&quot;_blank&quot; rel=&quot;noopener noreferrer&quot;&gt;git-repository&lt;/a&gt; of examples used in this post. I hope you find them useful. Thanks for reading 🙏🏻.&lt;/p&gt;
</content:encoded><category>JavaScript</category><category>Data Structures</category><category>ES6</category></item><item><title>Level up your Regex Game 🚀</title><link>https://smellycode.com/regex-game/</link><guid isPermaLink="false">https://smellycode.com/regex-game/</guid><description>😱😰😨😢😥😵😳😲😮😧😦😯😑😐😏🤗🤓😎</description><pubDate>Sat, 13 Oct 2018 18:30:00 GMT</pubDate><content:encoded>&lt;p&gt;Regular expressions are one of the most powerful tools which programmers can have in their arsenal. But learning them is one of hell of a painful thing. This week I mustered up some courage and decided to go through that pain. I am still learning about them. In this post, I’ll share what I have learned so far. So let’s get started.&lt;/p&gt;
&lt;h3&gt;Definition&lt;/h3&gt;
&lt;blockquote&gt;
&lt;p&gt;Regular expressions are patterns used to match character combinations in strings. ~ MDN&lt;/p&gt;
&lt;/blockquote&gt;
&lt;p&gt;When ugly cryptic symbols meet gorgeous characters, they produce patterns which can be used by a &lt;a href=&quot;https://www.regular-expressions.info/engine.html&quot; rel=&quot;noopener noreferrer&quot; target=&quot;_blank&quot;&gt;regex engine&lt;/a&gt;(a tool which understands those patterns) to match strings/characters in a text. These patterns are called “Regular Expressions”. Let’s have an example.&lt;/p&gt;
&lt;p&gt;Suppose you want to check the presence of ‘Sheldon’ in text ‘Bazinga! I am Sheldon Cooper’. You might say, you’ll use the &lt;code&gt;String.indexOf&lt;/code&gt; API. But we are not learning about string APIs here. We are learning regex so we’ll do it the regex way.&lt;/p&gt;
&lt;p&gt;In JavaScript, a regular expression can be created using one of the following two ways&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;Using regex literals(with the help of a pair of forward slashes &lt;code&gt;/&lt;/code&gt;).&lt;/li&gt;
&lt;li&gt;And the &lt;code&gt;RegExp&lt;/code&gt; constructor.&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;We’ll use literal way throughout this post. You can read about the constructor way on &lt;a href=&quot;https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp#character-sets&quot; target=&quot;_blank&quot; rel=&quot;noopener noreferrer&quot;&gt;MDN&lt;/a&gt; if you wish to.&lt;/p&gt;
&lt;p&gt;Alright! Let’s create a regex to find ‘Sheldon’ in a text. As we saw earlier we use &lt;code&gt;/&lt;/code&gt; to create regex. So whatever we write between a pair of &lt;code&gt;/&lt;/code&gt; becomes a pattern for matching. eg &lt;code&gt;/Sheldon/&lt;/code&gt; creates a regex which matches ‘Sheldon’ in a text. Congratulations! We just made our first regex.&lt;/p&gt;
&lt;p&gt;Hold on Hitesh! You haven’t explained how I am gonna use it. I can hear you.&lt;/p&gt;
&lt;p&gt;&lt;img src=&quot;https://smellycode.com/_astro/regex-meme.BLSDbDdp.jpg&quot; alt=&quot;Regex Meme&quot; /&gt;&lt;/p&gt;
&lt;p&gt;Well, what if I tell you that &lt;strong&gt;regex our also JavaScript objects&lt;/strong&gt; which have some useful methods to make our life simpler. One such method is &lt;code&gt;RegExp.test&lt;/code&gt; which is used to test pattern with respect to a text. It returns true if the pattern matches otherwise false.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;const regex = /Sheldon/; // matches &apos;Sheldon&apos; in text.
regex.test(&apos;Bazinga! I am Sheldon Cooper&apos;); // Returns true.
regex.test(&apos;Penny! Penny! Penny!&apos;); // Return false.
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Understanding and debugging a regex — especially when you are getting started — is difficult, let’s be honest. There are some helpful tools like &lt;a href=&quot;https://www.debuggex.com/?flavor=javascript&quot; target=&quot;_blank&quot;&gt;Regex Visualiser&lt;/a&gt;, &lt;a href=&quot;https://regex101.com/&quot; target=&quot;_blank&quot;&gt;Regex101&lt;/a&gt; and the almighty &lt;code&gt;console.dir&lt;/code&gt; which can help you throughout journey. Ok! Enough ado!! Let’s take a plunge.&lt;/p&gt;
&lt;p&gt;Mostly, we create regular expressions by juggling with simple characters(mainly alphanumeric) and special characters/symbols. Simple characters don’t hold any specific meaning but special characters do for sure. That is why they are defined in various categories/classes. We’ll take a gander at each category with the help of some examples.&lt;/p&gt;
&lt;h3&gt;Character Classes&lt;/h3&gt;
&lt;p&gt;This class holds &lt;code&gt;.&lt;/code&gt;,&lt;code&gt;\d&lt;/code&gt;, &lt;code&gt;\D&lt;/code&gt;, &lt;code&gt;\w&lt;/code&gt;, &lt;code&gt;\W&lt;/code&gt;, &lt;code&gt;\s&lt;/code&gt; and many more characters which are beyond the scope of the article. Here’s &lt;a href=&quot;https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp#character-classes&quot; target=&quot;_blank&quot;&gt;the full list&lt;/a&gt;.&lt;/p&gt;
&lt;h3&gt;Dot(.) Character Class&lt;/h3&gt;
&lt;p&gt;Dot character has candid nature. It gels well with every single character(except line terminators) which comes on its way while matching the text.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;const regex = /./;
// Statements below return true.
regex.test(&apos;!&apos;); // matches &apos;!&apos;
regex.test(&apos;Voila!&apos;); // macthes &apos;V&apos;
regex.test(&apos;$&apos;); // matches &apos;$&apos;
regex.test(&apos; &apos;); // macthes &apos; &apos; (space)
regex.test(&quot;&apos;&quot;); // matches &apos;(single quote)
/.Script/.test(&apos;JScript JavaScript&apos;); // macthes &apos;JScript&apos;
/.Script/.test(&apos;@Script $Script&apos;); // macthes &apos;@Script&apos;
// Statements below return false
regex.test(&apos;&apos;); // no character present.
regex.test(&apos;\n&apos;); // line terminator.
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Note: Dot loses its special meaning when it appears in a character set and matches the literal dot. Please refer to &lt;a href=&quot;https://smellycode.com/regex-game/#character-set&quot;&gt;Character Sets&lt;/a&gt; section for more details.&lt;/p&gt;
&lt;h3&gt;Digit Character Class(\d and \D)&lt;/h3&gt;
&lt;p&gt;As the name suggests, digit character class is used for matching numbers. &lt;code&gt;\d&lt;/code&gt; matches digits(numbers) while &lt;code&gt;\D&lt;/code&gt; matches non-digit characters.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;const regex = /\d/;
regex.test(&apos;1&apos;); // true matches &apos;1&apos;
regex.test(&apos;23&apos;); // true matches &apos;2&apos;
regex.test(&apos;1e10&apos;); // true matches &apos;1&apos;
regex.test(&apos;e&apos;); // false
/\D/.test(&apos;1&apos;); // false
/\D/.test(&apos;A&apos;); // true matches &apos;A&apos;
/\D/.test(&apos;A2&apos;); // true matches &apos;A&apos;
&lt;/code&gt;&lt;/pre&gt;
&lt;h3&gt;Word Character Class(\w and \W)&lt;/h3&gt;
&lt;p&gt;&lt;code&gt;\w&lt;/code&gt; matches any alphanumeric character including underscore (&lt;code&gt;_&lt;/code&gt;). &lt;code&gt;\W&lt;/code&gt; is the negation of &lt;code&gt;\w&lt;/code&gt; i.e. it matches all the non-alphanumeric characters excluding the underscore.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;const regex = /\w/;
regex.test(&apos;1&apos;); // true matches &apos;1&apos;
regex.test(&apos;23 is my roll number.&apos;); // true matches &apos;2&apos;
regex.test(&apos;1e10&apos;); // true matches &apos;1&apos;
regex.test(&apos;e&apos;); // true
regex.test(&apos; &apos;); // false
regex.test(&apos; _jedi &apos;); // true matches &apos;_&apos;
regex.test(&apos;!@#$%^&amp;amp;*()&apos;); // false
/\W/.test(&apos;1&apos;); // false
/\W/.test(&apos;23 is my roll number.&apos;); // true matches &apos; &apos;(first space)
/\W/.test(&apos;1e10&apos;); // false
/\W/.test(&apos;e&apos;); // false
/\W/.test(&apos; &apos;); // true
/\W/.test(&apos;_jedi &apos;); // false
/\W/.test(&apos;!@#$%^&amp;amp;*()&apos;); // true matchs &apos;!&apos;
&lt;/code&gt;&lt;/pre&gt;
&lt;h3&gt;Space Character Class(\s and \S)&lt;/h3&gt;
&lt;p&gt;Space character(&lt;code&gt;\s&lt;/code&gt;) matches a white space character in a text. White space in text can be any space, tab, new line or any other character which can create white space in text(eg. &lt;a href=&quot;http://jkorpela.fi/chars/spaces.html&quot; target=&quot;_blank&quot;&gt;unicode space characters&lt;/a&gt;). Any non-white space character can be matched by &lt;code&gt;\S&lt;/code&gt;.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;const regex = /\s/;
regex.test(&apos;1 &apos;); // true matches &apos; &apos;
regex.test(&apos;1\t&apos;); // true matches tab  &quot; &quot;
regex.test(&apos;\n&apos;); // true matches &quot;↵&quot;
regex.test(&apos; &apos;); // true
regex.test(&apos;Name&apos;); // false
/\S/.test(&apos; &apos;); // false
/\S/.test(&apos; 1&apos;); // true matches &quot;1&quot;
/\S/.test(&apos;\t&apos;); // false
/\S/.test(&apos;\n&apos;); // false
&lt;/code&gt;&lt;/pre&gt;
&lt;h3&gt;&lt;a name=&quot;character-set&quot;&gt;&lt;/a&gt;Character Sets([]) and Alternation&lt;/h3&gt;
&lt;p&gt;Character Sets are pretty useful especially when we want to match text against a set of characters. We create a character set by enclosing characters in brackets &lt;code&gt;[]&lt;/code&gt;. Character Set matches any of the character enclosed within brackets. eg. pattern &lt;code&gt;[abc]&lt;/code&gt; is a character set which matches &lt;code&gt;a&lt;/code&gt;, &lt;code&gt;b&lt;/code&gt;, and &lt;code&gt;c&lt;/code&gt; in a text.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;const regex = /[abc]/;
regex.test(&apos;a&apos;); // true
regex.test(&apos;b&apos;); // true
regex.test(&apos;c&apos;); // true
regex.test(&apos;abc&apos;); // true
regex.test(&apos;This is plain text&apos;); // true matches &quot;a&quot;
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;We can also define a range in character sets using a hyphen(-) eg. pattern &lt;code&gt;[0–4]&lt;/code&gt; will match any digit between &lt;code&gt;0&lt;/code&gt; to &lt;code&gt;4&lt;/code&gt; in a text. Hyphen loses its special meaning when it’s on the boundary(appears as the first or the last character in the character set), and treated as literal hyphen character. eg. &lt;code&gt;[04-]&lt;/code&gt; will macth &lt;code&gt;0&lt;/code&gt;, &lt;code&gt;4&lt;/code&gt; and &lt;code&gt;-&lt;/code&gt;.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;/[0-4]/.test(&apos;0&apos;); // true
/[0-4]/.test(&apos;4&apos;); // true
/[0-4]/.test(&apos;2&apos;); // true
/[0-4]/.test(&apos;54&apos;); // true matches &quot;4&quot;
/[0-4]/.test(&apos;a4&apos;); // true matches &quot;4&quot;
/[0-4]/.test(&apos;5&apos;); // false
/[0-4]/.test(&apos;a&apos;); // false
// Below is equivalent to \w.
/[A-Za-z0-9_]/.test(&apos;_jumbo&apos;);
// Hyphen loses special meaning when on boundary
/[04-]/.test(&apos;0&apos;); // true
/[04-]/.test(&apos;4&apos;); // true
/[04-]/.test(&apos;2&apos;); // false
/[04-]/.test(&apos;-&apos;); // true macthes &quot;-&quot;
/[04-]/.test(&apos;non-digit&apos;); // true matches &quot;-&quot;
/[0-4-7]/.test(&apos;non-digit&apos;); // true matches &quot;-&quot;
/[0-4-7]/.test(&apos;0&apos;); // true
/[0-4-7]/.test(&apos;4&apos;); // true
/[0-4-7]/.test(&apos;2&apos;); // true
/[0-4-7]/.test(&apos;5&apos;); // false
/[0-4-7]/.test(&apos;7&apos;); // true
/[0-4-7]/.test(&apos;-&apos;); // true macthes &quot;-&quot;
// Dot(.) and asterisk(*) also lose their power with charset.
/[.*]/.test(&apos;*&apos;); // true
/[.*]/.test(&apos;.&apos;); // true
/[.*]/.test(&apos;.*&apos;); // matches &quot;.&quot;
/[.*]/.test(&apos;abc&apos;); // false
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Character set also allows negation using &lt;code&gt;^&lt;/code&gt; which means we can match any character except the one present in charset. The only stipulation is it has to be the first character of the charset. If it’s not the first character then it will have its literal meaning.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;const regex = [^0-4]; // any character except range 0 to 4.
regex.test(&apos;0&apos;); // false
regex.test(&apos;4&apos;); // false
regex.test(&apos;2&apos;); // false
regex.test(&apos;5&apos;); // true
regex.test(&apos;a&apos;); // true
// When ^ is not first character
/[a^c]/.test(&apos;a&apos;); // true
/[a^c]/.test(&apos;c&apos;); // true
/[a^c]/.test(&apos;^&apos;); // true
/[a^c]/.test(&apos;abc&apos;); // matches &quot;a&quot;
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;strong&gt;Alternation&lt;/strong&gt; is achieved with the help of OR (|) operator. The behavior is akin to the logical OR operator. eg. &lt;code&gt;/green|red/&lt;/code&gt; will match either &lt;code&gt;green&lt;/code&gt; or &lt;code&gt;red&lt;/code&gt; in a text.&lt;/p&gt;
&lt;h2&gt;Boundaries&lt;/h2&gt;
&lt;p&gt;Just like string APIs (&lt;code&gt;String.startsWith&lt;/code&gt;, &lt;code&gt;String.endsWith&lt;/code&gt;, etc), regular expressions also provide ways to test if a string starts or ends with certain characters. It advances the game further with the help of word boundary(&lt;code&gt;\b&lt;/code&gt;) which will be discussing soon.&lt;/p&gt;
&lt;h3&gt;Beginning (^)&lt;/h3&gt;
&lt;p&gt;It matches the beginning of the text.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;const regex = /^T/;
regex.test(&apos;The Coldplay&apos;); // true matches &quot;T&quot; of &quot;The&quot;
regex.test(&apos;the Coldplay&apos;); // false
regex.test(&apos;the Mike Tyson&apos;); // false
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Beginning character has different meaning when it appears in a charset. Please refer the &lt;a href=&quot;https://smellycode.com/regex-game/#character-set&quot;&gt;charset section&lt;/a&gt;.&lt;/p&gt;
&lt;h3&gt;Ending ($)&lt;/h3&gt;
&lt;p&gt;It matches end of the text.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;const regex = /End$/;
regex.test(&apos;The End&apos;); // true matches &quot;End&quot;
regex.test(&apos;The end&apos;); // false
regex.test(&apos;The End.&apos;); // false
&lt;/code&gt;&lt;/pre&gt;
&lt;h3&gt;Word Boundaries(\b)&lt;/h3&gt;
&lt;p&gt;A word boundary is a position where a word starts or ends. It is basically an empty string before or after the word which acts as a boundary. Let’s use &lt;code&gt;String.replace&lt;/code&gt; method to grok it.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;// Below regex matches all word boundaries in text.
// &quot;g&quot; is global flag which will discuss in flags section.
const regex = /\b/g;
const str1 = &apos;Regular Expressions&apos;.replace(regex, &apos;~&apos;);
const str2 = &apos;Regular_Expressions&apos;.replace(regex, &apos;~&apos;);
const str3 = &apos;Regular-Expressions&apos;.replace(regex, &apos;~&apos;);
console.log(str1); // ~Regular~ ~Expressions~
console.log(str2); // ~Regular_Expressions~
console.log(str3); // ~Regular~-~Expressions~
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;In regular expressions, a word can only have characters of word character &lt;code&gt;\w&lt;/code&gt; class which means that ‘Regular_Expressions’ will be treated as a single word while ‘Regular-Expressions’ will have two words. You can read more about word boundaries &lt;a href=&quot;https://stackoverflow.com/questions/1324676/what-is-a-word-boundary-in-regexes&quot; target=&quot;_blank&quot;&gt;here&lt;/a&gt;.&lt;/p&gt;
&lt;p&gt;Regex also has non-word boundaries &lt;code&gt;\B&lt;/code&gt; which is opposite of &lt;code&gt;\b&lt;/code&gt;.&lt;/p&gt;
&lt;h3&gt;Quantifiers&lt;/h3&gt;
&lt;p&gt;Quantifiers are used for matching occurrence eg. matching &lt;code&gt;wow&lt;/code&gt; in a text where &lt;code&gt;wow&lt;/code&gt; can be present with multiple ‘o’(&lt;code&gt;wow&lt;/code&gt;, &lt;code&gt;woow&lt;/code&gt;, &lt;code&gt;woooow&lt;/code&gt; or &lt;code&gt;woooooooo&lt;/code&gt;).&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;code&gt;*&lt;/code&gt; matches zero or more occurrence of the preceding character.&lt;/li&gt;
&lt;/ul&gt;
&lt;pre&gt;&lt;code&gt;const regex = /wo*/;
regex.test(&apos;wooohooo&apos;); // true matches &quot;wooo&quot;
regex.test(&apos;wink&apos;); // true matches &quot;w&quot;;
regex.test(&apos;blink&apos;);; /false
&lt;/code&gt;&lt;/pre&gt;
&lt;ul&gt;
&lt;li&gt;&lt;code&gt;+&lt;/code&gt; matches 1 or more occurrence of the preceding character.&lt;/li&gt;
&lt;/ul&gt;
&lt;pre&gt;&lt;code&gt;const regex = /wo+w/;
regex.test(&apos;wow&apos;); // true
regex.test(&apos;woooow&apos;); // true
regex.test(&apos;www&apos;); // false
&lt;/code&gt;&lt;/pre&gt;
&lt;ul&gt;
&lt;li&gt;&lt;code&gt;?&lt;/code&gt; matches 0 or 1 time.&lt;/li&gt;
&lt;/ul&gt;
&lt;pre&gt;&lt;code&gt;const regex = /wo?w/;
regex.test(&apos;wow&apos;); // true
regex.test(&apos;woooow&apos;); // false
regex.test(&apos;www&apos;); // true matches &quot;ww&quot;
&lt;/code&gt;&lt;/pre&gt;
&lt;ul&gt;
&lt;li&gt;&lt;code&gt;{n,m}&lt;/code&gt; matches &lt;code&gt;n&lt;/code&gt; to &lt;code&gt;m&lt;/code&gt; times where &lt;code&gt;n ≥ 0&lt;/code&gt; and &lt;code&gt;m &amp;gt; 0&lt;/code&gt;. Also &lt;code&gt;m&lt;/code&gt; is optional means &lt;code&gt;{n}&lt;/code&gt; match exact n occurrence and &lt;code&gt;{n,}&lt;/code&gt; matches &lt;code&gt;n&lt;/code&gt; or more occurrence.&lt;/li&gt;
&lt;/ul&gt;
&lt;pre&gt;&lt;code&gt;/wo{1}w/.test(&apos;wow&apos;); // true
/wo{1}w/.test(&apos;ww&apos;); // false
/wo{1}w/.test(&apos;wo0w&apos;); // false
/wo{1,}w/.test(&apos;wow&apos;); // true
/wo{1,}w/.test(&apos;woooow&apos;); // true
/wo{1,3}w/.test(&apos;ww&apos;); // false
/wo{1,3}w/.test(&apos;wow&apos;); // true
/wo{1,3}w/.test(&apos;woow&apos;); // true
/wo{1,3}w/.test(&apos;wooow&apos;); // true
/wo{1,3}w/.test(&apos;woooow&apos;); // false
&lt;/code&gt;&lt;/pre&gt;
&lt;h3&gt;Flags&lt;/h3&gt;
&lt;p&gt;Flags are mainly used to provide additional information to the regex engine.Flags are mainly used to provide additional information to the regex engine. We place flags at the end of the regex — after the last forward slash.&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;code&gt;g&lt;/code&gt; global match; we have seen that by default a regex returns the first match but, with the help of global match flag, we can also get all the matches. Regex engine leverages &lt;code&gt;lastIndex&lt;/code&gt; property of a regex for global matching. Global match examples with &lt;code&gt;String.match&lt;/code&gt;.&lt;/li&gt;
&lt;/ul&gt;
&lt;pre&gt;&lt;code&gt;// only first match
const regexWithout = /foo/;
&apos;foo foosball football&apos;.match(regexWithout); // [&quot;foo&quot;]
// matches all &quot;foo&quot;s
const regexWith = /foo/g;
&apos;foo foosball football&apos;.match(regexWith); // [&quot;foo&quot;, &quot;foo&quot;, &quot;foo&quot;]
&lt;/code&gt;&lt;/pre&gt;
&lt;ul&gt;
&lt;li&gt;&lt;code&gt;i&lt;/code&gt; ignore cases;&lt;/li&gt;
&lt;/ul&gt;
&lt;pre&gt;&lt;code&gt;const regex = /Regex/i;
// All returns true
regex.test(&apos;regex&apos;);
regex.test(&apos;REGEX&apos;);
regex.test(&apos;rEgEx&apos;);
&lt;/code&gt;&lt;/pre&gt;
&lt;ul&gt;
&lt;li&gt;&lt;code&gt;m&lt;/code&gt; multiline; when it is passed the beginning (&lt;code&gt;^&lt;/code&gt;) and end (&lt;code&gt;$&lt;/code&gt;) characters work with lines instead of the whole input.&lt;/li&gt;
&lt;/ul&gt;
&lt;pre&gt;&lt;code&gt;const text = `
Roses are red
violets are blue
Regex are awesome
so do you`;
/blue$/m.test(text); // true matches the second line end.
/blue$/.test(false);
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;There are two more flags; sticky &lt;code&gt;y&lt;/code&gt; and unicode &lt;code&gt;u&lt;/code&gt; which got introduced in ES6. You can read about them &lt;a href=&quot;https://ponyfoo.com/articles/regular-expressions-post-es6&quot; target=&quot;_blank&quot; rel=&quot;noopener noreferrer&quot;&gt;here&lt;/a&gt;.&lt;/p&gt;
&lt;h3&gt;Grouping and Back References&lt;/h3&gt;
&lt;p&gt;Consider a scenario where we want to check whether a sentence starts and ends with the same word. To achieve it, regex needs some ways to remember the matches. Grouping and back references are used for such scenarios. We use parenthesis &lt;code&gt;()&lt;/code&gt; for grouping. Regex remembers whatever is captured in the group which can be referenced later using &lt;code&gt;\n&lt;/code&gt; where n is the ordered position of group starting from 1. In a regex object groups are referred using &lt;code&gt;$1, $2…&lt;/code&gt;&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;// matches &quot;a&quot; and back reference it using \1
const regex = /(a)b\1d/;
regex.test(&apos;abad&apos;); // true
regex.test(&apos;abd&apos;); // false
// multiple groups
/(a)b(c)\1d\2/.test(&apos;abcadc&apos;); // true
// Regex matches a sentence which starts and ends with same word
const sentenceRegex = /^([\w]+\b).*\1\.$/i;
sentenceRegex.test(&apos;Apple is red so red is apple.&apos;);
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Sometimes we just use grouping for legibility. For such scenarios, we can avoid the performance penalty of remembering them using non-capturing group &lt;code&gt;(?:)&lt;/code&gt;. Non-captured group will not be available to &lt;code&gt;\n&lt;/code&gt;.&lt;/p&gt;
&lt;h3&gt;Assertions (?=) and (?!)&lt;/h3&gt;
&lt;p&gt;When we want to test whether a character/string is followed by a certain character/string or not we use assertions.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;// Matches &quot;Sheldon&quot; followed by &quot;Cooper&quot;
const regex = /Sheldon(?=Cooper)/;
regex.test(&apos;SheldonCooper&apos;); // true, only &quot;Sheldon&quot; is matched
regex.test(&apos;SheldonLeeCooper&apos;); // false
// Matches &quot;Sheldon&quot; not followed by &quot;Cooper&quot;
const regex = /Sheldon(?!Cooper)/;
regex.test(&apos;SheldonCooper&apos;); // false
regex.test(&apos;SheldonLeeCooper&apos;); // true, only &quot;Sheldon&quot; is matched
&lt;/code&gt;&lt;/pre&gt;
&lt;hr /&gt;
&lt;h3&gt;Conclusion&lt;/h3&gt;
&lt;figure class=&quot;text-center invert-on-dark&quot;&gt;
&lt;p&gt;&lt;img src=&quot;https://smellycode.com/_astro/regex-comic.Bd3eZL6w.png&quot; alt=&quot;XKCD Regex Comic&quot; /&gt;
&lt;/p&gt;&lt;figcaption&gt;All Rise! The Regex Man is here.(&lt;a href=&quot;https://xkcd.com/208/&quot; target=&quot;_blank&quot; rel=&quot;noopener noreferrer&quot;&gt;Source&lt;/a&gt;)&lt;/figcaption&gt;&lt;p&gt;&lt;/p&gt;
&lt;/figure&gt;</content:encoded><category>JavaScript</category><category>Regular Expressions</category></item><item><title>A Bit about Binary Tree 🌳</title><link>https://smellycode.com/binary-tree/</link><guid isPermaLink="false">https://smellycode.com/binary-tree/</guid><description>Explanation of Binary Tree with simple words and code.</description><pubDate>Sat, 18 Aug 2018 18:30:00 GMT</pubDate><content:encoded>&lt;p&gt;In the previous post, &lt;a href=&quot;/trees&quot;&gt;A Gentle Introduction to Trees 🌳&lt;/a&gt;, we acquainted ourselves with trees and their properties. We saw that the naturally hierarchical data are well represented using trees. We learned that the topmost element in the hierarchy/tree which does not have any parent is called the root of a tree. Today’s post talks about a special type of tree called Binary Tree.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Binary tree&lt;/strong&gt; is a tree where each node can have maximum two children. Since there are only two children so it’s quite intuitive to call them &lt;code&gt;left&lt;/code&gt; and &lt;code&gt;right&lt;/code&gt; child. Let’s get our hands dirty and code a &lt;code&gt;BinaryTreeNode&lt;/code&gt; class in JavaScript as per the definition above.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;/**
 * Represent a BinaryTreeNode
 */
class BinaryTreeNode {
  constructor(value) {
    // Value which our beloved node represents.
    this.value = value;
    // Reference of the left child.
    this.left = null;
    // Reference of the right child.
    this.right = null;
  }
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Here’s our first binary tree created using the &lt;code&gt;BinaryTreeNode&lt;/code&gt; class.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;const root = new BinaryTreeNode(10);
const left = new BinaryTreeNode(20);
const right = new BinaryTreeNode(30);
root.left = left;
root.right = right;
console.log(root);
// Our first binary tree.
//
//    10
//   /  \
//  20   30
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;This is a naive way to create a binary tree. There are many far better ways to create a binary tree. We will discuss some of them as we move on.&lt;/p&gt;
&lt;p&gt;There are four basic operations &lt;strong&gt;C&lt;/strong&gt;reate, &lt;strong&gt;R&lt;/strong&gt;ead, &lt;strong&gt;U&lt;/strong&gt;pdate and &lt;strong&gt;D&lt;/strong&gt;elete(&lt;strong&gt;CRUD&lt;/strong&gt;), which are performed on every data structure. Let’s perform them on Binary Tree as well. At first, we’ll start with the “Read” operation cause it’s relatively easy(a million thanks to recursion). Also, it will strengthen our bond with the binary tree.&lt;/p&gt;
&lt;h3&gt;Traversal&lt;/h3&gt;
&lt;p&gt;Reading data from a data structure is also known as traversal. As we know Binary Tree is a non-linear data structure. So its data can be traversed in many ways. In general, data traversal for trees is categorized as &lt;strong&gt;Breadth First Traversal&lt;/strong&gt;(&lt;a href=&quot;https://en.wikipedia.org/wiki/Breadth-first_search&quot; target=&quot;_blank&quot; rel=&quot;noopener noreferrer&quot;&gt;BFS&lt;/a&gt;) aka &lt;strong&gt;Level Order Traversal&lt;/strong&gt; and &lt;strong&gt;Depth First Traversal&lt;/strong&gt;(&lt;a href=&quot;https://en.wikipedia.org/wiki/Depth-first_search&quot; target=&quot;_blank&quot; rel=&quot;noopener noreferrer&quot;&gt;DFS&lt;/a&gt;).&lt;/p&gt;
&lt;p&gt;Note. &lt;em&gt;These traversal methods are not specific to binary trees. They can be used for any tree. But, for brevity, we’ll only discuss them for binary trees&lt;/em&gt;.&lt;/p&gt;
&lt;h3&gt;Depth First Traversal&lt;/h3&gt;
&lt;p&gt;In depth-first traversal, we start with the root node and go into the depth of it. We dive deep as much as possible until we reach the end. Once we reach the bottom i.e. the leaf node, we backtrack to traverse other nodes. It’s really important to notice that while diving or backtracking, how are we dealing with the root node or the node acting as root node? Are we traversing root node before diving? Are we traversing root node after backtracking? Answer of these questions leads to 3 new categories of depth-first traversal in-order, pre-order and post-order. I hope I my poor articulation is not confusing you.&lt;/p&gt;
&lt;h3&gt;Inorder Traversal&lt;/h3&gt;
&lt;figure class=&quot;text-center invert-on-dark&quot;&gt;
&lt;p&gt;&lt;img src=&quot;https://smellycode.com/_astro/inorder-traversal.O0zcPhD_.gif&quot; alt=&quot;Inorder Traversal&quot; /&gt;
&lt;/p&gt;&lt;figcaption&gt;Inorder Traversal(&lt;a href=&quot;http://ceadserv1.nku.edu/longa/classes/mat385_resources/docs/traversal.htm&quot; target=&quot;_blank&quot; rel=&quot;noopener noreferrer&quot;&gt;Source&lt;/a&gt;)&lt;/figcaption&gt;&lt;p&gt;&lt;/p&gt;
&lt;/figure&gt;
&lt;p&gt;For in-order traversal, we start with the root node and go to the left of the tree as far as possible until we reach the end or leaf node. If there’s any leaf node, we read its data and backtrack to the immediate parent node or root node. Otherwise, we simply read data from the root node and move the right child, if there’s any, and repeat the same for the right node. The traversal sequence for in-order is &lt;code&gt;left-root-right&lt;/code&gt;. Here are some sample binary trees which we will use for traversing.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;       Sample binary trees
       ====================
    1)                      2)
  -----                   ------
    a                       j
  /   \                   /   \
 b     c                 f     k
                       /  \     \
                      a    h     z
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;For tree 1) and 2), in-order traversals will be &lt;code&gt;b-a-c&lt;/code&gt; and &lt;code&gt;a-f-h-j-k-z&lt;/code&gt;. Let me explain how we got them. For tree 1), we start with its root node i.e. node &lt;code&gt;a&lt;/code&gt; and move to the left that is node &lt;code&gt;b&lt;/code&gt;. Then we again move to the left of node &lt;code&gt;b&lt;/code&gt;. Since there’s no node to visit which means we have reached to the farthest left. We read/print its data and move back(backtrack) to the root node &lt;code&gt;a&lt;/code&gt;. We read data from it and move to its right child that is node &lt;code&gt;c&lt;/code&gt;. and repeat the same for it. Similarly, we can traverse tree 2).&lt;/p&gt;
&lt;p&gt;Let’s see how does it look in the code.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;/**
 * Prints the values of binary tree in-order.
 *
 */
const traverseInorder = root =&amp;gt; {
  if (root === null) {
    return;
  }

  // Traverse the left node.
  traverseInorder(root.left);

  // Print root node&apos;s value.
  console.log(root.value);

  //Traverse the right node.
  traverseInorder(root.right);
};
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;We learned from our &lt;a href=&quot;/trees&quot;&gt;previous post&lt;/a&gt; that trees are recursive in nature. So we leveraged their recursiveness and wrote a recursive function &lt;code&gt;traverseInorder&lt;/code&gt; which traverses a binary tree in order. As we know that for every recursive solution there’s an equivalent iterative solution. And we can go with the iterative solution as well but to keep it simple we will continue with recursion and will discuss the iterative solution on some other day.&lt;/p&gt;
&lt;p&gt;In-order traversal is commonly used for &lt;a href=&quot;https://en.wikipedia.org/wiki/Binary_search_tree&quot; target=&quot;_blank&quot; rel=&quot;noopener noreferrer&quot;&gt;binary search tree&lt;/a&gt; cause for BST it retrieves data in sorted order.&lt;/p&gt;
&lt;h3&gt;Preorder Traversal&lt;/h3&gt;
&lt;figure class=&quot;text-center invert-on-dark&quot;&gt;
&lt;p&gt;&lt;img src=&quot;https://smellycode.com/_astro/pre-order.BQQxQMV6.gif&quot; alt=&quot;Preorder Traversal&quot; /&gt;
&lt;/p&gt;&lt;figcaption&gt;Preorder Traversal(&lt;a href=&quot;http://ceadserv1.nku.edu/longa/classes/mat385_resources/docs/traversal.htm&quot; target=&quot;_blank&quot; rel=&quot;noopener noreferrer&quot;&gt;Source&lt;/a&gt;)&lt;/figcaption&gt;&lt;p&gt;&lt;/p&gt;
&lt;/figure&gt;
&lt;p&gt;Pre-order traversal is similar to in-order. The only difference is we traverse the root node first then, we move to the left and the right child. The traversal sequence is &lt;code&gt;root-left-right&lt;/code&gt;. For tree 1) and 2) in our boring example pre-order traversals are &lt;code&gt;a-b-c&lt;/code&gt; and &lt;code&gt;j-f-a-h-k-z&lt;/code&gt;. Here’s the Js code.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;/**
 * Print the values of binary tree in pre-order.
 *
 */
const traversePreOrder = root =&amp;gt; {
  if (root === null) {
    return;
  }
  // Print root node&apos;s value.
  console.log(root.value);
  // Traverse the left node.
  traversePreOrder(root.left);
  //Traverse the right node.
  traversePreOrder(root.right);
};
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;If you look at the code, you’ll realize that we have only changed the order of statement compared to in-order traversal. And that’s all is required.&lt;/p&gt;
&lt;h3&gt;Postorder Traversal&lt;/h3&gt;
&lt;figure class=&quot;text-center invert-on-dark&quot;&gt;
&lt;p&gt;&lt;img src=&quot;https://smellycode.com/_astro/post-order.ByYDE190.gif&quot; alt=&quot;Post Traversal&quot; /&gt;
&lt;/p&gt;&lt;figcaption&gt;Post Traversal(&lt;a href=&quot;http://ceadserv1.nku.edu/longa/classes/mat385_resources/docs/traversal.htm&quot; target=&quot;_blank&quot; rel=&quot;noopener noreferrer&quot;&gt;Source&lt;/a&gt;)&lt;/figcaption&gt;&lt;p&gt;&lt;/p&gt;
&lt;/figure&gt;
&lt;p&gt;In post-order traversal, we traverse the root node in the end. The traversal sequence is &lt;code&gt;left-right-root&lt;/code&gt;. For tree 1) and 2) post-order traversal will be &lt;code&gt;b-c-a&lt;/code&gt; and &lt;code&gt;a-h-f-z-k-j&lt;/code&gt;. Js code:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;/**
 * Print the values of binary tree in post-order.
 *
 */
const traversePostOrder = root =&amp;gt; {
  if (root === null) {
    return;
  }
  // Traverse the left node.
  traversePostOrder(root.left);
  //Traverse the right node.
  traversePostOrder(root.right);
  // Print root node&apos;s value.
  console.log(root.value);
};
&lt;/code&gt;&lt;/pre&gt;
&lt;h3&gt;Breadth First Traversal&lt;/h3&gt;
&lt;p&gt;In the breadth-first traversal, we traverse tree horizontally i.e. we traverse tree by levels. We start with the root node (or first level), explore it and move to the next level. Then traverse all the nodes present on that level and move to the next level. We do the same for all remaining levels. Since nodes are traversed by levels, so breadth-first-traversal is also referred as Level Order Traversal. Here’s an illustration.&lt;/p&gt;
&lt;figure class=&quot;text-center invert-on-dark&quot;&gt;
&lt;p&gt;&lt;img src=&quot;https://smellycode.com/_astro/binary-tree-cover-img.BowObdm-.gif&quot; alt=&quot;Depth-First vs Breadth-First&quot; /&gt;
&lt;/p&gt;&lt;figcaption&gt;Depth-First vs Breadth-First(&lt;a href=&quot;http://ceadserv1.nku.edu/longa/classes/mat385_resources/docs/traversal.htm&quot; target=&quot;_blank&quot; rel=&quot;noopener noreferrer&quot;&gt;Source&lt;/a&gt;)&lt;/figcaption&gt;&lt;p&gt;&lt;/p&gt;
&lt;/figure&gt;
&lt;p&gt;We accomplish level order traversal with the help of a &lt;code&gt;queue&lt;/code&gt;. We create an empty queue and enqueue the &lt;code&gt;root&lt;/code&gt; node. Then we do the followings, while the queue is not empty.&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;Dequeue a node.&lt;/li&gt;
&lt;li&gt;Explore the node.&lt;/li&gt;
&lt;li&gt;If the node has a left child, enqueue it.&lt;/li&gt;
&lt;li&gt;If the node has a right child, enqueue it.&lt;/li&gt;
&lt;/ol&gt;
&lt;pre&gt;&lt;code&gt;/**
 * Traverses  binary tree in level order.
 *
 */
const levelOrder = root =&amp;gt; {
  if (root === null) {
    return;
  }

  const queue = [root];
  while (queue.length) {
    const node = queue.shift();
    // pirnt/explore node.
    console.log(node.value);
    // enqueue left
    if (node.left !== null) {
      queue.push(node.left);
    }
    // enqueue right.
    if (node.right !== null) {
      queue.push(node.right);
    }
  }
};
&lt;/code&gt;&lt;/pre&gt;
&lt;h3&gt;Create&lt;/h3&gt;
&lt;p&gt;There’s no restriction on the data stored in a binary tree which gives us the flexibility to create it. We will discuss following two popular methods to create a binary tree:&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;From array representation.&lt;/li&gt;
&lt;li&gt;Level Order Insertion.&lt;/li&gt;
&lt;/ol&gt;
&lt;h3&gt;From array representation&lt;/h3&gt;
&lt;p&gt;A binary tree can also be represented using an array. For child &lt;code&gt;i&lt;/code&gt;, in the array representation, the left child will be at &lt;code&gt;2*i + 1&lt;/code&gt; and the right child will be at &lt;code&gt;2*i + 2&lt;/code&gt;. The &lt;code&gt;index&lt;/code&gt; of the &lt;code&gt;root&lt;/code&gt; node is &lt;code&gt;0&lt;/code&gt;. Here’s the JS code to create binary tree from array representation.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;/**
 * Creates a binary tree from it&apos;s array representation.
 *
 * @param {any[]} array
 */
const createTree = array =&amp;gt; {
  if (!array.length) {
    return null;
  }
  const nodes = array.map(value =&amp;gt;
    value !== null ? new BinaryTreeNode(value) : null
  );
  nodes.forEach((node, index) =&amp;gt; {
    if (node === null) {
      return;
    }
    const doubleOfIndex = 2 * index;
    // Left node -&amp;gt; (2 * i) + 1.
    const lIndex = doubleOfIndex + 1;
    if (lIndex &amp;lt; array.length) {
      node.left = nodes[lIndex];
    }
    // Right node -&amp;gt; (2 * i) + 2.
    const rIndex = doubleOfIndex + 2;
    if (rIndex &amp;lt; array.length) {
      node.right = nodes[rIndex];
    }
  });
  return nodes[0];
};
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Let’s consider an array and use above function to create a binary tree.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;const array = [1, 2, 3, 4, 5, 6];
const tree = createTree(array);
console.log(tree);
// Tree represented by array.
//                1
//             /     \
//            2       3
//          /  \     /
//         4    5   6
&lt;/code&gt;&lt;/pre&gt;
&lt;h3&gt;Level Order Insertion&lt;/h3&gt;
&lt;p&gt;In this approach, we insert an item at the first available position in the level order.&lt;/p&gt;
&lt;figure class=&quot;invert-on-dark&quot;&gt;
&lt;p&gt;&lt;img src=&quot;https://smellycode.com/_astro/level-order-insertion.7H_0AoYk.png&quot; alt=&quot;Level Order Insertion&quot; /&gt;&lt;/p&gt;
&lt;/figure&gt;
&lt;p&gt;Since we are inserting values in level order, so we can use iterative level order traversal. If we find a node whose left child is null then we assign a new node to its left child. Else if we find a node whose right child is null then we assign a new node to its right child. We keep traversing until we find a left or a right null/empty child. Here’s the JS code for level order insertion.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;/**
 * Insert the value into the binary tree at
 * first position available in level order.
 *
 */
const insertInLevelOrder = (root, value) =&amp;gt; {
  const node = new BinaryTreeNode(value);
  if (root === null) {
    return node;
  }
  const queue = [root];
  while (queue.length) {
    const _node = queue.shift();
    if (_node.left === null) {
      _node.left = node;
      break;
    }
    queue.push(_node.left);
    if (_node.right === null) {
      _node.right = node;
      break;
    }
    queue.push(_node.right);
  }
  return root;
};
&lt;/code&gt;&lt;/pre&gt;
&lt;h3&gt;Update&lt;/h3&gt;
&lt;p&gt;Updating a value of a node in a binary tree is relatively easy, cause values stored in a binary tree doesn’t have to maintain any specific tree property. To update the value, we simply find the node, whose value is being updated, using one of the traversals discussed above and replace its value.&lt;/p&gt;
&lt;h3&gt;Delete&lt;/h3&gt;
&lt;p&gt;Deleting a node form a binary tree is not as easy as it seems. It’s because there are so many scenarios which we need to deal with while deleting. Scenarios like:&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;Is targeted node a leaf node?&lt;/li&gt;
&lt;li&gt;Does targeted node only have a left child?&lt;/li&gt;
&lt;li&gt;Does targeted node only have a right child?&lt;/li&gt;
&lt;li&gt;Does targeted node have both the left and the right child?&lt;/li&gt;
&lt;li&gt;Are we only deleting the node and not its subtree?&lt;/li&gt;
&lt;li&gt;Are we deleting both the node and its subtree?
To avoid intricacies, we’ll only consider case 6 here i.e. we delete both the node and its subtrees. We’ll discuss other scenarios someday with Binary Search Tree.&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;To delete/remove a node from its subtree we need the reference of its parent. If the target is on the left of parent then we set left of the parent to null else we set right of the parent to null. We let the garbage collector take care of the reset i.e. removing subtrees and freeing the memory. We are simply setting the reference to null, so it doesn’t matter which traversal we use. We’ll end up with the same result, but &lt;a href=&quot;/asymptotic-notations&quot;&gt;time and space complexities&lt;/a&gt; may vary. Let’s use Breadth-First Traversal for now.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;/**
 * Removes a node and it&apos;s subtrees from a
 * binary tree.
 * @param root
 * @value
 *
 * @return updated root.
 */
const remove = (root, value) =&amp;gt; {
  if (root === null) {
    return null;
  }
  if (root.value === value) {
    return null;
  }
  const queue = [root];
  while (queue.length) {
    const node = queue.shift();

    // If target is on left of parent.
    if (node.left &amp;amp;&amp;amp; node.left.value === value) {
      node.left = null;
      return root;
    }
    queue.push(node.left);

    // If target is on right of parent.
    if (node.right &amp;amp;&amp;amp; node.right.value === value) {
      node.right = null;
      return root;
    }
    queue.push(node.right);
  }
  return root;
};
let tree = fromArrayRepresentation([1, 2, 3, 4]);
tree = remove(tree, 2); // Remove 2 and 4(its child of 2).
console.log(tree);
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Note: If a language(like C or C++) doesn’t have the garbage collector, then we may need to traverse the tree in post-order remove the children first before deleting the targeted node. For more detail please refer &lt;a href=&quot;https://www.geeksforgeeks.org/write-a-c-program-to-delete-a-tree/&quot; target=&quot;_blank&quot; rel=&quot;noopener noreferrer&quot;&gt;here&lt;/a&gt;.&lt;/p&gt;
&lt;h3&gt;Summary&lt;/h3&gt;
&lt;p&gt;Binary Tree is a special tree in which each node can at most contain two children called left and right. To read/traverse data from a binary tree we have two major approaches Depth-First Traversal and Breadth-First Traversal. Depth-First traversal is further classified in pre-order, in-order, post-order traversal. In depth-first traversal, we visit the node and its children first, then we visit siblings of the node. In breadth-first traversal, we visit the node and its siblings(nodes which are at the same level) first, then we move to the next level. Depth-First traversal is also referred as Level Order Traversal. There are many ways to create a binary tree. One can create a binary tree from its array representation. In array representation value at ith, index will have children at &lt;code&gt;2*i + 1&lt;/code&gt; and &lt;code&gt;2*i + 2&lt;/code&gt;. A binary tree can also be created using level order insertion where any new value is inserted at first available position in the level order. Updating a value in a binary tree is relatively easy because values in a binary tree don’t maintain any specific property with respect to each other. Among all operations, deleting a node is a bit complicated cause a node may carry children. So we have to take care of its children as well.&lt;/p&gt;
&lt;hr /&gt;
&lt;p&gt;I have created &lt;a href=&quot;https://github.com/hk-skit/competitive-programming&quot; target=&quot;_blank&quot; rel=&quot;noopener noreferrer&quot;&gt;a repository on Github&lt;/a&gt; which contains the implementation of the binary tree along with many other data structures in JavaScript. Please feel free to fork/clone it. If you have any suggestion or correction, please post them in the comment section. Thank you for reading.&lt;/p&gt;
</content:encoded><category>JavaScript</category><category>Data Structures</category><category>Algorithms</category><category>Trees</category></item><item><title>A Gentle Introduction to Trees 🌳</title><link>https://smellycode.com/trees/</link><guid isPermaLink="false">https://smellycode.com/trees/</guid><description>An overview of the tree data structure.</description><pubDate>Sat, 14 Jul 2018 18:30:00 GMT</pubDate><content:encoded>&lt;figure class=&quot;text-center&quot;&gt;
&lt;p&gt;&lt;img src=&quot;https://smellycode.com/_astro/trees-cover-img.Cyz1PSvL.jpeg&quot; alt=&quot;&quot; /&gt;
&lt;/p&gt;&lt;figcaption&gt;
&lt;a href=&quot;https://medium.com/smelly-code/a-gentle-introduction-to-trees-b907a966dad2&quot; target=&quot;_blank&quot;&gt;
Source
&lt;/a&gt;
&lt;/figcaption&gt;&lt;p&gt;&lt;/p&gt;
&lt;/figure&gt;
&lt;p&gt;Most of the time when people embark upon the journey of learning data structures, they get started with linear data structures like array, stack, linked list, queue etc. And if the journey “continues”, they acquaint themselves with non-linear data structures like trees and graphs. Fortunately, I continued the journey and stumbled upon an infamous non-linear data structure called Tree. In this series of post, we’ll take a closer look at trees and different types of trees like Binary Tree, Binary Search Tree.&lt;/p&gt;
&lt;p&gt;Let’s first understand linear and non-linear data structures before starting with trees.&lt;/p&gt;
&lt;h3&gt;Linear Data Structure:&lt;/h3&gt;
&lt;blockquote&gt;
&lt;p&gt;“A data structure is a linear data structure if its data items(elements) form a sequence or a linear list”.&lt;/p&gt;
&lt;/blockquote&gt;
&lt;p&gt;In plain English, linear data structures have a logical beginning and a logical end. Examples: array, stack, linked list, queue.&lt;/p&gt;
&lt;figure class=&quot;text-center invert-on-dark&quot;&gt;
&lt;p&gt;&lt;img src=&quot;https://smellycode.com/_astro/linear-ds.D4hX7BlS.png&quot; alt=&quot;&quot; /&gt;
&lt;/p&gt;&lt;figcaption&gt;
&lt;a href=&quot;https://www.youtube.com/watch?v=qH6yxkw0u78&quot; target=&quot;_blank&quot;&gt;
MyCodeSchool
&lt;/a&gt;
&lt;/figcaption&gt;&lt;p&gt;&lt;/p&gt;
&lt;/figure&gt;
&lt;h3&gt;Non-Linear Data Structure:&lt;/h3&gt;
&lt;p&gt;Unlike linear data structures, elements of a non-linear data structure do not form a sequence because of that they can be traversed in any desired order or non-sequential order. Examples: Tree, Graph etc.&lt;/p&gt;
&lt;p&gt;As a programmer, we often need to decide which data structure to use. Should we use a linked list ? or should we use a stack? Or Should we always use an array? Well, the choice of data structure depends upon the circumstances.&lt;/p&gt;
&lt;blockquote&gt;
&lt;p&gt;“Bad programmers worry about the code. Good programmers worry about data structures and their relationships.” ~ Linus Torvalds&lt;/p&gt;
&lt;/blockquote&gt;
&lt;p&gt;One may take the following factors into considerations:&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;What needs to be stored ?&lt;/li&gt;
&lt;li&gt;Memory usages or consumptions.&lt;/li&gt;
&lt;li&gt;Ease of implementation.&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;Let’s address the elephant in the room.
Trees are basically non-linear data structures which are mostly used to organize data in a hierarchical way. Let’s take some of the real life examples.&lt;/p&gt;
&lt;p&gt;Here the Stark Family Tree from Game of Thrones.&lt;/p&gt;
&lt;figure class=&quot;text-center invert-on-dark&quot;&gt;
&lt;p&gt;&lt;img src=&quot;https://smellycode.com/_astro/stark_family.CkagHGtq.jpeg&quot; alt=&quot;&quot; /&gt;
&lt;/p&gt;&lt;figcaption&gt;
Game of Thrones: Stark family tree (
&lt;a href=&quot;https://www.express.co.uk/showbiz/tv-radio/830578/game-of-thrones-family-tree-season-stark-targaryen-lannister-greyjoy&quot; target=&quot;_blank&quot;&gt;
Source
&lt;/a&gt;)
&lt;/figcaption&gt;&lt;p&gt;&lt;/p&gt;
&lt;/figure&gt;
&lt;p&gt;By looking at this tree, we can easily define relationships between each character.&lt;/p&gt;
&lt;p&gt;We can say that &lt;code&gt;Rickard&lt;/code&gt; and &lt;code&gt;Unknown&lt;/code&gt;(yet to be revealed) are grandparents of &lt;code&gt;Arya&lt;/code&gt; and her siblings i.e. &lt;code&gt;Robb&lt;/code&gt;, &lt;code&gt;Sansa&lt;/code&gt;, &lt;code&gt;Bran&lt;/code&gt;, &lt;code&gt;Rickon&lt;/code&gt;, and &lt;code&gt;Eddard&lt;/code&gt; &amp;amp; &lt;code&gt;Catelyn&lt;/code&gt; are their parents.&lt;/p&gt;
&lt;p&gt;Also &lt;code&gt;Arya&lt;/code&gt; and &lt;code&gt;Jon Snow&lt;/code&gt; are cousin cause their parents are siblings. I hope &lt;code&gt;Jon Snow&lt;/code&gt; at least knows this 😄.&lt;/p&gt;
&lt;p&gt;Here’s another example which shows tree of a directory on file system.&lt;/p&gt;
&lt;figure class=&quot;text-center invert-on-dark&quot;&gt;
&lt;p&gt;&lt;img src=&quot;https://smellycode.com/_astro/file_system.CaSQmrj0.gif&quot; alt=&quot;&quot; /&gt;
&lt;/p&gt;&lt;figcaption&gt;
&lt;a href=&quot;http://itwebtutorials.mga.edu/html/chp7/traversing-folders.aspx&quot; target=&quot;_blank&quot;&gt;
Middle Georgia University
&lt;/a&gt;
&lt;/figcaption&gt;&lt;p&gt;&lt;/p&gt;
&lt;/figure&gt;
&lt;h3&gt;Tree Terminology:&lt;/h3&gt;
&lt;pre&gt;&lt;code&gt; Sample tree
  -----------
       j    &amp;lt;-- root
     /   \
    f      k
  /   \      \  &amp;lt;-- edge
 a     h      z    &amp;lt;-- leaves
&lt;/code&gt;&lt;/pre&gt;
&lt;ul&gt;
&lt;li&gt;
&lt;p&gt;&lt;code&gt;node&lt;/code&gt;: A basic entity in tree which can contain &lt;code&gt;data&lt;/code&gt; or &lt;code&gt;value&lt;/code&gt; and references to other &lt;code&gt;nodes&lt;/code&gt;. We can say, a tree is collection of these nodes. In above sample tree &lt;code&gt;j&lt;/code&gt;, &lt;code&gt;f&lt;/code&gt;, &lt;code&gt;k&lt;/code&gt;, &lt;code&gt;a&lt;/code&gt;, &lt;code&gt;h&lt;/code&gt;, and &lt;code&gt;z&lt;/code&gt; are nodes of the tree.&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;&lt;code&gt;root&lt;/code&gt;: is the top most node of a tree. &lt;code&gt;j&lt;/code&gt; is the root node.&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;&lt;code&gt;children&lt;/code&gt;: &lt;code&gt;f&lt;/code&gt; and &lt;code&gt;k&lt;/code&gt; are children of &lt;code&gt;j&lt;/code&gt;. Similarly &lt;code&gt;a&lt;/code&gt; &amp;amp; &lt;code&gt;h&lt;/code&gt; are children of &lt;code&gt;f&lt;/code&gt; while &lt;code&gt;z&lt;/code&gt; is child of &lt;code&gt;k&lt;/code&gt;.&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;&lt;code&gt;parent&lt;/code&gt;: &lt;code&gt;j&lt;/code&gt; is parent of &lt;code&gt;f&lt;/code&gt; and &lt;code&gt;k&lt;/code&gt;, and grandparent of &lt;code&gt;a&lt;/code&gt;, &lt;code&gt;h&lt;/code&gt; and &lt;code&gt;z&lt;/code&gt;.&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;&lt;code&gt;sibling&lt;/code&gt;: children which have same parent are called sibling. &lt;code&gt;f&lt;/code&gt; and &lt;code&gt;k&lt;/code&gt; are sibling. &lt;code&gt;a&lt;/code&gt; and &lt;code&gt;h&lt;/code&gt; are also siblings. But &lt;code&gt;z&lt;/code&gt; is cousin of &lt;code&gt;a&lt;/code&gt; and &lt;code&gt;h&lt;/code&gt; cause their parents are siblings.&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;&lt;code&gt;leaf&lt;/code&gt;: A node with no child is called &lt;code&gt;leaf&lt;/code&gt; node. Here &lt;code&gt;a&lt;/code&gt;, &lt;code&gt;h&lt;/code&gt; and &lt;code&gt;z&lt;/code&gt; are leaf node.&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;&lt;code&gt;edge&lt;/code&gt;: Nodes are connected by edges. Sometimes edges are also referred as &lt;code&gt;links&lt;/code&gt;.&lt;/p&gt;
&lt;/li&gt;
&lt;/ul&gt;
&lt;h3&gt;Tree Properties:&lt;/h3&gt;
&lt;pre&gt;&lt;code&gt;Sample tree
   -----------
       j    &amp;lt;-- root - L-0
     /   \
    f      k         - L-1
  /   \      \
 a     h      z      - L-2
&lt;/code&gt;&lt;/pre&gt;
&lt;ol&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;A tree with&lt;/strong&gt; &lt;code&gt;n&lt;/code&gt; &lt;strong&gt;nodes will have exacly&lt;/strong&gt; &lt;code&gt;n-1&lt;/code&gt; &lt;strong&gt;edges or links&lt;/strong&gt; (Tree with only root node has &lt;code&gt;0&lt;/code&gt; link/edge). In the sample tree, we have 6 nodes and 5 edges (6 - 1).&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;The Depth of node&lt;/strong&gt; &lt;code&gt;x&lt;/code&gt; &lt;strong&gt;= length of the path from the&lt;/strong&gt; &lt;code&gt;root&lt;/code&gt; &lt;strong&gt;to node&lt;/strong&gt; &lt;code&gt;x&lt;/code&gt;. Length of a path is basically the number of edges in the path. So we can say that &lt;strong&gt;the depth of node&lt;/strong&gt; &lt;code&gt;x&lt;/code&gt; &lt;strong&gt;is the number of edges in the path from the&lt;/strong&gt; &lt;code&gt;root&lt;/code&gt; &lt;strong&gt;to&lt;/strong&gt; &lt;code&gt;x&lt;/code&gt;. The depth of the root node is 0. In the sample tree, depth of nodes &lt;code&gt;f&lt;/code&gt; and &lt;code&gt;k&lt;/code&gt; is 1, and depth of nodes &lt;code&gt;a&lt;/code&gt;, &lt;code&gt;h&lt;/code&gt; and &lt;code&gt;z&lt;/code&gt; is 2. &lt;strong&gt;Nodes with the same depth have the same level the in tree&lt;/strong&gt;. We can see &lt;code&gt;f&lt;/code&gt; and &lt;code&gt;k&lt;/code&gt; have the same depth and they are at the same level L-1.&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;The Height of node&lt;/strong&gt; &lt;code&gt;x&lt;/code&gt; &lt;strong&gt;= number of edges in the longest path from&lt;/strong&gt; &lt;code&gt;x&lt;/code&gt; &lt;strong&gt;to a&lt;/strong&gt; &lt;code&gt;leaf&lt;/code&gt; &lt;strong&gt;node&lt;/strong&gt;. The height of a &lt;code&gt;leaf&lt;/code&gt; node is 0 and the height of an empty tree is considered as -1. The height of a tree can be defined by the height of &lt;code&gt;root&lt;/code&gt; node.&lt;/p&gt;
&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;&lt;strong&gt;Note:&lt;/strong&gt; In some books, &lt;strong&gt;the depth of a node&lt;/strong&gt; &lt;code&gt;x&lt;/code&gt; is referred to the number of nodes in the path from the &lt;code&gt;root&lt;/code&gt; to node &lt;code&gt;x&lt;/code&gt;. In that case, depth of the of the &lt;code&gt;root&lt;/code&gt; node will be 1. Similarly, &lt;strong&gt;the height of the node&lt;/strong&gt; &lt;code&gt;x&lt;/code&gt; is also referred as &lt;em&gt;the number of nodes in the longest path from node&lt;/em&gt; &lt;code&gt;x&lt;/code&gt; &lt;em&gt;to&lt;/em&gt; &lt;code&gt;leaf&lt;/code&gt; &lt;em&gt;node&lt;/em&gt; which means the height of leaf node will be 1 and height of empty tree will be 0 instead of -1. In this series of posts, we will consider this definition of height and depth. You can read detailed discussion on depth and height &lt;a href=&quot;https://stackoverflow.com/questions/2603692/what-is-the-difference-between-tree-depth-and-height&quot;&gt;here&lt;/a&gt;.&lt;/p&gt;
&lt;p&gt;Another notable property of trees which make them super-powerful is their recursive nature.&lt;/p&gt;
&lt;blockquote&gt;
&lt;p&gt;Yes, Trees are recursive in nature.&lt;/p&gt;
&lt;/blockquote&gt;
&lt;p&gt;It means that a tree is composed of many small trees called &lt;code&gt;subtree&lt;/code&gt;. If we ignore root node then every node in a tree represents a subtree. This property of trees helps us to write recursive algorithms for many operations like search and traversal, which are extremely simple to grok and implement.&lt;/p&gt;
&lt;h3&gt;Applications:&lt;/h3&gt;
&lt;p&gt;Here are some common uses of trees taken from &lt;a href=&quot;https://en.wikipedia.org/wiki/Tree_%28data_structure%29#Common_uses&quot;&gt;Wikipedia&lt;/a&gt;.&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;Representing &lt;a href=&quot;https://en.wikipedia.org/wiki/Hierarchical&quot;&gt;hierarchical&lt;/a&gt; data.&lt;/li&gt;
&lt;li&gt;Storing data in a way that makes it efficiently &lt;a href=&quot;https://en.wikipedia.org/wiki/Search_algorithm&quot;&gt;searchable&lt;/a&gt; .&lt;/li&gt;
&lt;li&gt;Representing &lt;a href=&quot;https://en.wikipedia.org/wiki/Sorting_algorithm&quot;&gt;sorted lists&lt;/a&gt; of data.&lt;/li&gt;
&lt;li&gt;As a workflow for &lt;a href=&quot;https://en.wikipedia.org/wiki/Digital_compositing&quot;&gt;compositing&lt;/a&gt; digital images for &lt;a href=&quot;https://en.wikipedia.org/wiki/Visual_effects&quot;&gt;visual effects&lt;/a&gt;.&lt;/li&gt;
&lt;li&gt;Router algorithms.&lt;/li&gt;
&lt;/ul&gt;
&lt;hr /&gt;
&lt;p&gt;Here’s a sample Tree class with a countLeaves method which counts the number of leaf nodes in a tree inspired by &lt;a href=&quot;http://raganwald.com/2018/05/20/we-dont-need-no-stinking-recursion.html&quot;&gt;Raganwald post on stinking recursion&lt;/a&gt;.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;class Tree {
  constructor(...children) {
    this.children = children;
  }
  countLeaves() {
    if (!this.children.length) {
      return 1;
    }
    return this.children.reduce((leaves, child) =&amp;gt; {
      return leaves + child.countLeaves();
    }, 0);
  }
}
const tree = new Tree(new Tree(new Tree()), new Tree());
console.log(tree.countLeaves()); // 2 leaves
&lt;/code&gt;&lt;/pre&gt;
</content:encoded><category>Data Structures</category><category>Trees</category><category>Algorithms</category><category>JavaScript</category></item><item><title>Demystifying Interpolation formula for Interpolation Search</title><link>https://smellycode.com/interpolation-formula/</link><guid isPermaLink="false">https://smellycode.com/interpolation-formula/</guid><description>A quick explanation of interpolation formula used in Interpolation Search.</description><pubDate>Fri, 19 Jan 2018 18:30:00 GMT</pubDate><content:encoded>&lt;p&gt;&lt;a href=&quot;https://en.wikipedia.org/wiki/Interpolation_search&quot;&gt;Interpolation Search&lt;/a&gt; is similar to &lt;a href=&quot;https://hiteshkumar.dev/binging-binary-search/&quot;&gt;Binary Search&lt;/a&gt;. In Binary Search, we always calculate middle of the array and compare it with the key. If the key is equal to mid then we return otherwise we reduce our array to subarray based on our comparison. But, with Interpolation Search, instead of calculating the mid, we apply interpolation formula on our &lt;a href=&quot;http://disq.us/p/1djabdw&quot;&gt;uniformly distributed array/input&lt;/a&gt; to calculate the nearest position to the key.
As mentioned on &lt;a href=&quot;https://www.geeksforgeeks.org/interpolation-search/&quot;&gt;GeeksforGeeks&lt;/a&gt;,&lt;/p&gt;
&lt;blockquote&gt;
&lt;p&gt;the idea of the formula is to return higher value of position when the element to be searched is
closer to the end of the array OR to return smaller value of the position when the element to be
searched is closer to the beginning of the array.&lt;/p&gt;
&lt;/blockquote&gt;
&lt;p&gt;Let’s consider a real-life example to grok it better. Suppose you want to search “Yoyo” in a dictionary. If you follow traditional binary search, you’ll flip to the middle of the dictionary and lexically compare the word “Yoyo” with the middle word. But if you apply interpolation search, you’ll flip directly somewhere closer to the end of the dictionary since you know that word “Yoyo” will be closer to the end.&lt;/p&gt;
&lt;h3&gt;Derivation&lt;/h3&gt;
&lt;p&gt;To understand the formula let’s derive it. Suppose we have a linear function y = f(x) where the relationship between y and x is defined in the diagram below.&lt;/p&gt;
&lt;figure class=&quot;text-center invert-on-dark&quot;&gt;
&lt;p&gt;&lt;img src=&quot;https://smellycode.com/_astro/linear-function.C5YYGkTk.png&quot; alt=&quot;&quot; /&gt;
&lt;/p&gt;&lt;figcaption&gt;Linear Function y = f(x).&lt;/figcaption&gt;&lt;p&gt;&lt;/p&gt;
&lt;/figure&gt;
&lt;p&gt;Consider two points (x1, y1) and (x2, y2) where &lt;code&gt;y1 = f(x1)&lt;/code&gt; and &lt;code&gt;y2 = f(x2) ∀ x1 &amp;lt; x2&lt;/code&gt;. Let’s place them somewhere on the graph.&lt;/p&gt;
&lt;figure class=&quot;text-center invert-on-dark&quot;&gt;
&lt;p&gt;&lt;img src=&quot;https://smellycode.com/_astro/linear-function_2.BXfT1aZ-.png&quot; alt=&quot;&quot; /&gt;
&lt;/p&gt;&lt;figcaption&gt;y = f(x) with (x1, y1) and (x2, y2)&lt;/figcaption&gt;&lt;p&gt;&lt;/p&gt;
&lt;/figure&gt;
&lt;p&gt;Suppose we want to find an &lt;code&gt;x&lt;/code&gt; where &lt;code&gt;x1 &amp;lt;= x &amp;lt;= x2&lt;/code&gt; for a given value of y such that &lt;code&gt;y = f(x)&lt;/code&gt;. How can we find it? We can use trigonometry.&lt;/p&gt;
&lt;figure class=&quot;text-center invert-on-dark&quot;&gt;
&lt;p&gt;&lt;img src=&quot;https://smellycode.com/_astro/interpolation-formula-cover-img.DYkAMlpp.png&quot; alt=&quot;&quot; /&gt;
&lt;/p&gt;&lt;figcaption&gt;Deriving Interpolation Formula with Trigonometry&lt;/figcaption&gt;&lt;p&gt;&lt;/p&gt;
&lt;/figure&gt;
&lt;p&gt;As depicted in the diagram above, the value of tan𝛳 for △ABC will be equal to the value of tan𝛳 for △ADE. From &lt;a href=&quot;https://www.grc.nasa.gov/www/BGH/sincos.html&quot;&gt;trigonometry&lt;/a&gt;, we know that&lt;/p&gt;
&lt;figure class=&quot;invert-on-dark&quot;&gt;
&lt;p&gt;&lt;img src=&quot;https://smellycode.com/_astro/tangent.jr3syzwn.png&quot; alt=&quot;&quot; /&gt;&lt;/p&gt;
&lt;/figure&gt;
&lt;p&gt;It means tan𝛳 for △ABC is:&lt;/p&gt;
&lt;figure class=&quot;invert-on-dark&quot;&gt;
&lt;p&gt;&lt;img src=&quot;https://smellycode.com/_astro/tangent_1.qNnkCcBK.png&quot; alt=&quot;&quot; /&gt;&lt;/p&gt;
&lt;/figure&gt;
&lt;p&gt;And tan𝛳 for △ADE is:&lt;/p&gt;
&lt;figure class=&quot;invert-on-dark&quot;&gt;
&lt;p&gt;&lt;img src=&quot;https://smellycode.com/_astro/tangent_2.DvG0Uanh.png&quot; alt=&quot;&quot; /&gt;&lt;/p&gt;
&lt;/figure&gt;
&lt;p&gt;Since angle 𝛳 is same for both triangles. Therefore, we can say&lt;/p&gt;
&lt;figure class=&quot;invert-on-dark&quot;&gt;
&lt;p&gt;&lt;img src=&quot;https://smellycode.com/_astro/tangent_3.JFtNoGkL.png&quot; alt=&quot;&quot; /&gt;&lt;/p&gt;
&lt;/figure&gt;
&lt;p&gt;which implies that&lt;/p&gt;
&lt;figure class=&quot;invert-on-dark&quot;&gt;
&lt;p&gt;&lt;img src=&quot;https://smellycode.com/_astro/interpolation_formula_1.CVsSB2c4.png&quot; alt=&quot;&quot; /&gt;&lt;/p&gt;
&lt;/figure&gt;
&lt;p&gt;Or we can say that&lt;/p&gt;
&lt;figure class=&quot;invert-on-dark&quot;&gt;
&lt;p&gt;&lt;img src=&quot;https://smellycode.com/_astro/interpolation_formula_2.t-BPy74-.png&quot; alt=&quot;&quot; /&gt;&lt;/p&gt;
&lt;/figure&gt;
&lt;p&gt;Let’s see how this formula can help us to find mid for interpolation search. If we consider our input array as a function f(x) then&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;x1 =&amp;gt; low and y1 =&amp;gt; array[low]
x2 =&amp;gt; high and y2 =&amp;gt; array[high]
x =&amp;gt; pos and y =&amp;gt; array[pos] i.e. key.
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;After putting these values in formula&lt;/p&gt;
&lt;figure class=&quot;invert-on-dark&quot;&gt;
&lt;p&gt;&lt;img src=&quot;https://smellycode.com/_astro/interpolation_formula.D1rW4KxT.png&quot; alt=&quot;&quot; /&gt;&lt;/p&gt;
&lt;/figure&gt;
&lt;hr /&gt;
&lt;p&gt;Here’s the implementation of Interpolation Search in JavaScript.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;const interpolationSearch = (array, key) =&amp;gt; {
  // if array is empty.
  if (!array.length) {
    return -1;
  }

  let low = 0;
  let high = array.length - 1;
  while (low &amp;lt;= high &amp;amp;&amp;amp; key &amp;gt;= array[low] &amp;amp;&amp;amp; x &amp;lt;= array[high]) {
    // calculate position with
    let pos =
      low +
      Math.floor(
        ((high - low) * (key - array[low])) / (array[high] - array[low])
      );

    // if all elements are same then we&apos;ll have divide by 0 or 0/0
    // which may cause NaN
    pos = Number.isNaN(pos) ? low : pos;

    if (array[pos] === key) {
      return pos;
    }

    if (array[pos] &amp;gt; key) {
      high = pos - 1;
    } else {
      low = pos + 1;
    }
  }

  // not found.
  return -1;
};
&lt;/code&gt;&lt;/pre&gt;
</content:encoded><category>Data Structures</category><category>Algorithms</category><category>JavaScript</category></item><item><title>Binging Binary Search 🔎</title><link>https://smellycode.com/binging-binary-search/</link><guid isPermaLink="false">https://smellycode.com/binging-binary-search/</guid><description>An overview of Binary Search.</description><pubDate>Tue, 09 Jan 2018 18:30:00 GMT</pubDate><content:encoded>&lt;p&gt;Data Structures and Algorithms(DSA) is one of the essential tools which every engineer should have in his/her arsenal. Generally, they are taught in the first year of engineering but, in my first year, I was busy in &lt;a href=&quot;http://www.seminarski-diplomski.co.rs/EN-Marketing/Multilevel-marketing.html&quot;&gt;making “binary trees”&lt;/a&gt; 🙂. Because of that, I couldn’t focus on learning and started blindly toying with them. But for 2018, I’ve made a resolution that I will tame this demon of DSA and will not let it haunt me every time I try to step out of my comfort zone. So I’ve started studying DSA and it looks like it’s a long journey but as we know:&lt;/p&gt;
&lt;blockquote&gt;
&lt;p&gt;“The journey of a thousand miles begins with a single step”.&lt;/p&gt;
&lt;/blockquote&gt;
&lt;p&gt;For me that single step is Binary Search, so let’s get started with it.&lt;/p&gt;
&lt;h3&gt;Searching&lt;/h3&gt;
&lt;p&gt;Searching/finding is the most elementary task that we do on daily basis e.g. searching a name in the phone book, searching a book on the bookshelf. The way we search an item majorly depends on how items are kept/arranged. For example, on a bookshelf, if books are kept haphazardly then one may have to check every book till he/she finds the desired book. But in case of the phone book, one can directly jump to the initials of the name.&lt;/p&gt;
&lt;figure class=&quot;text-center&quot;&gt;
&lt;p&gt;&lt;img src=&quot;https://smellycode.com/_astro/searching.Cj3mmJgC.gif&quot; alt=&quot;Searching Image&quot; /&gt;
&lt;/p&gt;&lt;figcaption&gt;
&lt;a href=&quot;https://giphy.com/gifs/animation-books-stop-motion-zmlCPKMlXwq6k&quot; target=&quot;_blank&quot;&gt;
Giphy
&lt;/a&gt;&lt;p&gt;&lt;/p&gt;
  &lt;/figcaption&gt;
&lt;/figure&gt;
&lt;p&gt;In computer science, we are a handful of search algorithms. Some popular elementary search algorithms are Linear/Sequential Search, Binary Search, Interpolation Search, Ternary Search etc. Every search algorithm has it’s own pros and cons. In this post we’ll discuss a bit about Linear Search and then we’ll dive into Binary Search.&lt;/p&gt;
&lt;h3&gt;Linear/Sequential Search&lt;/h3&gt;
&lt;p&gt;In Linear Search as the name suggests we linearly/sequentially compare each item of the collection to the key item. We stop searching when we find the item else we continue searching until all the items are compared. Let’s take an example to understand it. Suppose we have been given a list of employee numbers in ascending order present on a particular day. We need to check whether employee 5 was present or not. We can leverage Linear Search to figure it out. We compare every id/number in the list with 5. If it’s found then we say that employee 5 was present else we’ll say employee 5 was absent. Here’s the implementation in javascript:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;/**
 * Linear Search.
 * @param array
 * @param element
 */
const linearSearch = (array, element) =&amp;gt; {
  // Traverse elements of the array and compare
  // them
  for (let i = 0; i &amp;lt; array.length; i++) {
    // Compare element at ith position with
    // key element. If both are equal then return
    // the index.
    if (array[i] === element) {
      return i;
    }
  }
  // no element found. Returns -1.
  return -1;
};

const employees = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
const employeeId = 5;
const flagPresent = linearSearch(employees, employeeId) !== -1;

if (flagPresent) {
  console.log(`Employee ${employeeId} was present.`);
} else {
  console.log(`Employee ${employeeId} was absent.`);
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;By looking at the number of comparisons we make to find the element using Linear Search, we can say that it’s time complexity is O(n) (You can read more about time complexity in my previous post &lt;a href=&quot;https://hiteshkumar.dev/asymptotic-notations/&quot;&gt;An Ode to Asymptotic Notation&lt;/a&gt;) which means time taken by Linear Search is directly proportional to the size of the input.&lt;/p&gt;
&lt;p&gt;We can conclude that Linear Search is good especially when input size is small but it’s sluggish when the input is relatively large. Also, it doesn’t take advantage of the fact that input i.e. employees list is sorted in ascending order. Let’s see if we can do better with Binary Search.&lt;/p&gt;
&lt;h3&gt;Binary Search&lt;/h3&gt;
&lt;p&gt;Binary Search is based on &lt;a href=&quot;https://en.wikipedia.org/wiki/Divide_and_conquer_algorithm&quot;&gt;Divide and Conquer Technique&lt;/a&gt;. According to &lt;a href=&quot;https://en.wikipedia.org/wiki/Introduction_to_Algorithms&quot;&gt;CLRS&lt;/a&gt;, Divide and Conquer technique is comprised of followings:&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Divide&lt;/strong&gt;: Break or divide the problem into the number of subproblems which are smaller instances of the same problem.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Conquer&lt;/strong&gt;: Continue breaking the subproblems into smaller subproblems. If the subproblem size is small enough then solve it in a straightforward manner.
Combine: the solutions of the subproblems into the solution for the original subproblems.&lt;/p&gt;
&lt;p&gt;Binary Search repeatedly divides the problem into two subproblems that may contain the item. It discards one of the subproblems by utilising the fact that items are sorted. It continues halving the subproblems until it finds the item or it narrows down the list to a single item. Since binary search discards the subproblems because of that it’s pseudo Divide &amp;amp; Conquer algorithm. Here’s the pseudocode for binary search:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;1. LET A is the list of items of size N and k is the key item.
2. LET min = 1 and max = N.
3. Repeat step 4, 5, 6 TILL min &amp;lt;= max.
4. LET mid = (min + max) / 2.
5. IF A[mid] ===  k THEN RETURN &apos;Item Found.&apos;
6. IF A[mid] &amp;lt; key THEN SET min = mid + 1 ELSE SET max = mid - 1.
7. RETURN &apos;Item not found&apos;.
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Here’s the JavaScript implementation for the same:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;/**
 * Iterative Binary Search Implementation
 * @param array: array of items.
 * @param key: key to be searched.
 *
 */
const binarySearch = (array, key) =&amp;gt; {
  // Min and max for our beloved array.
  let min = 0;
  let max = array.length - 1;

  while (min &amp;lt;= max) {
    // Calculating mid for guessing and dividing the problem.
    const mid = Math.floor((min + max) / 2);

    if (array[mid] === key) {
      // Yeah! key is present in the array. Let&apos;s return it&apos;s
      // position.
      return mid;
    }

    // Shifting mix and max respectively to focus
    // on subarray which may contian key.
    if (array[mid] &amp;lt; key) {
      min = mid + 1;
    } else {
      max = mid - 1;
    }
  }

  // We have reached here. It means key is not present in array.
  // Let&apos;s return -1 as an indicator for &quot;Not found&quot;.
  return -1;
};
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;The beauty of binary search is that in every iteration if it doesn’t find the key item, then it simply reduces the list to at least it’s half for the next iteration which makes a huge difference when we talk about its time complexity. Let’s consider worst-case scenario for an array of size 32. In the first iteration, we do not find the key element so we cut down the array length to 16. In next iteration, again we do not find the key element so again we cut it down to 8, then to 4, then to 2, and then to 1. Here’s the visual representation of Binary Search and Linear Search:&lt;/p&gt;
&lt;figure class=&quot;text-center invert-on-dark&quot;&gt;
&lt;p&gt;&lt;img src=&quot;https://smellycode.com/_astro/binary-search.CpP0L4M7.gif&quot; alt=&quot;&quot; /&gt;
&lt;/p&gt;&lt;figcaption&gt;
Visualising Binary Search &amp;amp; Linear Search &lt;a href=&quot;http://hstaylor.weebly.com/blog/binary-searches-simple-python-exercises&quot; target=&quot;_blank&quot;&gt;Source&lt;/a&gt;
&lt;/figcaption&gt;&lt;p&gt;&lt;/p&gt;
&lt;/figure&gt;
&lt;h3&gt;Complexity&lt;/h3&gt;
&lt;p&gt;The best case of binary search is when the first comparison/guess is correct(the &lt;code&gt;key&lt;/code&gt; item is equal to the &lt;code&gt;mid&lt;/code&gt; of array). It means, regardless of the size of the list/array, we’ll always get the result in constant time. So &lt;strong&gt;the best case complexity is O(1)&lt;/strong&gt;.&lt;/p&gt;
&lt;p&gt;In worst case scenario, the binary search finds the item at the end of the list/array when it’s narrowed down to a single item. As we saw earlier with the list of size 32, to narrow it down to a single item we make at least 5 comparisons.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;32/2 --&amp;gt; 16 // 1
16/2 --&amp;gt; 8 // 2
8/2 --&amp;gt; 4 // 3
4/2 --&amp;gt; 2 // 4
2/2 --&amp;gt; 1 // 5
Total = 5 guesses/comparisons.
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;If we double the size to 64 then only one more comparison is extra made.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;64/2 --&amp;gt; 32 // 1
32/2 --&amp;gt; 16 // 2
16/2 --&amp;gt; 8 // 3
8/2 --&amp;gt; 4 // 4
4/2 --&amp;gt; 2 // 5
2/2 --&amp;gt; 1 // 6
Total = 6 guesses/comparisons.
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;If we look at the comparison and size of the input we see a pattern here eg. 32 = 2⁵ and 64 = 2⁶. Let’s assume &lt;code&gt;n&lt;/code&gt; is the size of input and &lt;code&gt;k&lt;/code&gt; is the number of comparisons then we can say that&lt;/p&gt;
&lt;figure class=&quot;invert-on-dark&quot;&gt;
&lt;p&gt;&lt;img src=&quot;https://smellycode.com/_astro/complexity_1.DGXLEcPq.png&quot; alt=&quot;&quot; /&gt;&lt;/p&gt;
&lt;/figure&gt;
&lt;p&gt;Let’s apply logarithm to both sides with base 2(you can read more about &lt;a href=&quot;https://www.khanacademy.org/math/algebra2/exponential-and-logarithmic-functions&quot;&gt;logarithms here&lt;/a&gt;).&lt;/p&gt;
&lt;figure class=&quot;invert-on-dark&quot;&gt;
&lt;p&gt;&lt;img src=&quot;https://smellycode.com/_astro/complexity_2.V2FQfe1U.png&quot; alt=&quot;&quot; /&gt;&lt;/p&gt;
&lt;/figure&gt;
&lt;p&gt;By the help of the equation above we can make a blanket statement that &lt;strong&gt;the worst case complexity of binary search is O(log n)&lt;/strong&gt;.&lt;/p&gt;
&lt;h3&gt;Limitations&lt;/h3&gt;
&lt;ol&gt;
&lt;li&gt;Binary search can be applied iff items are sorted otherwise one must sort items before applying it. And we know that sorting is relatively an expensive operation.&lt;/li&gt;
&lt;li&gt;Binary search can only be applied to data structures which allow direct access to elements. If we do not have direct access then we can not apply binary search on it eg. we can not apply binary search to Linked List.&lt;/li&gt;
&lt;/ol&gt;
&lt;h3&gt;Conclusion&lt;/h3&gt;
&lt;p&gt;Binary search is a powerful tool to find an element in a large collection especially when the collection is sorted and allows direct access to its element. We learned that for best-case binary search runs with constant time i.e. O(1) while for average and worst-case its runtime is O(log n).&lt;/p&gt;
</content:encoded><category>JavaScript</category><category>Data Structures</category><category>Algorithms</category></item><item><title>An Ode to Asymptotic Notations</title><link>https://smellycode.com/asymptotic-notations/</link><guid isPermaLink="false">https://smellycode.com/asymptotic-notations/</guid><description>Aymptotic notations are fancy ways/classes of speaking about algorithms. I&apos;ll do my best to explain them in simple words.</description><pubDate>Sat, 26 Aug 2017 18:30:00 GMT</pubDate><content:encoded>&lt;p&gt;On the La La Land of algorithms, there are ample ways to depict the efficiency
and scalability of an algorithm especially when the input size is large.
Altogether, these ways are called as Asymptotic
Notations(&lt;a href=&quot;https://en.wikipedia.org/wiki/Asymptotic_analysis&quot;&gt;Asymptotic Analysis&lt;/a&gt;).
In this post, we’ll acquaint ourselves with these notations and we’ll see how
we can leverage them to analyse an algorithm.&lt;/p&gt;
&lt;blockquote&gt;
&lt;p&gt;Note: I am writing this post in order to learn cause I strongly believe
in &lt;a href=&quot;https://english.stackexchange.com/a/285220/212452&quot;&gt;learning by teaching&lt;/a&gt;.
In case, you have suggestion/correction, please feel free to post in comment section.&lt;/p&gt;
&lt;/blockquote&gt;
&lt;p&gt;Before we delve into the analysis of an algorithm, we need to know what’s an
algorithm and why studying/analysing algorithms is important. So let’s get started.&lt;/p&gt;
&lt;h3&gt;What is an algorithm?&lt;/h3&gt;
&lt;p&gt;According to &lt;a href=&quot;https://www.merriam-webster.com/dictionary/algorithm&quot;&gt;Merraim Webster&lt;/a&gt;,&lt;/p&gt;
&lt;blockquote&gt;
&lt;p&gt;&lt;strong&gt;A&lt;/strong&gt;n algorithm is a procedure for solving a mathematical problem (as of
finding the greatest
&lt;a href=&quot;https://www.merriam-webster.com/dictionary/common%20divisor&quot;&gt;common divisor&lt;/a&gt;)
in a finite number of steps that frequently involves repetition of an operation;
broadly : a step-by-step procedure for solving a problem or accomplishing some
end especially by a computer.&lt;/p&gt;
&lt;/blockquote&gt;
&lt;p&gt;In other words &lt;strong&gt;an algorithm is simply a finite set of well-defined instructions,
written to solve a specific problem&lt;/strong&gt;
(&lt;a href=&quot;https://www.youtube.com/watch?v=6hfOvs8pY1k&quot;&gt;Ted-Ed: What’s an algorithm?&lt;/a&gt;).
e.g. We want to find an element in an array. One way to find it, we traverse
each element in the array and compare with the key element. If it’s equal then
we say that element is present in the array else we continue traversing till the
end of the array (Linear Search).&lt;/p&gt;
&lt;figure class=&quot;text-center invert-on-dark&quot;&gt;
&lt;p&gt;&lt;img src=&quot;https://smellycode.com/_astro/linear-search.BSIC1bYh.gif&quot; alt=&quot;Linear Search Illustration&quot; /&gt;&lt;/p&gt;
  &lt;figcaption&gt;
    Source: &lt;a href=&quot;https://www.tutorialspoint.com/data_structures_algorithms/linear_search_algorithm.htm&quot; target=&quot;_blank&quot;&gt;TutorialsPoint&lt;/a&gt;
  &lt;/figcaption&gt;
&lt;/figure&gt;
&lt;p&gt;Generally, algorithms are written in the pseudo code. Pseudo code is simply the
text written in an informal language which explains the algorithm and can be
translated in any programming language. Think of pseudo code as a text-based
algorithmic design tool. Let’s write pseudo code for the example above.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;Algorithm:
Find Element(array, key)
a) Set i = 1;
b) if i is greater than array_size then go to step g.
c) if array[i] is equal to key then go to step f.
d) set i = i + 1;(increase i by 1).
e) go to step b.
f) print &apos;Present&apos; and go to step h.
g) print &apos;Not present&apos;.
h) Exit.
Pseudo Code:
findElement(array, key)
    for each item in array
        if item == key
            return &apos;Present&apos;.
    return &apos;Not present&apos;.
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Here’s another algorithm which might be helpful for you if you are living alone.&lt;/p&gt;
&lt;figure class=&quot;text-center invert-on-dark&quot;&gt;
&lt;p&gt;&lt;img src=&quot;https://smellycode.com/_astro/living-alone.Dw7T4AaS.jpg&quot; alt=&quot;Living Alone Algorithm&quot; /&gt;&lt;/p&gt;
  &lt;figcaption&gt;
    &lt;a href=&quot;http://powerofpower.net/comics/82&quot; target=&quot;_blank&quot;&gt;Living Alone Algorithm&lt;/a&gt;
  &lt;/figcaption&gt;
&lt;/figure&gt;
&lt;p&gt;According to Cormen’s &lt;a href=&quot;https://en.wikipedia.org/wiki/Introduction_to_Algorithms&quot;&gt;Introduction to Algorithm&lt;/a&gt;,&lt;/p&gt;
&lt;blockquote&gt;
&lt;p&gt;An algorithm is said to be correct if, for every input instance, it halts
with the correct output.&lt;/p&gt;
&lt;/blockquote&gt;
&lt;p&gt;We supply various instances of input (including edge cases) to an algorithm to
measure its correctness. For example, how linear search algorithm will behave
if we pass an empty array as input.&lt;/p&gt;
&lt;blockquote&gt;
&lt;p&gt;Algorithms are unambiguous in nature.&lt;/p&gt;
&lt;/blockquote&gt;
&lt;p&gt;It means that for an algorithm, each of its steps &amp;amp; inputs/outputs must be
clear and lead to only one meaning.&lt;/p&gt;
&lt;h3&gt;Why Studying Algorithms?&lt;/h3&gt;
&lt;p&gt;As engineers, we always strive to provide better solutions. We know that often
there are many ways to solve a problem and each way has its own strengths and
weaknesses. Studying solutions/algorithms helps us to decide which solution to
pick. For example to find an element in an array, instead of Linear Search we
can use Binary Search if we know that our input array is sorted. While studying
an algorithm we consider following questions:&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;Does it solve the problem with all possible inputs?&lt;/li&gt;
&lt;li&gt;Does it use resources efficiently?&lt;/li&gt;
&lt;li&gt;Can it be optimised?&lt;/li&gt;
&lt;li&gt;Is it scalable?&lt;/li&gt;
&lt;li&gt;Is there any better algorithm?&lt;/li&gt;
&lt;li&gt;and the list goes on…&lt;/li&gt;
&lt;/ol&gt;
&lt;hr /&gt;
&lt;p&gt;Execution of an algorithm requires many resources like computational time,
memory, communication bandwidth, computer hardware etc. When we analyse an
algorithm, we primarily focus on computational/running time and memory/space
required for the algorithm (aka Time Complexity &amp;amp; Space Complexity). Let’s
determine the time complexity of our Linear Search algorithm. Here’s a simple
JavaScript program for LinearSearch.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;/**
 * Linear Search.
 * @param array
 * @param element
 */
const linearSearch = (array, element) =&amp;gt; {
  // Traverse elements of the array and compare
  // them
  for (let i = 0; i &amp;lt; array.length; i++) {
    // Compare element at ith position with
    // key element. If both are equal then return
    // the index.
    if (array[i] === element) {
      return i;
    }
  }
  // no element found. Returns -1.
  return -1;
};
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;You can see that our &lt;code&gt;linearSearch&lt;/code&gt; function takes two parameters: &lt;code&gt;array&lt;/code&gt; and
&lt;code&gt;element&lt;/code&gt; we wish to find. It simply traverses the &lt;code&gt;array&lt;/code&gt; using &lt;code&gt;for&lt;/code&gt; loop and
compares every item of the array with &lt;code&gt;element&lt;/code&gt; parameter. Let’s assume comparison
statement takes time &lt;code&gt;a&lt;/code&gt; unit of computer time and the size of array is &lt;code&gt;n&lt;/code&gt; then&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;Best Case&lt;/strong&gt;: First entry in the array is equal to &lt;code&gt;element&lt;/code&gt;. Only one
iteration, so &lt;code&gt;time = a;&lt;/code&gt; (minimum time required to find the element).&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;Worst Case:&lt;/strong&gt; Last entry in the array is equal to &lt;code&gt;element&lt;/code&gt; Or Element not
present in the array. &lt;code&gt;n&lt;/code&gt; iterations, so &lt;code&gt;time = a \* n;&lt;/code&gt; (maximum time
required to find the element).&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;Average Case:&lt;/strong&gt; Any entry between first and last matches to element.
so required time will be between min and max time (&lt;code&gt;a ≤ time ≤ a \* n&lt;/code&gt;).&lt;/p&gt;
&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;By looking at above scenarios, we can conclude that the running time of an
algorithm depends on the size of the input and the time taken by the computer to
run the lines of code of the algorithm. In other words, we can think of running
time as &lt;em&gt;&lt;strong&gt;a function of the size&lt;/strong&gt;&lt;/em&gt; of its input. eg. For Linear Search, it is
F(n) = an.&lt;/p&gt;
&lt;p&gt;Another important thing which we consider for analysis is &lt;em&gt;&lt;strong&gt;the rate of growth of
the function&lt;/strong&gt;&lt;/em&gt;. The rate of growth(aka Order of Growth) describes how the running
time increases when the size of input increases. Here’s the plot of running time
for Linear Search with respect to input size.&lt;/p&gt;
&lt;figure class=&quot;text-center invert-on-dark&quot;&gt;
&lt;p&gt;&lt;img src=&quot;https://smellycode.com/_astro/linear-search-graph.BBtzEaBw.png&quot; alt=&quot;Linear Search Graph&quot; /&gt;&lt;/p&gt;
  &lt;figcaption&gt;
    &lt;a href=&quot;http://mathcs.pugetsound.edu/~tmullen/hw/s16ics/lab14/&quot; target=&quot;_blank&quot;&gt;
      Linear Search Graph(Math CS)
    &lt;/a&gt;
  &lt;/figcaption&gt;
&lt;/figure&gt;
&lt;p&gt;When we talk about the rate of growth, we mainly focus on the part of our
function which has high impedance and causes drastic changes in the running
time of algorithm especially when the input size is very large.&lt;/p&gt;
&lt;p&gt;Consider a quadratic function &lt;code&gt;F(n) = an² + bn + c&lt;/code&gt;. For very large value of &lt;code&gt;n&lt;/code&gt;,
term &lt;code&gt;(bn + c)&lt;/code&gt; becomes less significant and the addition of it to &lt;code&gt;an²&lt;/code&gt; barely
make any difference. It’s like throwing a bucket filled with water in the ocean
or on Big Show 😀. So we can knock it off. Now we are left with &lt;code&gt;an²&lt;/code&gt;.&lt;/p&gt;
&lt;figure class=&quot;text-center&quot;&gt;
&lt;p&gt;&lt;img src=&quot;https://smellycode.com/_astro/big-show-water-bucket.Dw7pFH0Y.gif&quot; alt=&quot;Big show water bucket&quot; /&gt;&lt;/p&gt;
&lt;/figure&gt;
&lt;p&gt;As we know that &lt;code&gt;a&lt;/code&gt; is constant coefficient and we want our entire focus to be
on the size of input so we can knock off &lt;code&gt;a&lt;/code&gt; as well. Consequently, we are left
with &lt;code&gt;n²&lt;/code&gt; and that’s what indeed matter for us. It tells us that running time
of our function grows as &lt;code&gt;n²&lt;/code&gt; which means that it’s growth rate is quadratic.
Similarly, we can say that growth rate for Linear Search is linear (n).&lt;/p&gt;
&lt;p&gt;&lt;em&gt;When we remove the less significant terms and coefficients, we get the rate of
growth of our function but we need more formal/generic way of describing them,
that’s when we use asymptotic notations&lt;/em&gt;.&lt;/p&gt;
&lt;blockquote&gt;
&lt;p&gt;Think of asymptotic notations, as a formal way to speak about functions and
classifying them.&lt;/p&gt;
&lt;/blockquote&gt;
&lt;p&gt;Asymptotic notations has following classes or notations for describing functions:&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;O-Notation (Big Oh).&lt;/li&gt;
&lt;li&gt;𝛺-Notation (Big Omega).&lt;/li&gt;
&lt;li&gt;ϴ-Notation (Theta).&lt;/li&gt;
&lt;li&gt;o-Notation (Little Oh).&lt;/li&gt;
&lt;li&gt;𝜔-Notation (Little Omega).&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;In this post, we will discuss top 3 notations i.e. O, 𝛺 and ϴ. If you wish to
read about other two notations, you can read them in
&lt;a href=&quot;https://en.wikipedia.org/wiki/Introduction_to_Algorithms&quot;&gt;CLRS&lt;/a&gt;.
So let’s disucss them one by one.&lt;/p&gt;
&lt;h4&gt;O-Notation:&lt;/h4&gt;
&lt;p&gt;In &lt;a href=&quot;https://stackoverflow.com/questions/487258/what-is-a-plain-english-explanation-of-big-o-notation?rq=1&quot;&gt;plain English&lt;/a&gt;,
Big oh notation is a way of estimating upper bound/limit of a function when the
input is very large. Let’s write it in mathematical form.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;O(g(n)) = {
    f(n): there exist positive constants c and k such that
    0 ≤ f(n) ≤ cg(n) for all n ≥ k
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Don’t worry if you are not able to understand it. I am with you and “May the
force be with us”. Let me break it down for you. At first, we have chosen an
arbitrary constant called k as a benchmark for large input means our input is
considered large only when n ≥ k. After that, we are defining the upper bound
for our function f(n) with the help of function g(n) and constant c. It means
that our function f(n)’s value will always be less than or equal to c * g(n)
where g(n) can be any non-negative function for all sufficiently large n. For
example, for Linear Search g(n) = n. So Time Complexity of Linear Search, for
both worst case and average case, is O(n) i.e. Order of n. Time Complexity of
Linear Search for best case is O(1) i.e. constant time (key element is the first
item of the array).&lt;/p&gt;
&lt;figure class=&quot;text-center invert-on-dark&quot;&gt;
&lt;p&gt;&lt;img src=&quot;https://smellycode.com/_astro/big-o.BC7bH0qM.png&quot; alt=&quot;Big O Notation&quot; /&gt;&lt;/p&gt;
  &lt;figcaption&gt;
    Source: GeeksforGeeks
  &lt;/figcaption&gt;
&lt;/figure&gt;
&lt;p&gt;Big Oh notation is the most widely used notation for time complexity cause it
talks about the upper bound of an algorithm which helps us to decide which
algorithm is better. eg. algorithm of complexity O(n) will do better than
algorithm of complexity O(n²) for sufficiently large input(it may not be true
when input is small).&lt;/p&gt;
&lt;h4&gt;𝛺-Notation:&lt;/h4&gt;
&lt;p&gt;Omega notation is converse of Big Oh notation. It is a way of estimating lower
bound/limit of a function when the input is significantly large.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;Ω (g(n)) = {
    f(n): there exist positive constants c and k such that
    0 ≤ cg(n) ≤ f(n) for all n ≥ k
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;As we can see, the value of function is always greater than or equal to lower
bound i.e. c * g(n).&lt;/p&gt;
&lt;figure class=&quot;text-center invert-on-dark&quot;&gt;
&lt;p&gt;&lt;img src=&quot;https://smellycode.com/_astro/omega.Csmk7ebe.png&quot; alt=&quot;Big 𝛺 Notation&quot; /&gt;&lt;/p&gt;
  &lt;figcaption&gt;
    Source: GeeksforGeeks
  &lt;/figcaption&gt;
&lt;/figure&gt;
&lt;p&gt;Omega notation is mainly useful when we are interested in the least amount of
time required for the function/algorithm which make it the least used notation
among other notations.&lt;/p&gt;
&lt;h4&gt;ϴ-Notation:&lt;/h4&gt;
&lt;p&gt;Theta notation is asymptotically tight bound, it means our function lies between
upper bound and lower bound.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;Θ(g(n)) = {
    f(n): there exist positive constants a, band k such that
    0 ≤ b * g(n) ≤ f(n) ≤ a * g(n) for all n ≥ k
}
&lt;/code&gt;&lt;/pre&gt;
&lt;figure class=&quot;text-center invert-on-dark&quot;&gt;
&lt;p&gt;&lt;img src=&quot;https://smellycode.com/_astro/theta.rZ7DN8GL.png&quot; alt=&quot;Big ϴ Notation&quot; /&gt;&lt;/p&gt;
  &lt;figcaption&gt;
    Source: GeeksforGeeks
  &lt;/figcaption&gt;
&lt;/figure&gt;
&lt;p&gt;As we can see, if f(n) is theta of g(n) then f(n) always lies between b * g(n)
and a * g(n) for all values of n which are greater than or equal to k. eg. we
know that upper bound for Insertion Sort is order of n² (when array is sorted
in reverse order, worst case) and lower bound is order of n (when array is
already sorted, best case). So in ϴ notation we describe the time complexity
for insertion sort using following statements:&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;Worst case time complexity of insertion sort is ϴ(n²).&lt;/li&gt;
&lt;li&gt;Best case time complexity of insertion sort is ϴ(n).&lt;/li&gt;
&lt;li&gt;Average case time complexity of insertion sort is ϴ(n²).&lt;/li&gt;
&lt;/ol&gt;
&lt;h3&gt;Which notation to use?&lt;/h3&gt;
&lt;p&gt;Often people ask which notation shall we use to describe the complexity of an
algorithm? Well, it depends on the situation and the desired statement. Let’s
take an example of Insertion Sort. We know that for Insertion Sort the worst
case time complexity is ϴ(n²) and best case time complexity is ϴ(n). Can we say
that the time complexity of insertion sort is ϴ(n²)? No. We can’t cause we know
that for the best case it is ϴ(n). Similarly, we can not say that it’s ϴ(n)
cause for the worst case it is ϴ(n²). An astute reader might ask, is there any
way to make a single/blanket statement which covers both cases and tells us
about the complexity instead of talking about the best case and the worst case?
Yes. There is. What if in lieu of ϴ notation, we use Big O notation, then we
can say that the time complexity of insertion sort is Order of n² i.e. O(n²)
then we don’t need to worry about linear time i.e. O(n) cause upper bound n²
covers it. A details discussion about which notation to use can be found on this
&lt;a href=&quot;https://cs.stackexchange.com/questions/57/how-does-one-know-which-notation-of-time-complexity-analysis-to-use&quot;&gt;StackExchange thread&lt;/a&gt;.&lt;/p&gt;
&lt;h3&gt;Summary&lt;/h3&gt;
&lt;p&gt;To summarise, we can say that asymptotic notations are fancy ways/classes of
speaking about algorithms. They help us to compare one algorithm with another.
They also help us to reason about our algorithms with various cases like best
case, worst case, and average case.&lt;/p&gt;
&lt;h3&gt;References:&lt;/h3&gt;
&lt;ol&gt;
&lt;li&gt;Introduction to Algorithm by &lt;a href=&quot;https://en.wikipedia.org/wiki/Introduction_to_Algorithms&quot;&gt;CLRS&lt;/a&gt;.&lt;/li&gt;
&lt;li&gt;Asymptotic Notations by &lt;a href=&quot;http://www.geeksforgeeks.org/fundamentals-of-algorithms/#AnalysisofAlgorithms&quot;&gt;GeeksForGeeks&lt;/a&gt;.&lt;/li&gt;
&lt;li&gt;&lt;a href=&quot;https://www.khanacademy.org/computing/computer-science/algorithms/asymptotic-notation/a/asymptotic-notation&quot;&gt;Khan Acadamy&lt;/a&gt;.&lt;/li&gt;
&lt;li&gt;and of course Stackoverflow.&lt;/li&gt;
&lt;/ol&gt;
</content:encoded><category>Algorithms</category><category>Asymptotic Notations</category></item><item><title>Salient Notes from “The Monk Who Sold His FERRARI”</title><link>https://smellycode.com/the-monk-who-sold-his-ferrari/</link><guid isPermaLink="false">https://smellycode.com/the-monk-who-sold-his-ferrari/</guid><description>Keynotes I captured while reading the book.</description><pubDate>Sat, 05 Aug 2017 18:30:00 GMT</pubDate><content:encoded>&lt;p&gt;Books are the ultimate source of inspiration. They change the way we look at our beautiful world. They help us to live and lead a life filled with joy and prosperity. I am glad that I have cultivated the habit of reading books. This week I completed &lt;a href=&quot;http://www.robinsharma.com/store/books/HardcoverandPaperback/the-monk-who-sold-his-ferrari&quot;&gt;Robin Sharma’s The Monk Who Sold His FERRARI&lt;/a&gt;. Whenever I read a book, I jot down my thoughts and quotable quotes which I come across. This post is a collection of all the salient thoughts and quotes which I noted down when I was reading The Monk Who Sold His Ferrari. Hope you’ll enjoy reading them.&lt;/p&gt;
&lt;p&gt;&lt;img src=&quot;https://smellycode.com/_astro/the-monk-who-sold-his-ferrari-cover-img.CsdASN-4.jpeg&quot; alt=&quot;Cover Image&quot; /&gt;&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;
&lt;p&gt;Life becomes so much simpler and meaningful when you leave the baggage of past behind.&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;Everything happens for a reason. Every event has a purpose and every setback its lesson. Failure, whether of personal, professional or even spiritual kind, is essential to personal expansion. It brings inner growth and a whole host of psychic rewards. Never regret your past. Rather, embrace it as the teacher that it is.&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;Life is all about the choices. One’s destiny unfolds according to the choices one makes.&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;Success on the outside means nothing unless you have success within.&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;When the student is ready, the teacher appears.&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;There are no free lunches.&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;Never overlook the power of simplicity.&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;If you care for your mind, if you nurture it and if you cultivate it just like a fertile, rich garden, it will blossom far beyond your expectations. But if you let the weeds take root, lasting peace of mind and deep inner harmony will always elude you.&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;The most joyful, dynamic and contented people of this world are no different from you or me in terms of their makeup. We are all flesh and bones. We all come from the same universal source. However, the ones who do more just exists, the one who fan the flames of their human potential and truly savour the magical dance of life do different things than those whose lives are ordinary.&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;Your I can is more important than your I.Q.&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;There are no mistakes in life, only lessons. There is no such thing as a negative experience, only opportunity to grow, learn and advance along the road of self-mastery. From struggle comes strength. Even pain can be a wonderful teacher.&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;The laws of nature always ensure that when one door closes another opens.&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;Things are always created twice: first in the workshop of the mind and then, and only then, in reality.&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;When you are inspired by some great purpose, some extraordinary project, all of your thoughts break their bonds: your mind transcends limitations, your consciousness expands in every direction and you find your self in a new, great and wonderful world. Dormant forces, faculties, and talents become alive and you discover yourself to be a greater person than you ever dreamed yourself to be.&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;The secret of happiness is simple: find out what you truly love to do and then direct all of your energy towards doing it. Once you do this, abundance flows into your life and all your desires are filled with ease and grace.&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;Saying that you don’t have time to improve your thoughts and your life is like saying you don’t have time to stop for gas because your are too busy driving. Eventually it will catch up with you.&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;A rose is very much like life: you will meet thorns along the way but if you have faith and believe in your dreams you will eventually move beyond the thorns into the glory of the flower(Heart of Rose).&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;One must not allow the clock and the calendar to blind him to the fact that each moment of life is a miracle and a mystery.&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;Self-knowledge is the stepping stone to self-mastery.&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;The quality of your thinking determines the quality of your life.&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;Run your own race.&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;Fatigue dominates the lives of those who are living who are living without direction and dreams.&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;The purpose of life is a life of purpose.&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;You will never be able to hit a target that you can not see.&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;The main reason people do not follow through on any resolutions they make is that it is too easy to slip back into their old ways. Pressure is not always a bad thing. Pressure can inspire you to achieve great ends. People generally achieve magnificent things when their back are up against the wall and they are forced to tap into the wellspring of human potential that lies within them.&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;Three mirrors that forms a person’s reflection; the first is how you see yourself, the second is how others see you and the third mirror reflects the truth. Know yourself, know the truth.&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;What lies behind you and what lies in front of you is nothing when compared to what lies within you.&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;Never forget the importance of living with unbridled exhilaration. Never neglect to see the exquisite beauty in all living things. Today, and this very important moment, is a gift. Stay focused on your purpose. The universe will take care of everything else.&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;The degree of courage you live with determines the amount of fulfilment you receive. It allows you to truly realise all the exquisite wonders of the epic that is your life. And those who master themselves have an abundance of courage.&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;You practice the art of kaizen by pushing yourself daily. Work hard to improve your mind and body. Nourish your spirit. Do the things you fear. Start to live with unbridled energy and limitless enthusiasm. Watch the sunrise. Dance in a rain shower. Be the person you dream of being. Do the things you have always wanted to do but you didn’t because you tricked yourself into believing that you were too young, too old, too rich or too poor. Prepare to live a soaring, full alive life. In the East they say luck favours the prepared mind. I believe life favours the prepared mind.&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;Fear is nothing more than a negative stream of consciousness.&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;Try not to live your life bound by the shackles of your schedule.&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;Stop making excuses, just do it.&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;There’s nothing wrong in making mistakes. Mistakes are part of life and essential for growth. It’s like that saying, “Happiness comes through good judgment, good judgment comes through experience, and experience comes through bad experience”. But there’s something very wrong with making same mistakes over and over again, day in and day out. This shows the complete lack of self-awareness, the very quality that separates humans from animals.&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;We don’t laugh because we are happy. We are happy because we laugh.&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;You sow a thought, you reap an action. Reap an action, you sow a habit. Sow a habit, you reap a character. Sow a character, you reap your destiny.&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;The universe favours the brave. When you resolve to lift your life to its highest level, the strength of your soul will guide you to a magical place with magnificent treasures.&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;Through the steel of discipline, you will forge a character rich with courage and peace. Through the virtue of Will, you are destined to rise to life’s highest ideal and live within a heavenly mansion filled with all that is good, joyful and vital. Without them, you are lost like a mariner without a compass, one who eventually sinks with his ship.&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;Truly enlightened people never seek to be like others. Rather, they seek to be superior to their former selves. Don’t race against others. Race against yourself.&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;Words are the verbal embodiment of power. By filling your mind with words of hope, you become hopeful. By filling your mind with words of kindness, you become kind. By filling your mind with thoughts of courage, you become courageous. Words have power.&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;Time mastery leads to life master. Guard time well. Remember it’s not non-renewable resource.&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;Learn to say no. Having the courage to say no to the little things in life will give you the power to say yes to the big things.&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;Push yourself to do more and to experience more. Harness your energy to start expanding your dreams. Yes, expand your dreams. Don’t accept a life of mediocrity when you hold such infinite potential within the fortress of your mind. Dare to tap into your greatness. This is your birthright!&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;When all is said and done, no matter what you have achieved, no matter how many summer homes you own, no matter how many cars sit in your driveway, the quality of your life will come down to the quality of your contribution.&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;A little bit of fragrance always clings to the hand that gives you roses.&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;Friends add humour, fascination and beauty to life. There are few things more rejuvenating than sharing a belly-bursting laugh with an old friend. Friends keep you humble when you get too self-righteous. Friends make you smile when you are taking yourself too seriously. Good friends are there to help you when life throws one of its little curves at you and things look worse than they seem.&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;Past is water under the bridge and the future is a distant sun on the horizon of your imagination. The most important moment is now. Learn to live in it and savour it fully.&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;Don’t kid yourself into believing that you will start to enrich your mind, care for your body and nourish your soul when your bank account gets big enough and you have the luxury of more free time. Today is the day to enjoy the fruits of your efforts. Today is the day to seize the moment and live a life that soars. Today is the day to live from your imagination and harvest your dreams. And please never, ever forget the gift of family.&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;Life doesn’t always gives you what you ask for, but it always gives you what you need.&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;Make the decision to spend more time with those who make your life meaningful. Revere the special moments, revel in their power. Do the things that you have always wanted to do. Climb that mountain you have always wanted to climb or learn to play the trumpet. Dance in the rain or build a new business. Learn to love music, learn a new language and rekindle the delight of your childhood. Stop putting off your happiness for the sake of achievement. Instead, why not enjoy the process? Revive your spirit and start tending to your soul. This is the way to Nirvana.&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;We are all here for some special reason. Stop being a prisoner of your past. Become the architect of your future.&lt;/p&gt;
&lt;/li&gt;
&lt;/ol&gt;
</content:encoded><category>Personal Growth</category></item><item><title>Insertion Sort with Callback.</title><link>https://smellycode.com/insertion-sort-with-callback/</link><guid isPermaLink="false">https://smellycode.com/insertion-sort-with-callback/</guid><description>Implementation of insertion sort using with callback.</description><pubDate>Tue, 16 May 2017 18:30:00 GMT</pubDate><content:encoded>&lt;pre&gt;&lt;code&gt;interface SortCallback {
  (a: any, b: any): boolean;
}
class InsertionSort {
  private sortCb(a, b): boolean {
    return a &amp;gt; b;
  }
  public sort(array, cb: SortCallback = this.sortCb) {
    for (let i = 1; i &amp;lt; array.length; i++) {
      let j = i - 1;
      let key = array[i];
      while (j &amp;gt;= 0 &amp;amp;&amp;amp; cb(array[j], key)) {
        array[j + 1] = array[j];
        array[j] = key;
        j -= 1;
      }
    }
  }
}
let iSort = new InsertionSort();
let array = [5, 2, 4, 6, 1, 3];
console.log(JSON.stringify(array));
iSort.sort(array, (a, b) =&amp;gt; b &amp;gt; a);
console.log(JSON.stringify(array));
&lt;/code&gt;&lt;/pre&gt;
</content:encoded><category>JavaScript</category><category>Data Structures</category><category>Algorithms</category><category>Typescript</category></item><item><title>Angular =&gt; extend, copy &amp; merge</title><link>https://smellycode.com/angular-copy-extend-merge/</link><guid isPermaLink="false">https://smellycode.com/angular-copy-extend-merge/</guid><description>An overview of angular&apos;s copy, merge and extend api.</description><pubDate>Sat, 11 Feb 2017 18:30:00 GMT</pubDate><content:encoded>&lt;p&gt;Superheroic &lt;a href=&quot;https://angularjs.org/&quot;&gt;AngularJs&lt;/a&gt; comes with a set of utility
functions which are not specific to angular and can be leveraged anywhere.
In this post, we will discuss &lt;code&gt;angular.copy()&lt;/code&gt;, &lt;code&gt;angular.extend()&lt;/code&gt; &amp;amp;
&lt;code&gt;angular.merge()&lt;/code&gt;. Before delving into these, we need to walk through two
important concepts &lt;em&gt;Deep Copy&lt;/em&gt; and &lt;em&gt;Shallow Copy&lt;/em&gt; cause these functions linger
around these concepts.&lt;/p&gt;
&lt;p&gt;Shallow Copy is a field by field copy of an object. All the fields of an object
are copied to another object. If a field value is a reference to an object
(e.g., a memory address) it copies the reference and if field value is a primitive
type it copies the value of the primitive type. Since we copy the reference only
so &lt;em&gt;if one object is modified then changes will be visible in other object also&lt;/em&gt;.&lt;/p&gt;
&lt;p&gt;Deep Copy duplicates everything. In lieu of copying the references, it creates a
new copy of object and then copy the refrence of new object to destination object.
Since we create a brand new object and refer it. Thus the changes made in one
objects are not visible to another object. A detailed discussion on deep copy
and shallow copy
&lt;a href=&quot;http://stackoverflow.com/questions/184710/what-is-the-difference-between-a-deep-copy-and-a-shallow-copy&quot;&gt;can be found here&lt;/a&gt;.&lt;/p&gt;
&lt;p&gt;Well now it’s high time for our celebrated functions. Let’s look into them one
by one.&lt;/p&gt;
&lt;p&gt;&lt;code&gt;angular.copy()&lt;/code&gt; does deep copy of an object. In other words, it creates the new
destination object(if not supplied) by duplicating the values from supplied source
object.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;angular.copy(source, [destination]);
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;As you can see the second parameter is optional. So when it is not passed a new
object is created otherwise properties will be copied to destination object.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;var source = {
  a: &apos;a&apos;,
  b: &apos;b&apos;
};
var destination = {
  x: &apos;my ex&apos;,
  y: &apos;your y&apos;
};
var sourceCopy = angular.copy(source);
sourceCopy.a = &apos;Changed a&apos;;
console.log(source.a, sourceCopy.a); //&quot;a&quot;, &quot;Changed a&quot;
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Here are some cases from the official api doc for
&lt;a href=&quot;https://docs.angularjs.org/api/ng/function/angular.copy&quot;&gt;angular.copy()&lt;/a&gt; which
extensively talks about it.&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;If no destination is supplied, a copy of the object or array is created.&lt;/li&gt;
&lt;li&gt;If a destination is provided, all of its elements (for arrays) or properties
(for objects) are deleted and then all elements/properties from the source are
copied to it.&lt;/li&gt;
&lt;li&gt;If source is not an object or array (inc. null and undefined), source is
returned.&lt;/li&gt;
&lt;li&gt;If source is identical to destination an exception will be thrown.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;&lt;code&gt;angular.extend()&lt;/code&gt; as name suggests it extends the destination object by copying
enumerable properties of source object. Let&apos;s see it in action.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;var source = {
  a: &apos;a&apos;
};
var destination = {
  b: &apos;b&apos;
};
angular.extend(destination, source);
console.log(destination); //{a: &apos;a&apos;, b: &apos;b&apos;}
var obj = {
  c: &apos;c&apos;
};
//if you don&apos;t want to mess with original destination obj.
var r = angular({}, obj, source);
console.log(r); //{a: &apos;a&apos;, c:&apos;c&apos;}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;code&gt;angular.extend()&lt;/code&gt; does shallow copy which means if changes are made in
non-primitive property of source object than they will be visible in destination
object or vice versa.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;var source = {
  a: {
    c: &apos;Some value of c&apos;
  }
};
var destination = {
  b: &apos;this is b&apos;
};
angular.extend(destination, source);
console.log(destination); // {a: {c: &apos;Some value of c&apos;}, b: &apos;this is b&apos;}
source.a.c = &apos;modified c&apos;;
console.log(destination.a.c); // &quot;modified c&quot;
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Note: &lt;code&gt;angular.extend()&lt;/code&gt; does not support rescursive merge(deep copy). That&apos;s
where &lt;code&gt;angular.merge()&lt;/code&gt; comes into picture. See the code below.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;var objA = {
  a: {
    b: &apos;b&apos;
  }
};
var objB = {
  a: {
    c: &apos;c&apos;
  }
};
var r = angular.extend({}, objA, objB);
// It will log { a: { c : &quot;c&quot; } } instead of // { a: { b: &quot;b&quot;, c : &quot;c&quot; }}
console.log(r);
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;code&gt;angular.merge()&lt;/code&gt; deeply extends destination object by copying enumerable
properties from the source to destination. Unlike extend(), merge() recursively
descends into object properties of source and perform copy.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;var objA = {
  a: {
    b: &apos;b&apos;
  }
};
var objB = {
  a: {
    c: &apos;c&apos;
  }
};
var r = angular.merge({}, objA, objB);
console.log(r); // { a: { b: &quot;b&quot;, c : &quot;c&quot; }}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;That’s all folks!! Here are the references:
&lt;a href=&quot;https://docs.angularjs.org/api/ng/function/angular.extend&quot;&gt;angular.extend()&lt;/a&gt;,
&lt;a href=&quot;https://docs.angularjs.org/api/ng/function/angular.copy&quot;&gt;angular.copy()&lt;/a&gt; &amp;amp;
&lt;a href=&quot;https://docs.angularjs.org/api/ng/function/angular.merge&quot;&gt;angular.merge()&lt;/a&gt;.&lt;/p&gt;
</content:encoded><category>JavaScript</category><category>AngularJs</category></item></channel></rss>