<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Shirsh Zibbu on Medium]]></title>
        <description><![CDATA[Stories by Shirsh Zibbu on Medium]]></description>
        <link>https://medium.com/@zhirzh?source=rss-11f14fe74017------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*jemws8Ey-bhJUQIV.</url>
            <title>Stories by Shirsh Zibbu on Medium</title>
            <link>https://medium.com/@zhirzh?source=rss-11f14fe74017------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 16 Nov 2026 21:03:05 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@zhirzh/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Classes in JavaScript, then and now]]></title>
            <link>https://medium.com/hackernoon/classes-in-javascript-then-and-now-c60235cede6b?source=rss-11f14fe74017------2</link>
            <guid isPermaLink="false">https://medium.com/p/c60235cede6b</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[typescript]]></category>
            <dc:creator><![CDATA[Shirsh Zibbu]]></dc:creator>
            <pubDate>Sat, 04 Jan 2020 22:20:49 GMT</pubDate>
            <atom:updated>2020-03-10T11:40:12.071Z</atom:updated>
            <content:encoded><![CDATA[<h3>Classes in JavaScript — then and now</h3><h4>And TypeScript too</h4><h3>Constructors and prototypes</h3><p>The earliest versions of JavaScript didn’t have classes. If we wanted to model data as <em>values-and-behaviors</em> like in any other OOP language, we would create <a href="https://javascript.info/constructor-new"><strong>constructor functions</strong></a> for creating the object with the assigned values and add behaviors to the constructor’s <strong>prototype </strong>that would serve as the “blueprint” for the model.</p><pre>function <strong>Human</strong>(name, age) {<br>  this.<strong>name</strong> = name</pre><pre>  if (age) {<br>    this.<strong>age</strong> = age<br>  }<br>}</pre><pre><strong>Human</strong>.prototype.<strong>age</strong> = 0 <em>// default value</em></pre><pre><strong>Human</strong>.prototype.<strong>speak</strong> = function() {<br>  console.log(`Human: ${this.name} | ${this.age}`)<br>}</pre><pre>const me = new Human(&#39;Shirsh Zibbu&#39;)<br>me.speak()<br><em>//&gt; Human: Shirsh Zibbu | 0</em></pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*K2xaiuPF908e645jvoIkoQ.png" /></figure><p>The next we wanted was <a href="https://crockford.com/javascript/inheritance.html"><strong>classical inheritance</strong></a> and it was achieved by simply creating an instance of baseclass and connecting it with the subclass constructor &amp;prototype.</p><pre>function <strong>Person</strong>(name, age, address) {<br>  <em>// call parent constructor<br></em>  <strong>Human</strong>.call(this, name, age)</pre><pre>  this.<strong>address</strong> = address<br>}</pre><pre><em>// enable lookup delegation to `Human.prototype`<br></em><strong>Person</strong>.prototype = new <strong>Human</strong>()</pre><pre><em>// fix `</em>instanceof<em>` operator</em><strong><br>Person</strong>.prototype.constructor = <strong>Person</strong></pre><pre><em>// method override</em><br><strong>Person</strong>.prototype.<strong>speak</strong> = function() {<br><em>  // call parent method</em><br><strong>  Human</strong>.prototype.<strong>speak</strong>.call(this)</pre><pre>  console.log(`Person: ${this.address}`)<br>}</pre><pre><em>// new method</em><br><strong>Person</strong>.prototype.<strong>greet</strong> = function() {<br>  console.log(&#39;hello world&#39;)<br>}</pre><pre>const me = new Person(&#39;Shirsh Zibbu&#39;, 25, &#39;India&#39;)<br>me.speak()<br><em>//&gt; Human: Shirsh Zibbu | 25<br>//&gt; Person: India</em></pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9t7jdYmyy_TER_YInVHLRA.png" /></figure><p>This works perfectly except for a few cases where the baseclass constructors need arguments to create an instance and might not work otherwise.</p><p>This problem was fixed when <a href="https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object/create">Object.create()</a> was introduced. Instead of creating a new instance of the baseclass, we can now create a dummy object that delegates to baseclass-prototype and use it as the prototype for our subclass.</p><pre>...</pre><pre><em>// enable lookup delegation to `Human.prototype`</em><br><strong>Person</strong>.prototype = Object.create(<strong>Human</strong>.prototype)</pre><pre>...</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mWhwT9Pmx9235FzGUfX1kg.png" /></figure><p>There is yet another way to set up the prototype for the subclass by using <a href="https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object/setPrototypeOf">Object.setPrototypeOf()</a> but it is not as popular. We don’t need to create a baseclass instance or even a dummy object to enable lookup delegation.</p><p>We can just set the [[Prototype]] of subclass-protype to baseclass-protype.</p><pre>...</pre><pre><em>// enable lookup delegation to `Human.prototype`</em><br>Object.setProtypeOf(<strong>Person</strong>.prototype, <strong>Human</strong>.prototype)</pre><pre>...</pre><h3>A slight detour from OOP</h3><p>It is not necessary to create constructors and prototypes to model data in a more OOP like fashion. The idea here is to create a single blueprint object that holds default values and all the methods for a “model” and create a simple function that builds new “model instances” (simple objects that delegate to the blueprint).</p><pre>function <strong>Human</strong>(name, age) {<br>  // compatibility with `new` operator usage<br>  if (new.target) {<br>    return <strong>Human</strong>(name, age)<br>  }</pre><pre>  const <strong>extensions</strong> = { name }<br>  if (age) {<br>    <strong>extensions</strong>.age = age<br>  }</pre><pre>  return Object.assign(<br>    Object.create(<strong>__Human__</strong>),<br>    <strong>extensions</strong><br>  )<br>}</pre><pre><em>// blueprint for &quot;Human&quot;</em><br>const <strong>__Human__</strong> = {<br>  age: 0,<br>  speak() {<br>    console.log(`Human: ${this.name} | ${this.age}`)<br>  }<br>}</pre><pre>function <strong>Person</strong>(name, age, address) {<br>  // compatibility with `new` operator usage<br>  if (new.target) {<br>    return <strong>Person</strong>(name, age, address)<br>  }</pre><pre>  return Object.assign(<br>    Object.create(<strong>__Person__</strong>),<br>    new <strong>Human</strong>(name, age),<br>    { address }<br>  )<br>}</pre><pre><em>// blueprint for &quot;Person&quot; class<br></em>const <strong>__Person__</strong> = Object.assign(<br><em>  // enable lookup delegation to `Human.prototype`<br></em>  Object.create(<strong>__Human__</strong>),<br>  {<br>    speak() {<br><strong>      __Human__</strong>.speak.call(this)<br>      console.log(`Person: ${this.address}`)<br>    }<br>  }<br>)</pre><pre>const me = <strong>Person</strong>(&#39;Shirsh Zibbu&#39;, 25, &#39;India&#39;)<br>me.speak()<br><em>//&gt; Human: Shirsh Zibbu | 25<br>//&gt; Person: India</em></pre><p>This style of modeling relies only on native JavaScript constructs — objects, functions, and prototype delegation. Too bad it never caught up.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZfI8O6ASl8xFOCuSAmLYAg.png" /></figure><p>There was some movement towards this unorthodox pattern but it never became popular. Instead, we got the new ES6 class syntax.</p><h3>ES6 class syntax</h3><p>The class syntax is the defacto way to work in OOP languages. It was only a matter of time that JavaScript received the same.</p><pre>class <strong>Human</strong> {<br>  age = 0 <em>// default value but </em><strong><em>NOT</em></strong><em> on prototype</em></pre><pre>  constructor(name, age) {<br>    this.name = name</pre><pre>    if (age) {<br>      this.age = age<br>    }<br>  }</pre><pre><strong>  speak</strong>() {<br>    console.log(`Human: ${this.name} | ${this.age}`)<br>  }<br>}</pre><pre>class <strong>Person</strong> extends <strong>Human</strong> {<br>  constructor(name, age, address) {<br>    <strong>super</strong>(name, age)</pre><pre><em>    // can&#39;t use `this` before calling `super()`<br></em>    <strong>this</strong>.address = address<br>  }</pre><pre><strong>  speak</strong>() {<br>    <em>// call parent method<br></em><strong>    super</strong>.speak()</pre><pre>    console.log(`Person: ${this.address}`)<br>  }</pre><pre><strong>  greet</strong>() {<br>    console.log(&#39;hello world&#39;)<br>  }<br>}</pre><pre>const me = new <strong>Person</strong>(&#39;Shirsh Zibbu&#39;, 25, &#39;India&#39;)<br>me.speak()<br><em>//&gt; Human: Shirsh Zibbu | 25<br>//&gt; Person: India</em></pre><p>It is important to know that all of this is just syntactic sugar on the existing system with a few differences:</p><ul><li>Class properties (like age) are assigned directly on the instance and not on its [[Prototype]]</li><li>CLASS.prototype cannot be re-assigned, re-defined or deleted</li><li>A subclass inherits static members of its baseclass</li></ul><pre>function <strong>Human</strong>(name, age) {<br>  this.age = 0 // default value but NOT on prototype</pre><pre>  this.name = name</pre><pre>  if (age) {<br>    this.age = age<br>  }<br>}</pre><pre><strong>Human</strong>.prototype.<strong>speak</strong> = function() {<br>  console.log(`Human: ${this.name} | ${this.age}`)<br>}</pre><pre><em>// lock prototype<br></em>Object.defineProperty(<strong>Human</strong>, &quot;prototype&quot;, {<br>  value: <strong>Human</strong>.prototype,<br>  writable: false,<br>  enumerable: false,<br>  configurable: false,<br>})</pre><pre>function <strong>Person</strong>(name, age, address) {<br>  Human.call(this, name, age, address)</pre><pre><em>// can&#39;t use `this` before calling `super()`</em><br>  this.address = address<br>}</pre><pre><em>// enable lookup delegation to `Human.prototype`</em><br><strong>Person</strong>.prototype = Object.create(<strong>Human</strong>.prototype)</pre><pre><em>// fix `</em>instanceof<em>` operator</em><strong><br>Person</strong>.prototype.constructor = <strong>Person</strong></pre><pre><em>// method override</em><strong><br>Person</strong>.prototype.<strong>speak</strong> = function() {<br>  // call parent method<br>  <strong>Human</strong>.prototype.<strong>speak</strong>.call(this)</pre><pre>  console.log(`Person: ${this.address}`)<br>}</pre><pre><strong>Person</strong>.prototype.<strong>greet</strong> = function() {<br>  console.log(&#39;hello world&#39;)<br>}</pre><pre>Object.defineProperty(<strong>Person</strong>, &quot;prototype&quot;, {<br>  value: <strong>Person</strong>.prototype,<br>  writable: false,<br>  enumerable: false,<br>  configurable: false,<br>})</pre><pre>Object.setPrototypeOf(<strong>Person</strong>, <strong>Human</strong>) <em>// static inheritance</em></pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bqtlN0JMlMgiK8aY0vomqA.png" /></figure><h3>Static analysis</h3><p>Since TypeScript is a static extension of JavaScript, it doesn’t modify or remove any existing runtime behaviors but adds a few which are <em>compile-time</em> — types, interfaces, generics, abstract classes, and more.</p><p>One major difference in how interfaces work in TypeScript compared to Java is that <strong>interfaces describe the structure of an instance, not a class</strong>. That is why interfaces in TypeScript can’t have static members.</p><blockquote><strong>TypeScript interfaces describe the structure of an </strong>instance<strong>, not a class</strong></blockquote><p>When we create a class in TypeScript, we also get an implicit interface that describes the shape of an instance of that class (and any other object if we use it as a declaration type or as a cast/assertion).</p><pre>interface <strong>Animal</strong> { ... }</pre><pre>class <strong>Human</strong> implements <strong>Animal</strong> { ... }</pre><pre><em>// equivalent to<br></em>class <strong>Human</strong> implements <strong>Human</strong>, <strong>Animal </strong>{ ... }</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AgJqEZzfip1EO8_SUsqHZQ.png" /></figure><h4>Implements extras</h4><p>In cases of inheritance, the <strong>implicit interface</strong> of the subclass will also extend the <strong>combined interface</strong> of the base class.</p><pre>interface <strong>Animal</strong> { ... }</pre><pre>class <strong>Human</strong> implements <strong>Animal</strong> { ... }</pre><pre>class <strong>Person</strong> extends <strong>Human</strong> { ... }</pre><pre><em>// equivalent to<br></em>class <strong>Human</strong> implements <strong>Human</strong>, <strong>Animal </strong>{ ... }</pre><pre>class <strong>Person</strong> extends <strong>Person</strong>, <strong>Human</strong> { ... }</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XKIwfr-kw52aIbBcello2g.png" /></figure><h4>Static types for classes</h4><p>Even though I said that <em>interfaces describe the structure of an object and not a class</em>, we can still enforce static members on a class if we want to. But it won’t be pretty.</p><p>We need to define our Person class using class expressions rather than declaring it. This allows us to use the Developer interface to describe the shape of the class itself. However, class expressions don’t get a “free” implicit interface. And to <em>add insult to injury</em>, we can’t directly instantiate our Person class because the interface describing its shape (i.e., Developer) doesn’t contain a <strong>construct signature</strong>.</p><p>After fixing all these issues, here’s what we get:</p><pre>interface Developer {<br>  new (name: string, age: number, address: string): Person</pre><pre>  langs: string[]<br>}</pre><pre>class <strong>Human</strong> {<br>  name: string</pre><pre>  age = 0</pre><pre>  constructor(name: string, age: number) {<br>    this.name = name</pre><pre>    if (age) {<br>      this.age = age<br>    }<br>  }</pre><pre>  speak() {<br>    console.log(`Human: ${this.name} | ${this.age}`)<br>  }<br>}</pre><pre>interface <strong>Person</strong> extends <strong>Human</strong> {<br>  address: string<br>}</pre><pre>const <strong>Person</strong>: Developer = class extends <strong>Human</strong> implements <strong>Person</strong> {<br>  static langs = [&#39;JavaScript&#39;, &#39;TypeScript&#39;]</pre><pre>  address: string</pre><pre>  constructor(name: string, age: number, address: string) {<br>    super(name, age)</pre><pre>    this.address = address<br>  }</pre><pre>  speak() {<br>    console.log(`Person: ${this.address}`)</pre><pre>    super.speak()<br>  }<br>}</pre><pre>const me = new Person(&#39;Shirsh Zibbu&#39;, 25, &#39;India&#39;)<br>me.speak()<br>me.address<br>//&gt; Person: India<br>//&gt; Human: Shirsh Zibbu | 25</pre><p>You can check everything works on <a href="https://www.typescriptlang.org/play/?ssl=1&amp;ssc=1&amp;pln=2&amp;pc=22#code/JYOwLgpgTgZghgYwgAgCIQG4QDYHsAO0yA3gFDIXIgQDuyAFCHALYQBcyAzmFKAOYAaZHD7sqAV2YAjaELgATeVAidOHbrxB8AlBwAK0TrhABuUuUrY4WtVx78A2gF0zAX3MIrq5AAlJ1kgsKJlZ1ey0zIOFRZABeZAAGSMpkBGMNcQQwXChGFjENfjlRDhBJGShtQJSUsAALYE4AOhCUeNazGspgGAYRCCqyLq76xqb+uOiITuH3FPcozkI4AGt6QaiUtJAjbAgmvD56AAM-ZmsOABJiUebW12QAH2Rr2-HRV2PtGYp3BdBILBECgDFAjCBkBAAB6QEDyTi+fwQoaUBRKFS2QoRUgLbbcZCg8EcdBYPCEKCTTxwbzQ2HwxHnCHAZj4PascAIwnGaqUbhwMDABDIKw2SYOADkACk4Bg4ABlBC8fBgcVCcUAFQAnoQFUqVU5zCk0cpVGFNHxkpQ8TxMtlcq0zUUpqVyrJhIoTZjwjoeV1OOJyXlWMUBj8am9jRjJpHVGGFiklhBVutfTU8bg9gdcEdjlyQFcbg1mjHOJ9vpteQHoE1E8ny-McR50mBkKxJtQ6Hn6OK5Q0wXVkAAtYBSKTiVXIABMAFY1QBJOHAODi7SkVg15ZrVfrkukAD0e4AfATDMYOAv5Ev90eGRdkL3gP2hyOx08p9PSEA">here TypeScript playground</a>.</p><h3>Bonus</h3><p>Here’s a <em>not-so-simple</em> setup for you to admire that uses everything listed in this article and a few more things. The code for this setup is <a href="https://www.typescriptlang.org/play/#code/JYOwLgpgTgZghgYwgAgBrIN7IB4C5lwgCeyAvgFDlhEAOKAmsgLybJECM+hJpyAZKyIAmfOyEBmMpUqhIsRCgAKmcsjXIQEAO4AKAJT4AgqvU1OBYuQrlZ0eEmTKsNERZ4zwdhcgCKAHgAVAD4VdQ1tHQA6aLgoAHMAZy5iA2QAkzUAR2SiK2kbT3kHQ2QIbEgQABMEtFD1OHxNADdoPPIEAHsQBLBkQ3xlFgQAGzgEmuAAWxphiEmIcBqSjAzkHrgwYARkM2ZkMXFV9c3tlz2AcgALCGHhjuQtDqhhyvPKMLw3d-q9gFcqiAwUAQSoEGrNVrWDxyewoABCpXKC2qfQANMhGCswgAjfD-ADWIA6WhAbU63V6cPw-jhISGo3GiIqKJKUxmcwWYBqCKx6mOW2QmT2IF+t2+ag4e3gwwSEFWwgAhKIJOLkLiNL9JtjoHsAAxtSjknoEYXaPr6SiGSJmchWlyUOCRbDkR1wfJG3rY01aZBwi3kOGRTKUbFO8ihjjhyLCEORN2h7HkIA"><strong>here</strong></a> ✌</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ceZWfQSer6REPjiN32hXrg.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c60235cede6b" width="1" height="1" alt=""><hr><p><a href="https://medium.com/hackernoon/classes-in-javascript-then-and-now-c60235cede6b">Classes in JavaScript, then and now</a> was originally published in <a href="https://medium.com/hackernoon">HackerNoon.com</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[FizzBuzz test using RxJS]]></title>
            <link>https://zhirzh.medium.com/fizzbuzz-test-using-rxjs-4be84d09a4ff?source=rss-11f14fe74017------2</link>
            <guid isPermaLink="false">https://medium.com/p/4be84d09a4ff</guid>
            <category><![CDATA[rxjs]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Shirsh Zibbu]]></dc:creator>
            <pubDate>Wed, 01 Jan 2020 10:35:16 GMT</pubDate>
            <atom:updated>2020-01-01T10:40:43.245Z</atom:updated>
            <content:encoded><![CDATA[<h4>A simple solution to a simple problem using a tool that is simply overkill.</h4><p>What is this <strong>FizzBuzz</strong> test?</p><blockquote>Write a program that prints the numbers from 1 to 100. But for multiples of three print “<strong>Fizz</strong>” instead of the number and for the multiples of five print “<strong>Buzz</strong>”. For numbers which are multiples of both three and five print “<strong>FizzBuzz</strong>”.<br>— <a href="http://wiki.c2.com/?FizzBuzzTest">wiki.c2.com</a></blockquote><p>The problem itself isn’t very hard and can be solved with a simple loop iterating over numbers 1 through 100 that prints values matching one of the conditions. The only obvious gotcha is to check for “<em>multiples of both three and five</em>” after checking for multiples of either one.</p><pre>for (let i=1; i&lt;=100; i++) {<br>  if (i%3 === 0 &amp;&amp; i%5 === 0) console.log(&quot;FizzBuzz&quot;)<br>  else if (i%3 === 0) console.log(&quot;Fizz&quot;)<br>  else if (i%5 === 0) console.log(&quot;Buzz&quot;)<br>  else console.log(i)<br>}</pre><pre><em>//&gt; 1 2 Fizz 4 Buzz Fizz 7 8 ... 13 14 FizzBuzz 16 17 ...</em></pre><h3>FizzBuzz test using RxJS</h3><p>One obvious solution using RxJS is to convert the loop into an observable and map over it. You can try this <a href="https://rxviz.com/v/QJVnvZvJ"><strong>here</strong></a>.</p><pre>const { range } = Rx;<br>const { map } = RxOperators;</pre><pre>range(1, 100).pipe(<br>  map(i =&gt; {<br>    if (i%3 === 0 &amp;&amp; i%5 === 0) console.log(&quot;FizzBuzz&quot;)<br>    else if (i%3 === 0) console.log(&quot;Fizz&quot;)<br>    else if (i%5 === 0) console.log(&quot;Buzz&quot;)<br>    else console.log(i)<br>  })<br>)</pre><pre><em>//&gt; 1 2 Fizz 4 Buzz Fizz 7 8 ... 13 14 FizzBuzz 16 17 ...</em></pre><p>But there’s another way to do this. Let’s consider the output values as a single stream.</p><pre>Output$ : 1 2 <strong>F</strong> 4 <strong>B</strong> <strong>F</strong> 7 8 ... 13 14 <strong><em>FB</em></strong> 16 17 ...</pre><p>We can split this stream into 4 different streams, each emitting a single kind of value.</p><pre>Output$   : 1 2 <strong>F</strong> 4 <strong>B</strong> <strong>F</strong> 7 8 F B  ... 13 14 <strong><em>FB</em></strong> 16 17 ...</pre><pre>Number$   : 1 2 3 4 5 6 7 8 9 10 ... 13 14 15 16 17 ...<br>Fizz$     : _ _ F _ _ F _ _ F __ ... __ __ F  __ __ ...<br>Buzz$     : _ _ _ _ B _ _ _ _ B  ... __ __ B  __ __ ...<br>FizzBuzz$ : _ _ _ _ _ _ _ _ _ __ ... __ __ FB __ __ ...</pre><p>The Fizz$ stream emits values once every 3 terms and the Buzz$ stream emits once every 5 terms. Naturally, FizzBuzz$ stream emits once every 15 terms. We can now zip together these streams and pick values in decreasing precedence:</p><ul><li>FizzBuzz$</li><li>Fizz$ or Buzz$</li><li>Number$</li></ul><p>You can try this <a href="https://rxviz.com/v/7JXEv6z8"><strong>here</strong></a>.</p><pre>const { range } = Rx;<br>const { map, tap, zip } = RxOperators;</pre><pre>const Number$ = range(1, 100)</pre><pre>const Fizz$ = Number$.pipe(<br>  map(i =&gt; i%3 === 0 ? &#39;Fizz&#39; : null)<br>)</pre><pre>const Buzz$ = Number$.pipe(<br>  map(i =&gt; i%5 === 0 ? &#39;Buzz&#39; : null)<br>)</pre><pre>const FizzBuzz$ = Fizz$.pipe(<br>  zip(Buzz$),<br>  map(([f, b]) =&gt; (f === null || b === null) ? null : &quot;FizzBuzz&quot;)<br>)</pre><pre>const Output$ = FizzBuzz$.pipe(<br>  zip(Buzz$, Fizz$, Number$),<br>  map(xs =&gt; xs.find(x =&gt; x !== null))<br>)</pre><pre>Output$.pipe(<br>  tap(console.log)<br>)</pre><pre><em>//&gt; 1 2 Fizz 4 Buzz Fizz 7 8 ... 13 14 FizzBuzz 16 17 ...</em></pre><h3>Simple is better than complex</h3><p>This was rather intense for such a simple problem. Can we do better?</p><p>If we look at Fizz$ and Buzz$ streams, we can see that they emit a repeating set of values and really don’t depend on Number$ stream. So let’s write them that way.</p><pre>const { from } = Rx;</pre><pre>const Fizz$ = from([null, null, &#39;fizz&#39;]).pipe(repeat())<br>const Buzz$ = from([null, null, null, null, &#39;buzz&#39;]).pipe(repeat())</pre><p>We can also eliminate the FizzBuzz$ stream since it is just a combination of the Fizz$ and Buzz$ streams and instead construct the “FizzBuzz” values inside a map() operator. Then we repeat the final step from the previous setup and get our Output$ stream.</p><pre>const { from, range } = Rx;<br>const { map, repeat, tap, zip } = RxOperators;</pre><pre>const Number$ = range(1, 100)</pre><pre>const Fizz$ = from([null, null, &#39;fizz&#39;]).pipe(repeat())<br>const Buzz$ = from([null, null, null, null, &#39;buzz&#39;]).pipe(repeat())</pre><pre>const Output$ = Fizz$.pipe(<br>  zip(Buzz$),<br>  map(fb =&gt; fb.join(&#39;&#39;)), // construct &quot;FizzBuzz&quot;<br>  zip(Number$),<br>  map(xs =&gt; xs.find(x =&gt; !!x)),<br>)</pre><pre>Output$.pipe(<br>  tap(console.log)<br>)</pre><pre><em>//&gt; 1 2 Fizz 4 Buzz Fizz 7 8 ... 13 14 FizzBuzz 16 17 ...</em></pre><p>You can try this <a href="https://rxviz.com/v/2ORzve2O"><strong>here</strong></a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4be84d09a4ff" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ReactIndia trivia quiz Day2 answers]]></title>
            <link>https://zhirzh.medium.com/reactindia-trivia-quiz-day2-answers-c9fb3d41eed6?source=rss-11f14fe74017------2</link>
            <guid isPermaLink="false">https://medium.com/p/c9fb3d41eed6</guid>
            <category><![CDATA[reactindia]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Shirsh Zibbu]]></dc:creator>
            <pubDate>Sun, 29 Sep 2019 04:25:26 GMT</pubDate>
            <atom:updated>2019-09-30T20:10:32.991Z</atom:updated>
            <content:encoded><![CDATA[<blockquote>Disclaimer: The quiz was for fun and the questions do not make for good interview questions.</blockquote><h4>What is the output of this snippet?</h4><pre>const <strong>foo</strong> = (x, ...y) =&gt; new Array(2)</pre><pre>console.log(foo.length)</pre><p><strong><em>Answer:</em></strong> 1</p><p>A function’s length property is the number of required parameters given in the function definition and “rest” parameters are not considered required parameters. See <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/length">here</a> and <a href="https://developer.mozilla.org/docs/Web/JavaScript/Reference/Functions/rest_parameters">here</a>.</p><h4>Which video format was designed specifically for serving video on the web?</h4><p><strong><em>Answer:</em></strong> WebM</p><p>WebM is a royalty-free video media format to be used in video &amp; audio elements. See <a href="https://wikipedia.org/wiki/WebM">here</a>.</p><h4>In TypeScript, which of the following can be assigned to variable c?</h4><pre>type <strong>A</strong> = {<br>  x: string<br>}</pre><pre>type <strong>B</strong> = {<br>  y: number<br>}</pre><pre>type <strong>C </strong>= A &amp; B</pre><pre>let <strong>c</strong>: C</pre><p><strong><em>Answer:</em></strong> c = { x: &quot;xmas&quot;, y: 123 }</p><p>An intersection type of multiple <em>non-primitive</em> types is a new non-primitive type which has all the keys from all the participating types. See <a href="http://www.typescriptlang.org/play/#code/C4TwDgpgBAglC8UDeUCGAuKA7ArgWwCMIAnKAXwFgAoUSKAIQWSgMwGdhiBLLAc3OrVa0AMJM4AMgbUA9DKjCoYxCgzZ8RYgBoW7Tj36Uq1AMYB7LBygnMy5NSiO0mAIwAmAMxaHT1lADkAGZmZv7eVEZAA">here</a>.</p><pre>type <strong>A</strong> = { a: number }<br>type <strong>B</strong> = { b: string }</pre><pre>type <strong>C</strong> = A &amp; B // { a: number, y: string }</pre><pre>const <strong>c</strong>: C = {<br>    a: 123,<br>    b: &#39;foo&#39;,<br>}</pre><p>Moreover, if a key exists in multiple participating types, they form an intersection:</p><pre>type <strong>A</strong> = { x: number }<br>type <strong>B</strong> = { x: string }<br>type <strong>C</strong> = { x: 123 }</pre><pre>type <strong>D</strong> = A &amp; B // { x: never }</pre><pre>type <strong>E</strong> = A &amp; C // { x: 123 }</pre><h4>What will this component render if a parent component is rendered at time t=0s and t=1s?</h4><pre>function <strong>Foo</strong>() {<br>  let <strong>data</strong> = 5</pre><pre>  setTimeout(() =&gt; {<br>    data += 3<br>  }, 500)<br>  <br>  return &lt;div&gt;{data}&lt;/div&gt;<br>}</pre><p><strong><em>Answer:</em></strong> 5, 5</p><p>Since Foo is a stateless functional component and data is just a local variable, the rendered content will not change even if the parent re-renders multiple times.</p><h4>Who is the creator of JavaScript?</h4><p><strong><em>Answer:</em></strong> Brendan Eich</p><p>Read more <a href="https://wikipedia.org/wiki/Brendan_Eich#Netscape_and_JavaScript">here</a> and <a href="https://brendaneich.com/">here</a>.</p><h4>What is the output of this snippet?</h4><pre>class <strong>A</strong> {<br>  static <strong>foo</strong> = &quot;hello&quot;<br>}</pre><pre>class <strong>B</strong> extends A {<br>  foo = &quot;world&quot;<br>}</pre><pre>console.log(B.foo)</pre><p><strong><em>Answer:</em></strong> hello</p><p>When a class extends another class, the sub-class will delegate all static key lookups to the base-class.</p><h4>Which warning, if any, is shown for this snippet?</h4><pre>const <strong>ListItem</strong> = props =&gt; (<br>  &lt;li key={props.value}&gt;<br>    {props.value}<br>  &lt;/li&gt;<br>)</pre><pre>const <strong>NumberedList</strong> = props =&gt; {<br>  const <strong>items</strong> = props.numbers.map(<br>    x =&gt; <strong>ListItem</strong>({ value: x })<br>  )</pre><pre>  return &lt;ol&gt;{items}&lt;/ol&gt;<br>}</pre><p><strong><em>Answer:</em></strong> No warning</p><p>Typically, when an array of React elements is rendered, we need to provide each element a unique key for React to be able to track elements across renders. If keys are not provided then we get a warning saying “<em>a key should be provided for list items</em>”.</p><p>However, this is only true for elements rendered using the JSX syntax, like &lt;ListItem /&gt;which translated into React.createElement(ListItem) but that is not what happens in the snippet. Instead, we directly call ListItem() as a regular function and use the returned element.</p><p>Since React was not involved in rendering, it doesn’t track the element and doesn’t mind the otherwise missing key attribute.</p><h4>What will be the output of this snippet?</h4><pre>new Promise(() =&gt; {<br>  throw new Error(&quot;Hungry&quot;)<br>}).catch(() =&gt; {<br> console.log(&quot;Order Food&quot;)<br>})</pre><p><strong><em>Answer:</em></strong> Order Food</p><p>When a promise executor throws in a synchronous fashion, the promise gets rejected. See <a href="https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise#Parameters">here</a>.</p><h4>What is the output of this snippet?</h4><pre>const <strong>x</strong> = Object.create(<strong>null</strong>)<br>x.abc = &quot;abc&quot;</pre><pre>console.log(x.hasOwnProperty(&quot;abc&quot;))</pre><p><strong><em>Answer:</em></strong> Uncaught error saying x.hasOwnProperty() is not a function.</p><p>Creating a new object using Object.create(foo) sets the new object’s <em>[[Prototype]]</em> as foo and not the deafult Object.prototype object.</p><p>And since this new object has no access to Object.prototype#hasOwnProperty() method, trying to invoke an “undefined” method will throw. See <a href="https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object/create">here</a>.</p><h4>What is the order of tasks the browser performs in painting a frame</h4><p><strong><em>Answer:</em></strong> Style &gt; Layout &gt; Paint &gt; Composite</p><p>The process of rendering content on the screen is best explained at <a href="https://developers.google.com/web/fundamentals/performance/rendering#the_pixel_pipeline">developers.google.com</a> and must be read as a whole.</p><blockquote>We are hiring! Head over to <a href="https://tech.anarock.com/hiring#open_positions">our website</a> to see the open positions.</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c9fb3d41eed6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ReactIndia trivia quiz Day1 answers]]></title>
            <link>https://zhirzh.medium.com/reactindia-trivia-quiz-by-anarocktech-f7426d957e23?source=rss-11f14fe74017------2</link>
            <guid isPermaLink="false">https://medium.com/p/f7426d957e23</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[reactindia]]></category>
            <dc:creator><![CDATA[Shirsh Zibbu]]></dc:creator>
            <pubDate>Sat, 28 Sep 2019 02:50:32 GMT</pubDate>
            <atom:updated>2019-09-30T08:56:47.858Z</atom:updated>
            <content:encoded><![CDATA[<blockquote><strong>Disclaimer</strong>: The quiz was for fun and the questions do not make for good interview questions.</blockquote><h4>What is the difference in extending React.PureComponent instead of React.Component?</h4><p>Answer: <strong><em>React.PureComponent will not re-render if either of props or state have not changed</em></strong></p><p>React’sPureComponent comes with a default implementation shouldComponentUpdate() that perform shallow comparisons for prop &amp; state. This means that a re-render will only happen if either of the two changes.</p><p>Also, there’s now a new React method — React.Memo() — that does the same for functional components.</p><p>You can read more about this <a href="https://reactjs.org/docs/react-api.html#reactpurecomponent">here</a> and <a href="https://reactjs.org/docs/react-api.html#reactmemo">here</a>.</p><h4>Which lifecycle methods can be used with stateful functional components?</h4><p><strong><em>Answer:</em></strong> None of the lifecycle methods</p><p>React provides the lifecycle methods as part of the Component &amp; PureComponent base-classes. Since functional components don’t extend either one, they can’t implement any of the lifecycle methods. See <a href="https://reactjs.org/docs/state-and-lifecycle.html">here</a>.</p><h4>Which lifecycle methods are NOT triggered when shouldComponentUpdate() returns false?</h4><p><strong><em>Answer:</em></strong> render(), componentDidUpdate()</p><p>When a element’s shouldComponentUpdate() returns true, that element begins to re-render and triggers these lifecycle methods (in order):</p><ul><li>componentWillUpdate()</li><li><em>getDerivedStateFromProps()</em></li><li>render()</li><li>componentDidUpdate()</li></ul><p>You can read more about the lifecycle methods (new &amp; old) <a href="https://reactjs.org/docs/react-component.html#the-component-lifecycle">here</a>.</p><h4>In React, how do you stop event propagation?</h4><p><strong><em>Answer:</em></strong> e.stopPropagation()</p><p>React’s SyntheticEvent has the same effect when calling stopPropagation() method and the initial versions also supported returning “false” to stop event propagation. However, as of v0.14, returning false from an event handler will no longer stop event propagation. see <a href="https://reactjs.org/docs/events.html#overview">here</a>.</p><h4>What is wrong with the key attribute in the ListItem component?</h4><pre>const <strong>ListItem</strong> = props =&gt; {<br>  return (<br>    &lt;li <strong>key</strong>={props.value}&gt;{props.value}&lt;/li&gt;<br>} </pre><pre>const <strong>NumberedList</strong> = props =&gt; {<br>  const <strong>listItems</strong> = props.numbers.map(<br>    x =&gt; &lt;ListItem <strong>value</strong>={x} /&gt;<br>  )</pre><pre>  return &lt;ol&gt;{listItems}&lt;/ol&gt;<br>}</pre><p><strong><em>Answer:</em></strong> The key should be on the ListItem element</p><p>Keys allow React to keep track of <strong>elements</strong> which have been added, changed, and removed. For that reason, the key attribute should be placed on &lt;ListItem /&gt; rather than &lt;li /&gt;. See <a href="https://reactjs.org/docs/lists-and-keys.html#keys">here</a>.</p><h4>What is the output of this snippet?</h4><pre>const <strong>p</strong> = new <strong>Promise</strong>((res, rej) =&gt; {<br>  return <strong>setTimeout</strong>(() =&gt; {<br>    throw <strong>Error</strong>(&quot;Hungry&quot;)<br>  }, 1000)<br>})</pre><pre>p.<strong>catch</strong>(e =&gt; {<br>  console.log(&quot;Order Food!&quot;)<br>})</pre><p><strong><em>Answer:</em></strong> Uncaught error saying “Hungry”</p><p>This one is tricky, but if we look closely, the callback passed to setTimeout() is the only function that will throw an error. Since a timer callback execution always happens in a new <a href="https://developer.mozilla.org/docs/Glossary/Call_stack">call-stack</a>.</p><p>When the error is thrown, it will bubble-up to the top of this new stack and trigger an “uncaught error” message. However, the error will <strong>not</strong> “leak out” to our primary stack (or any other stack either).</p><p>Also, since we never called res or rej, the promise is never “fulfiled”. And it is fairly easy to see that any callbacks on an unfulfilled promise will ever execute.</p><h4>What is the output of this snippet?</h4><pre>const <strong>foo</strong> = {<br>  <strong>get</strong> name() {<br>    return this.name<br>  },</pre><pre>  <strong>set</strong> name(name) {<br>    this.name = name<br>  }<br>}</pre><pre>foo.name = &quot;baz&quot;</pre><p><strong><em>Answer:</em></strong> An uncaught error saying “maximum call stack size exceeded”</p><p>The setter has infinite recursion since it is trying to set “name” on this.</p><h4>What is the output of this snippet?</h4><pre>const <strong>foo</strong> = function <strong>baz</strong>() {}<br>foo.name = &quot;guf&quot;<br>console.log(foo.name)</pre><p><strong><em>Answer: baz</em></strong></p><p>A function’s name is a read-only property and cannot be modified by a simple assignment. Also, assigning a named function expression to a variable can be broken down into a two-step process. See <a href="https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Function/name">here</a>.</p><pre>function <strong>baz</strong>() {}<br>const <strong>foo</strong> = baz</pre><p>This makes it certain that foo.name will indeed be “baz”.</p><h4>Which of these methods does NOT exist on an svg element?</h4><p>Answer: <strong><em>getBoundBox</em></strong></p><p>If we explore the prototype chain of DOM elements, we will find that the methods getClientRects() and getBoundingClientRect() are defined on the <a href="https://developer.mozilla.org/docs/Web/API/Element">Element</a> class’s prototype and getBBox() is defined on the <a href="https://developer.mozilla.org/en-US/docs/Web/API/SVGGraphicsElement">SVGGraphicsElement</a> class.</p><p>You can explore the DOM tree at <a href="https://zhirzh.github.io/prototype-tree/?mode=browser">prototype-tree</a>. You can change the URL parameter “mode” to valuesnode for exploring NodeJS &amp; core for vanilla JS.</p><h4>What is the output of this snippet?</h4><pre>function <strong>foo</strong>(x = 0, y = 1) {<br>  return [1, 2, 3]<br>}</pre><pre>console.log(foo.length)</pre><p><strong><em>Answer:</em></strong> 0</p><p>A function&#39;s length property is the number of required parameters given in the function definition and a parameter with a default value is not considered required. See <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/length">here</a>.</p><blockquote>We are hiring! Head over to <a href="https://tech.anarock.com/hiring#open_positions">our website</a> to see the open positions.</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f7426d957e23" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Making CRA apps work with SSR — Part 4]]></title>
            <link>https://zhirzh.medium.com/making-cra-apps-work-with-ssr-part-4-2954d04ea67c?source=rss-11f14fe74017------2</link>
            <guid isPermaLink="false">https://medium.com/p/2954d04ea67c</guid>
            <category><![CDATA[server-side-rendering]]></category>
            <category><![CDATA[react-router]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[express]]></category>
            <dc:creator><![CDATA[Shirsh Zibbu]]></dc:creator>
            <pubDate>Mon, 22 Oct 2018 12:45:29 GMT</pubDate>
            <atom:updated>2018-10-23T10:36:03.855Z</atom:updated>
            <content:encoded><![CDATA[<h3>Making CRA apps work with SSR — Part 4</h3><h4>Routing with react-router</h4><blockquote>This article is now part of a much longer series of posts titled <a href="https://hackernoon.com/making-cra-apps-work-with-ssr-b45f7c23d8db">Making CRA apps work with SSR</a>. You can find the the code <a href="https://github.com/zhirzh/cra-with-ssr">here on github</a>.</blockquote><p>This is the fourth entry in my <a href="https://medium.com/@zhirzh/making-cra-apps-work-with-ssr-b45f7c23d8db">CRA apps with SSR</a> series. This time we’ll work on routing for our app.</p><p>We’ll look at two types of routing with <em>react-router</em> — static routes and dynamic routes. There’s also route params and redux integration.</p><h3>Add routing to client</h3><p>We’ll use <a href="https://github.com/ReactTraining/react-router"><em>react-router</em></a> for routing in our client app. But first, we need to do some housekeeping. We’ll use the <em>App</em> component as an entry point for our routing logic. This means that we must find a new home for our app code</p><p>Let’s call it the <em>Home</em> component. We’ll just rename the files …</p><pre># client/</pre><pre>mv src/{App,Home}.js<br>mv src/{App,Home}.css</pre><p>… and make some small changes in the new <em>Home</em> component …</p><pre>&gt;&gt;&gt; client/src/Home.js</pre><pre>import React, { Component } from &#39;react&#39;;<br>import { connect } from &#39;react-redux&#39;;<br>import { addTodo, updateTodo, removeTodo } from &#39;./logic/todos&#39;;<br>import logo from &#39;./logo.svg&#39;;<br>import &#39;./<strong>Home</strong>.css&#39;;</pre><pre>class <strong>Home</strong> extends Component {<br>  state = {<br>    newTask: &#39;&#39;,<br>  };<br>  ...<br>}</pre><pre>export default connect(<br>  state =&gt; ({<br>    todos: state.todos,<br>  }),</pre><pre>  {<br>    addTodo,<br>    updateTodo,<br>    removeTodo,<br>  }<br>)(<strong>Home</strong>);</pre><p>and the old (now renovated) <em>App</em> component.</p><pre>&gt;&gt;&gt; client/src/App.js</pre><pre>import React, { Component } from &#39;react&#39;;<br><strong>import Home from &#39;./Home&#39;;</strong></pre><pre>class App extends Component {<br>  render() {<br>    return <strong>&lt;Home /&gt;</strong>;<br>  }<br>}</pre><pre>export default App;</pre><p>We will now add the router package …</p><pre># client/</pre><pre>npm i react-router-dom</pre><p>… write our routing logic inside <em>App</em> component …</p><pre>&gt;&gt;&gt; client/src/App.js</pre><pre>import React, { Component } from &#39;react&#39;;<br><strong>import { Route, Switch } from &#39;react-router-dom&#39;;</strong><br>import Home from &#39;./Home&#39;;</pre><pre><strong>const NoMatch = () =&gt; (<br>  &lt;div&gt;<br>    &lt;h1&gt;404&lt;/h1&gt;<br>    Page Not Found<br>  &lt;/div&gt;<br>);</strong></pre><pre>class App extends Component {<br>  render() {<br>    return (<br><strong>      &lt;Switch&gt;<br>        &lt;Route path=&quot;/&quot; component={Home} exact /&gt;<br>        &lt;Route render={NoMatch} /&gt;<br>      &lt;/Switch&gt;<br></strong>    )<br>  }<br>}</pre><pre>export default App;</pre><p>… and wrap everything up in a <em>BrowserRouter</em> component.</p><pre>&gt;&gt;&gt; client/src/index.js</pre><pre>import React from &#39;react&#39;;<br>import ReactDOM from &#39;react-dom&#39;;<br>import { Provider } from &#39;react-redux&#39;;<br><strong>import { BrowserRouter } from &#39;react-router-dom&#39;;</strong><br>import &#39;./index.css&#39;;</pre><pre>...</pre><pre>ReactDOM.render(<br>  &lt;Provider store={store}&gt;<br><strong>    &lt;BrowserRouter&gt;</strong><br>      &lt;App /&gt;<br><strong>    &lt;/BrowserRouter&gt;</strong><br>  &lt;/Provider&gt;,</pre><pre>  document.getElementById(&#39;root&#39;)<br>);</pre><pre>...</pre><p><strong><em>Note</em></strong><em>: There’s some perpetuating confusion about the </em>Provider<em> and </em>Router<em> components and who should wrap whom. </em><a href="https://redux.js.org/advanced/usagewithreactrouter#connecting-react-router-with-redux-app"><em>The redux docs are pretty clear on this</em></a><em>. We will wrap </em>Router<em> component in </em>Provider<em> component so that route handlers can get access to the store.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QAtH2_WCFqCUeMh308ftGA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dOyAtzlHJE6jmpJVtxDn8w.png" /></figure><h3>Add routing to server</h3><p>We can now build our react app and move to the server side. We’ll start by installing the packages.</p><pre># server/</pre><pre>npm i react-router</pre><p>The official <a href="https://reacttraining.com/react-router/web/guides/server-rendering">react-router SSR guide</a> gives us some tips on how to add routing to the server side. The idea is that using a browser-first piece of tech in a server environment requires some tricky wiring in the react app itself.</p><p>First off, rewire <em>reactRenderer</em> as an express middleware (and not a router) to selectively render the routes that it catches.</p><pre>&gt;&gt;&gt; server/src/app.js</pre><pre>app.use(cookieParser());</pre><pre><strong>app.use(reactRenderer);</strong></pre><pre>app.use(express.static(BUILD_DIR));</pre><p>In <em>reactRenderer</em>, we match the request URL to a list of URLs that the client uses. If we get a match, render the react app. If not, pass control to the next middleware in the chain.</p><p>We have to pass a location (which is the the request url) to <em>StaticRouter</em> since it has no other way of knowing which route to render.</p><p>We also pass a mystical object called <em>context</em> that serves as a data holder for any routing logic that executes at runtime. The <a href="https://reacttraining.com/react-router/web/guides/server-rendering/adding-app-specific-context-information">docs talk about it</a> and how to use it to handle internal redirects.</p><pre>// react-renderer.js</pre><pre>var React = require(&#39;react&#39;);<br>var { renderToString } = require(&#39;react-dom/server&#39;);<br>var { Provider } = require(&#39;react-redux&#39;);<br><strong>var { matchPath, StaticRouter } = require(&#39;react-router&#39;);</strong></pre><pre>...</pre><pre><strong>var routes = [&#39;/&#39;];</strong></pre><pre>function reactRenderer(req, res, <strong>next</strong>) {<br><strong>  var match = routes.find(route =&gt; matchPath(req.path, {<br>    path: route,<br>    exact: true,<br>  }));</strong></pre><pre><strong>  // bail<br>  if (!match) {<br>    next();</strong></pre><pre><strong>    return;<br>  }</strong></pre><pre><strong>  var location = req.url;<br>  var context = {};</strong></pre><pre>  ...</pre><pre>  var app = renderToString(<br>    &lt;Provider store={store}&gt;<br><strong>      &lt;StaticRouter location={location} context={context}&gt;<br></strong>        &lt;App /&gt;<strong><br>      &lt;/StaticRouter&gt;<br></strong>    &lt;/Provider&gt;<br>  );</pre><pre>  ...<br>}</pre><p>And with just that, we have our minimal routing config.</p><h3>Parametric routing</h3><p>To explore parametric routes, we’ll add a new react component <em>ParaPage</em> that simply renders the props generated by <em>react-router</em>.</p><pre>&gt;&gt;&gt; <strong>client/src/ParaPage.js</strong></pre><pre>import React, { Component } from &#39;react&#39;;</pre><pre>class ParaPage extends Component {<br>  render() {<br>    return (<br>      &lt;div&gt;<br>        &lt;h1&gt;ParaPage&lt;/h1&gt;</pre><pre>        &lt;pre&gt;<br>          {JSON.stringify(this.props.match.params, null, 2)}<br>        &lt;/pre&gt;<br>      &lt;/div&gt;<br>    );<br>  }<br>}</pre><pre>export default ParaPage;</pre><p>Since, the <em>react-router</em> website <a href="https://reacttraining.com/react-router/web/example/url-params">doesn’t talk about</a> the possible route patterns, here’s a list of possibilities. I did my best to complete it, but I missed out a few, list them in the comments below.</p><p>Parametric route patterns:</p><ul><li>glob: /path-1/<strong>*</strong></li><li>named: /path-1/:<strong>foo</strong></li><li>named-glob: /path-1/:foo<strong>*</strong></li><li>named-glob-one: /path-1/:foo<strong>+</strong></li><li>named-optional: /path-1/:foo<strong>?</strong></li><li>named-regex: /path-1/:foo<strong>(\d+)</strong></li><li>unnamed: /path-1/<strong>(.*)</strong></li><li>nested: /path-1/:foo/<strong>bar</strong></li></ul><p><strong><em>Note</em></strong><em>: When mixing different different patterns, it is really important to lay them out in order of decreasing selectivity. For instance, </em><strong><em>glob</em></strong><em> has highest specificity and will match anything that looks like </em>/path-1/<strong>*</strong><em>, whereas </em><strong><em>named-regex</em></strong><em> will only ever match the given the regex.</em></p><pre>&gt;&gt;&gt; client/src/App.js</pre><pre>&lt;Switch&gt;<br>  &lt;Route path=&quot;/&quot; component={Home} exact /&gt;</pre><pre><strong>  &lt;Route path=&quot;/para/:numer_regex(\d+)&quot; component={ParaPage} /&gt;<br>  &lt;Route path=&quot;/para/:text_regex([a-zA-Z]+)&quot; component={ParaPage} /&gt;</strong></pre><pre><strong>  &lt;Route path=&quot;/para/:any&quot; component={ParaPage} /&gt;<br>  &lt;Route path=&quot;/para/:any_regex(.*)&quot; component={ParaPage} /&gt;<br>  &lt;Route path=&quot;/para/(.*)&quot; component={ParaPage} /&gt;<br>  &lt;Route path=&quot;/para/*&quot; component={ParaPage} /&gt;<br>  &lt;Route path=&quot;/para/:any_optional?&quot; component={ParaPage} /&gt;</strong></pre><pre><strong>  &lt;Route path=&quot;/para&quot; exact component={ParaPage} /&gt;</strong></pre><pre>&lt;Route render={NoMatch} /&gt;<br>&lt;/Switch&gt;</pre><p>I suggest taking some time out to try out all these routes. One thing that is of special interest is the presence of trailing slash, the use of <em>exact</em> prop and the position of “/para” route.</p><p>We also need to to add these routes in reactRenderer <strong>in the same order</strong> so the server can handle requests from any one of these.</p><pre>&gt;&gt;&gt; server/src/react-renderer.js</pre><pre>var routes = [<br>  &#39;/&#39;,</pre><pre><strong>  &#39;/para/:number_regex(\\d+)&#39;,<br>  &#39;/para/:text_regex([a-zA-Z]+)&#39;,</strong></pre><pre><strong>  &#39;/para/:any&#39;,<br>  &#39;/para/:any_regex(.*)&#39;,<br>  &#39;/para/(.*)&#39;,<br>  &#39;/para/*&#39;,<br>  &#39;/para/:any_optional?&#39;,</strong></pre><pre><strong>  &#39;/para&#39;,</strong><br>];</pre><h3>Dynamic routing on client</h3><p>Thus far, everything was done in a <em>static</em> fashion. But loading everything ahead of time is a slow process. We can speed things up by loading parts of the app as and when required. This where <a href="https://webpack.js.org/guides/code-splitting/">code splitting</a> comes in.</p><p>The official <a href="https://reacttraining.com/react-router/web/guides/code-splitting">react-router code-splitting guide</a> provides a super easy way to go about it using the <a href="https://github.com/jamiebuilds/react-loadable#introducing-react-loadable"><em>react-loadable</em></a> package.</p><p>Start by installing the packages …</p><pre># client/</pre><pre>npm i react-loadable</pre><p>… then add a new component that will be loaded dynamically …</p><pre><strong>&gt;&gt;&gt; client/src/DynaPage.js</strong></pre><pre>import React, { Component } from &#39;react&#39;;</pre><pre>class DynaPage extends Component {<br>  render() {<br>    return (<br>      &lt;div&gt;<br>        &lt;h1&gt;DynaPage&lt;/h1&gt;<br>      &lt;/div&gt;<br>    );<br>  }<br>}</pre><pre>export default DynaPage;</pre><p>… wrap it inside <em>Loadble</em> HOC …</p><pre>&gt;&gt;&gt; client/src/App.js</pre><pre>import React, { Component } from &#39;react&#39;;<br>import { Route, Switch } from &#39;react-router-dom&#39;;<br><strong>import Loadable from &#39;react-loadable&#39;;</strong><br>import Home from &#39;./Home&#39;;<br>import ParaPage from &#39;./ParaPage&#39;;</pre><pre>...</pre><pre><strong>const DynaPageAsync = Loadable({<br>  loading: () =&gt; &lt;h1&gt;Loading...&lt;/h1&gt;,<br>  loader: () =&gt; import(&#39;./DynaPage&#39;),<br>});</strong></pre><pre>class App extends Component {...}</pre><pre>export default App;</pre><p>… and connect it to a <em>Route.</em></p><pre>&gt;&gt;&gt; client/src/App.js</pre><pre>...</pre><pre>class App extends Component {<br>  render() {<br>    return (<br>      &lt;Switch&gt;<br>        &lt;Route path=&quot;/&quot; component={Home} exact /&gt;</pre><pre>        ...</pre><pre><strong>        &lt;Route path=&quot;/dyna&quot; component={DynaPageAsync} /&gt;</strong></pre><pre>        &lt;Route render={NoMatch} /&gt;<br>      &lt;/Switch&gt;<br>    )<br>  }<br>}</pre><h3>Dynamic routing on server</h3><p>Rendering dynamic routes on the server is a simple task. Just load all modules <strong>before mounting</strong> the root component.</p><p>We will use <em>the</em> <a href="https://github.com/thejameskyle/react-loadable/#loadablepreloadall"><em>preloadAll()</em></a><em> method </em>that loads the dynamic modules recursively and returns a promise and we must wait for this promise to resolve before we can render our app.</p><pre>&gt;&gt;&gt; server/src/react-renderer.js</pre><pre>var React = require(&#39;react&#39;);<br>var { renderToString } = require(&#39;react-dom/server&#39;);<br>var { Provider } = require(&#39;react-redux&#39;);<br>var { matchPath, StaticRouter } = require(&#39;react-router&#39;);<br><strong>var Loadable = require(&#39;../../client/node_modules/react-loadable&#39;);</strong></pre><pre>...</pre><pre>function reactRenderer(req, res, next) {<br>  ...</pre><pre><strong>  Lodable.preloadAll().then(() =&gt; {</strong><br>    var app = renderToString(<br>      &lt;Provider store={store}&gt;<br>        &lt;StaticRouter location={location} context={context}&gt;<br>          &lt;App /&gt;<br>        &lt;/StaticRouter&gt;<br>      &lt;/Provider&gt;<br>    );</pre><pre>    var html = fs<br>      .readFileSync(path.join(BUILD_DIR, &#39;index.html&#39;), &#39;utf8&#39;)<br>      .replace(&#39;__ROOT__&#39;, app)<br>      .replace(<br>        &#39;__REDUX__&#39;,<br>        JSON.stringify(store.getState())<br>      );</pre><pre>    res.send(html);<br><strong>  });</strong><br>}</pre><pre>module.exports = reactRenderer;</pre><p><strong><em>Note</em></strong><em>: I am importing </em>react-loadable<em> from the </em>client/<em> folder because the package maintains an internal list of promises and </em><a href="https://github.com/jamiebuilds/react-loadable/blob/4a3e74ffdf380d189c5aac13bb9526da974ac2e8/src/index.js#L305-L309"><em>calling preloadAll() flushes that list</em></a><em>.</em></p><p><em>This can be avoided by using the same </em>node_modules/<em> folder for client &amp; server or by writing client &amp; server code in a shared repo.</em></p><p><em>Personally, I would </em><strong><em>never</em></strong><em> use either of the “hacks”.</em></p><pre># client/</pre><pre>npm run build<br>...</pre><pre># server/</pre><pre>npm start<br>...</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2qsivkwQy_lozY60nMZ1Ew.png" /></figure><h3>The End</h3><p>With <em>react-router</em> and <em>react-loadable</em> packages, we added static, parametric and dynamic routing to both — the client and the server code. That’s a lot for one post! The code is <a href="https://github.com/zhirzh/cra-with-ssr/tree/fb811e8985587c8801697b8dd68438ba575cde45">here on github</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2954d04ea67c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Making CRA apps work with SSR — Part 3]]></title>
            <link>https://zhirzh.medium.com/making-cra-apps-work-with-ssr-part-3-c981adb8bdab?source=rss-11f14fe74017------2</link>
            <guid isPermaLink="false">https://medium.com/p/c981adb8bdab</guid>
            <category><![CDATA[react-redux]]></category>
            <category><![CDATA[redux]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[server-side-rendering]]></category>
            <dc:creator><![CDATA[Shirsh Zibbu]]></dc:creator>
            <pubDate>Mon, 22 Oct 2018 12:28:08 GMT</pubDate>
            <atom:updated>2018-10-23T10:33:52.165Z</atom:updated>
            <content:encoded><![CDATA[<h3>Making CRA apps work with SSR — Part 3</h3><h4>Integrating Redux</h4><blockquote>This article is now part of a much longer series of posts titled <a href="https://hackernoon.com/making-cra-apps-work-with-ssr-b45f7c23d8db">Making CRA apps work with SSR</a>. You can find the the code <a href="https://github.com/zhirzh/cra-with-ssr">here on github</a>.</blockquote><p>In a <a href="https://medium.com/@zhirzh/making-cra-apps-work-with-ssr-part-1-8f5f813d510b">part 2</a>, we added static assets to our barebones CRA + SSR app. In this post we’ll add <a href="http://redux.js.org/"><em>redux</em></a> into the mix.</p><h3>Add redux to client</h3><p>Before we can integrate redux in the server code, we need to add it in the client code. I am using the ubiquitous “todos” app for demonstrating redux integration.</p><p>Since the main focus here is server integration, I’ll skip the client integration. You can checkout get the starter code <a href="https://github.com/zhirzh/cra-with-ssr/tree/client-redux">here on github</a>.</p><pre># my-app/</pre><pre>git checkout <strong>client-redux</strong></pre><pre>npm i<br>npm start</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*E_jOz5NgIHu3HuaPohFj6Q.png" /></figure><h3>Add redux to server</h3><p>Thanks to the official <a href="https://redux.js.org/recipes/serverrendering">redux Server Rendering guide</a>, redux integration is actually pretty easy.</p><p>Install the packages …</p><pre># server/</pre><pre>npm i redux react-redux</pre><p>… and connect redux with <a href="https://github.com/reduxjs/react-redux/blob/master/docs/api.md#provider">&lt;Provider /&gt;</a></p><pre>&gt;&gt;&gt; server/src/react-renderer.js</pre><pre>var React = require(&#39;react&#39;);<br>var { renderToString } = require(&#39;react-dom/server&#39;);<br><strong>var { Provider } = require(&#39;react-redux&#39;);</strong></pre><pre>var { BUILD_DIR } = require(&#39;./paths&#39;);<br>var App = require(&#39;../../client/lib/App&#39;).default;<br><strong>var configureStore = require(&#39;../../client/lib/modules/store&#39;).default;</strong></pre><pre>...</pre><pre>function reactRenderer(req, res) {<br><strong>  var store = configureStore();</strong></pre><pre><strong>  var app = renderToString(<br>    &lt;Provider store={store}&gt;<br>      &lt;App /&gt;<br>    &lt;/Provider&gt;<br>  );</strong></pre><pre>  var html = fs<br>    .readFileSync(path.join(BUILD_DIR, &#39;index.html&#39;), &#39;utf8&#39;)<br>    .replace(&#39;__ROOT__&#39;, app);</pre><pre>  return res.send(html);<br>}</pre><h3>Initial render on server</h3><p>Simply adding a redux store doesn’t do much. We also need some data inside. We can get data into the store by declaring it in the renderer, importing from a database or dispatching actions.</p><pre>&gt;&gt;&gt; server/src/react-renderer.js</pre><pre>var { BUILD_DIR } = require(&#39;./paths&#39;);<br>var App = require(&#39;../../client/lib/App&#39;).default;<br>var configureStore = require(&#39;../../client/lib/modules/store&#39;).default;<br><strong>var { addTodo } = require(&#39;../../client/lib/logic/todos&#39;);</strong></pre><pre>function reactRenderer(req, res) {<br><strong>  var state = {<br>    todos: [<br>      {<br>        id: 0,<br>        task: &#39;task from server&#39;,<br>      },<br>    ],<br>  }</strong></pre><pre><strong>  var store = configureStore({<br>    state,<br>  });</strong></pre><pre><strong>  store.dispatch(addTodo(&#39;also from server&#39;));</strong></pre><pre>  var app = renderToString(...);</pre><pre>  ...<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MiXlI24iHl0xzRGRs3174A.png" /></figure><p>We can see that the although data is being rendered on the server, it doesn’t appear anywhere on the client. That’s because the store on client and server are not <em>in-sync</em>.</p><h3>Initial render on client</h3><p>We have to <em>embed</em> the server state for the client to use during its first render.</p><p>We need to add a render hook in client/public/index.html for redux …</p><pre>&gt;&gt;&gt; client/public/index.html</pre><pre>&lt;div id=&quot;root&quot;&gt;__MY_APP__&lt;/div&gt;<br><strong>&lt;script&gt;window.__INITIAL_STATE__ = __REDUX__&lt;/script&gt;</strong></pre><p>… replace it with the server store state …</p><pre>&gt;&gt;&gt; server/src/react-renderer.js</pre><pre>function reactRenderer(req, res) {<br>  var state = {...}</pre><pre>  var store = configureStore({<br>    state,<br>  });</pre><pre>  store.dispatch(addTodo(&#39;also from server&#39;));</pre><pre>  var app = ...;</pre><pre>  var html = fs<br>    .readFileSync(path.join(BUILD_DIR, &#39;index.html&#39;), &#39;utf8&#39;)<br>    .replace(&#39;__ROOT__&#39;, app)<br><strong>    .replace(<br>      &#39;__REDUX__&#39;,<br>      JSON.stringify(store.getState())<br>    );</strong></pre><pre>  return res.send(html);<br>}</pre><p>… and tell client redux to get the initial state from window.__INITIAL_STATE__</p><pre>&gt;&gt;&gt; client/src/index.js</pre><pre><strong>const state = window.__INITIAL_STATE__;</strong></pre><pre>const store = configureStore({<br>  middlewares: [loggerMiddleware],<br>  <strong>state,</strong><br>});</pre><pre>ReactDOM.render(<br>  &lt;Provider store={store}&gt;<br>    &lt;App /&gt;<br>  &lt;/Provider&gt;,</pre><pre>  document.getElementById(&#39;root&#39;)<br>);</pre><h3>The End</h3><p>If we now build our client &amp; start our server, everything should work.</p><pre># client/<br>npm run build<br>...</pre><pre># server<br>npm start<br>...</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tZNt0w1qv85SUCoJhchF9w.png" /></figure><p>So far, we have created a CRA app with SSR with asset imports and redux. In the next part, I will add routing to the existing setup using <a href="https://reacttraining.com/react-router/web"><em>react-router</em></a>.</p><p>Since routing is a major part of any web project, this might take some time. In the meantime, I might add some other niceties, like support for css-modules.</p><p>And as always, you can find the code for this part <a href="https://github.com/zhirzh/cra-with-ssr/tree/bc5b49c49f1cd3398ffac4cdd2c9724aa5189320">here on github</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c981adb8bdab" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Making CRA apps work with SSR — Part 2]]></title>
            <link>https://zhirzh.medium.com/making-cra-apps-work-with-ssr-part-2-ff5f644e9d24?source=rss-11f14fe74017------2</link>
            <guid isPermaLink="false">https://medium.com/p/ff5f644e9d24</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[css-modules]]></category>
            <category><![CDATA[server-side-rendering]]></category>
            <dc:creator><![CDATA[Shirsh Zibbu]]></dc:creator>
            <pubDate>Mon, 22 Oct 2018 12:22:13 GMT</pubDate>
            <atom:updated>2018-10-22T12:24:13.943Z</atom:updated>
            <content:encoded><![CDATA[<h3>Making CRA apps work with SSR — Part 2</h3><h4>Adding support for static assets</h4><blockquote>This article is now part of a much longer series of posts titled <a href="https://hackernoon.com/making-cra-apps-work-with-ssr-b45f7c23d8db">Making CRA apps work with SSR</a>. You can find the the code <a href="https://github.com/zhirzh/cra-with-ssr">here on github</a>.</blockquote><p>In <a href="https://medium.com/@zhirzh/making-cra-apps-work-with-ssr-part-1-1e23d6b1603d">part 1</a>, we started working on a more wholesome way of implementing server-side rendering in a react app made using <a href="https://github.com/facebook/create-react-app"><em>create-react-app</em></a>. As of now, asset imports that are not working.</p><p>I avoided the problem in the previous post by removing the imports. Let’s add them back in.</p><pre>&gt;&gt;&gt; client/src/App.js</pre><pre>import React, { Component } from &#39;react&#39;;<br><strong>import logo from &#39;./logo.svg&#39;;<br>import &#39;./App.css&#39;;</strong></pre><pre>// ...</pre><p>This is a problem that <a href="https://webpack.js.org/">webpack</a> (and many other bundlers) have already solved for us. At this point, it seems like an obvious choice to use it. And there’s a babel plugin that does exactly that — <a href="https://www.npmjs.com/package/babel-plugin-webpack-loaders"><em>babel-plugin-webpack-loaders</em></a>.</p><p>The plugin BPWL works by running webpack externally and allows us to use webpack loaders as part of babel transformations.</p><p>However, BPWL does <strong>not</strong> support babel@v7 and is a <em>dead end</em>. It still works if you’re using babel@v6.</p><h4>Solution</h4><p>We will use the babel plugin <a href="https://www.npmjs.com/package/babel-plugin-transform-assets"><em>babel-plugin-transform-assets</em></a> for dealing with asset imports.</p><p>It transforms asset imports into slugs similar to webpack. This is crucial for maintaining import sanity between our server rendered app and our client build output.</p><p>To make it work, install the plugin …</p><pre># client/</pre><pre>npm i babel-plugin-transform-assets</pre><p>… and add the config.</p><pre>&gt;&gt;&gt; client/package.json</pre><pre>{<br>  &quot;babel&quot;: {<br>    &quot;plugins&quot;: [<br>      &quot;@babel/plugin-transform-modules-commonjs&quot;,<br><strong>      [<br>        &quot;transform-assets&quot;,<br>        {<br>          &quot;extensions&quot;: [<br>            &quot;css&quot;,<br>            &quot;svg&quot;<br>          ],<br>          &quot;name&quot;: &quot;static/media/[name].[hash:8].[ext]&quot;<br>        }<br>      ]<br></strong>    ],<br>  ...<br>}</pre><p>Everything should work now.</p><pre># client/</pre><pre>&gt; my-app--client@0.1.0 build /my-app/client<br>&gt; react-scripts build &amp;&amp; npm run lib</pre><pre>Creating an optimized production build...<br>Compiled successfully.</pre><pre>...</pre><pre>&gt; my-app--client@0.1.0 lib /my-app/client<br>&gt; rm -rf lib/ &amp;&amp; NODE_ENV=production babel src/ -d lib/ &amp;&amp; npm run lib:esm</pre><pre>Successfully compiled 4 files with Babel.</pre><pre>&gt; my-app--client@0.1.0 lib:esm /my-app/client<br>&gt; find lib/ -type f -name *.js -exec sed -i&#39;&#39; -e &#39;s|<a href="http://twitter.com/babel/runtime">@babel/runtime</a>/helpers/esm|<a href="http://twitter.com/babel/runtime">@babel/runtime</a>/helpers|g&#39; {} +</pre><pre># server/</pre><pre>npm start</pre><pre>&gt; my-app--server@0.0.0 start /home/shirsh.zibbu/my-app/server<br>&gt; npm run lib &amp;&amp; node ./bin/www</pre><pre>&gt; my-app--server@0.0.0 lib /home/shirsh.zibbu/my-app/server<br>&gt; rm -rf lib/ &amp;&amp; babel src/ -d lib/</pre><pre>Successfully compiled 5 files with Babel.</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*opAI5E4PF8MaxpKh2_z7BQ.png" /></figure><h3>The End</h3><p>All we did was fill the blanks that we left. You can get the code <a href="https://github.com/zhirzh/cra-with-ssr/tree/1b8703a75910cb56beddb3fe2c82cf398f34273f">here on github</a>. Next up is data management with redux.</p><p><em>PS: Although I dropped BPWL, it might work for you. You can find that code </em><a href="https://github.com/zhirzh/cra-with-ssr-old/tree/BPWL"><em>here</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ff5f644e9d24" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Making CRA apps work with SSR — Part 1]]></title>
            <link>https://zhirzh.medium.com/making-cra-apps-work-with-ssr-part-1-1e23d6b1603d?source=rss-11f14fe74017------2</link>
            <guid isPermaLink="false">https://medium.com/p/1e23d6b1603d</guid>
            <category><![CDATA[server-side-rendering]]></category>
            <category><![CDATA[express]]></category>
            <category><![CDATA[react]]></category>
            <dc:creator><![CDATA[Shirsh Zibbu]]></dc:creator>
            <pubDate>Mon, 22 Oct 2018 12:16:04 GMT</pubDate>
            <atom:updated>2018-10-23T10:32:47.801Z</atom:updated>
            <content:encoded><![CDATA[<h3>Making CRA apps work with SSR — Part 1</h3><h4>Just plain old <em>React</em></h4><blockquote>This article is now part of a much longer series of posts titled <a href="https://hackernoon.com/making-cra-apps-work-with-ssr-b45f7c23d8db">Making CRA apps work with SSR</a>. You can find the the code <a href="https://github.com/zhirzh/cra-with-ssr">here on github</a>.</blockquote><p>In the React ecosystem, <a href="https://github.com/facebookincubator/create-react-app/"><em>create-react-app</em></a> is a well-known project. It’s a super useful tool that provides a zero-configuration starting point for a React app, packaged with <a href="https://github.com/facebookincubator/create-react-app/blob/master/packages/react-scripts/template/README.md#table-of-contents">a lot of good stuff</a>.</p><p>SSR is not one of them.</p><p>At first, implementing SSR seems rather simple. But things get complicated in the process faster than I thought. And most of the existing solutions (that I came across) are <em>inadequate</em>.</p><h3>Inadequate Implementations</h3><h4>1. Static Serving</h4><p>People out there who mislabel static serving as SSR are abundant. You may come across solutions that use a server to respond with the static build files. Sometimes those generated by <a href="https://github.com/facebookincubator/create-react-app/blob/dc95d18c9ccbf69ccc2e85b11de638f6462d7181/README.md#npm-run-build-or-yarn-build">react-scripts/build</a>.</p><pre>const app = express();</pre><pre>app.get(&#39;/&#39;, (req, res) =&gt; {<br>  res.sendFile(&#39;/some/path/index.html&#39;);<br>});</pre><p>This is not SSR. Simply serving the HTML file is not SSR.</p><h4>2. babel-register</h4><p>There are many other solutions that use <a href="https://babeljs.io/docs/usage/babel-register/"><em>babel-register</em></a>, which is not good.</p><blockquote>babel-register is apparently a bad idea for production, but, for the most part its fine …<br> — <a href="https://hackernoon.com/server-side-rendering-with-create-react-app-1faf5a9d1eff">Ben Lu</a></blockquote><p>While it does make our lives easier (as you will see), it is advisable to not use in production mode. Below I list some of the projects that I found that use <em>babel-register</em>.</p><ol><li><a href="https://github.com/cereallarceny/cra-ssr">cra-ssr</a></li><li><a href="https://github.com/agungsb/create-react-app-ssr-pwa">create-react-app-ssr-pwa</a></li><li><a href="https://github.com/kirill-konshin/create-react-server">create-react-server</a></li><li><a href="https://github.com/ayroblu/ssr-create-react-app">ssr-create-react-app</a></li></ol><h4>3. Server Side Templating</h4><p>This is yet another approach that I only ever saw in <a href="https://stackoverflow.com/a/38129612">this SO answer</a>. SST takes the middle ground between Static Serving and SSR.</p><p>Instead of serving files <em>as is</em>, modify the contents on the server, so embedding the data required for initial render.</p><h3>A wholesome approach</h3><p>Here’s my approach on coming up with a solution for CRA+SSR. The process is a bit long, but it’s a one time investment that pays well in the long run.</p><h4>Workbench</h4><p>Let’s setup our workbench first. We’ll create a project my-app which has a client and a server part. The client part is a CRA app my-app-client and the server is a basic <a href="https://expressjs.com/"><em>express</em></a> app.</p><pre>npm i -g create-react-app express-generator</pre><pre>mkdir my-app<br>cd my-app</pre><pre># create CRA app &quot;my-app--client&quot; in folder client/<br>create-react-app my-app--client --use-npm<br>mv my-app--client client</pre><pre># test client<br>cd client<br>PORT=3000 npm start</pre><pre># create express app &quot;my-app--server&quot; in folder server/<br>express --git my-app--server<br>mv my-app--server server</pre><pre># test server<br>cd server<br>npm i<br>PORT=8000 npm start</pre><p>We will connect our client’s build directory to our server app. Create a file server/paths.js to store the paths used in our server code. In server/app.js, connect both the BUILD_DIR and PUBLIC_DIR as static folders.</p><pre><strong>&gt;&gt;&gt; server/paths.js</strong></pre><pre>var path = require(&#39;path&#39;);</pre><pre>var BUILD_DIR = path.join(__dirname, &#39;..&#39;, &#39;client&#39;, &#39;build&#39;);<br>var PUBLIC_DIR = path.join(__dirname, &#39;public&#39;);</pre><pre>module.exports = {<br>  BUILD_DIR,<br>  PUBLIC_DIR,<br>};</pre><pre>&gt;&gt;&gt; server/app.js</pre><pre>var createError = require(&#39;http-errors&#39;);<br>var express = require(&#39;express&#39;);<br>var path = require(&#39;path&#39;);<br>var cookieParser = require(&#39;cookie-parser&#39;);<br>var logger = require(&#39;morgan&#39;);<br><strong>var { BUILD_DIR, PUBLIC_DIR } = require(&#39;./paths&#39;);</strong></pre><pre>...</pre><pre>app.use(logger(&#39;dev&#39;));<br>app.use(express.json());<br>app.use(express.urlencoded({ extended: false }));<br>app.use(cookieParser());<br><strong>app.use(express.static(BUILD_DIR));<br></strong>app.use(express.static(<strong>PUBLIC_DIR</strong>));</pre><p>By doing this, our express app will look for index.html first in the build folder of our client part and if it finds one, it will serve it. We can now build our react app and it will show up in the browser when we visit <a href="http://localhost:3000/">http://localhost:3000</a>.</p><p><strong><em>Note</em></strong><em>: We have just implemented </em><a href="#f302"><em>Static Serving</em></a><em>.</em></p><pre># client/<br>npm run build</pre><pre># server/<br>npm start</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*p_uTeMgsmnfzUm2mjk7sSw.png" /></figure><h4>Render React on Server</h4><p>The next step is to wire our server app to first render the react app and then serve it. This will take some time since there are a number of steps involved.</p><p>First off, we have to add a <em>render hook in</em> our html template for the server to render the app. Since our server code is not run inside a browser, it cannot find a render target using document.getElementById(&#39;root&#39;).</p><pre>&gt;&gt;&gt; client/public/index.html<strong><br></strong>...</pre><pre>&lt;body&gt;<br>  &lt;noscript&gt;<br>    You need to enable JavaScript to run this app.<br>  &lt;/noscript&gt;<br>  &lt;div id=&quot;root&quot;&gt;<strong>__ROOT__</strong>&lt;/div&gt;</pre><p>Then we move on to the server part. Create a new file react-renderer.js that will handle the app render and add it in app.js.</p><pre><strong>&gt;&gt;&gt; server/react-renderer.js</strong></pre><pre>var fs = require(&#39;fs&#39;);<br>var path = require(&#39;path&#39;);</pre><pre>var React = require(&#39;react&#39;);<br>var { renderToString } = require(&#39;react-dom/server&#39;);</pre><pre>var { BUILD_DIR } = require(&#39;./paths&#39;);<br>var App = require(&#39;../client/src/App&#39;);</pre><pre>function reactRenderer(req, res) {<br>  var app = renderToString(React.createElement(App));</pre><pre>  var html = fs<br>    .readFileSync(path.join(BUILD_DIR, &#39;index.html&#39;), &#39;utf8&#39;)<br>    .replace(&#39;__ROOT__&#39;, app);</pre><pre>  return res.send(html);<br>}</pre><pre>module.exports = reactRenderer;</pre><p>We add this react-renderer function as the main route handler before we add any static directory. This ensures that our response is the rendered react app and not the static file that we built earlier.</p><pre>&gt;&gt;&gt; server/app.js</pre><pre>var { BUILD_DIR, PUBLIC_DIR } = require(&#39;./paths&#39;);<br><strong>var reactRenderer = require(&#39;./react-renderer&#39;);</strong></pre><pre>...</pre><pre>app.use(logger(&#39;dev&#39;));<br>app.use(express.json());<br>app.use(express.urlencoded({ extended: false }));<br>app.use(cookieParser());</pre><pre><strong>app.get(&#39;/&#39;, reactRenderer);</strong></pre><pre>app.use(express.static(BUILD_DIR));<br>app.use(express.static(PUBLIC_DIR));</pre><p>Since we are now using react in our server code, we need to install it as well.</p><pre>npm i react react-dom</pre><p>In theory, this should work; in practice, it doesn’t. When we start the server, we are greeted with this error message.</p><pre><strong>npm start</strong></pre><pre>&gt; my-app--server@0.0.0 start /my-app/server<br>&gt; node ./bin/www</pre><pre>/my-app/client/src/App.js:1<br>(function (exports, require, module, __filename, __dirname) <br>{ <strong>import</strong> React, { Component } from &#39;react&#39;;<br>  <strong>^^^^^^</strong></pre><pre>SyntaxError: Unexpected token import</pre><p>We <strong>cannot</strong> mix code written in ES6 and <a href="https://en.wikipedia.org/wiki/CommonJS">CJS</a> standards. This means we need to convert our code in client/ to CJS standard.</p><p>If we use babel-register to run our cross-standard code (which we won’t), we would’ve implemented the <a href="#ccf1"><em>babel-register</em></a> approach. Instead, we are going to convert our entire codebase — client and server — to CJS.</p><h4>Migrating server code</h4><p>First we’ll deal with the server code. It’s should be no surprise that we need <a href="https://babeljs.io/">babel</a> to transform our code. And for that, we need to move our code …</p><pre>mkdir src/</pre><pre>mv routes src/<br>mv views src/<br>mv app.js src/<br>mv paths.js src/<br>mv react-renderer.js src/</pre><p>… install required babel packages…</p><pre>npm i\<br>  @babel/core\<br>  @babel/cli\<br>  @babel/preset-env\<br>  @babel/preset-react</pre><p>… add babel config …</p><pre>&gt;&gt;&gt; server/package.json</pre><pre>{<br>  ...</pre><pre>  &quot;scripts&quot;: {<br>    <strong>&quot;lib&quot;: &quot;rm -rf lib/ &amp;&amp; babel src/ -d lib/&quot;,</strong><br>    &quot;start&quot;: &quot;<strong>npm run lib &amp;&amp; </strong>node ./bin/www&quot;<br>  }</pre><pre>  ...</pre><pre><strong>  &quot;babel&quot;: {<br>    &quot;presets&quot;: [<br>      &quot;@babel/env&quot;,<br>      &quot;@babel/react&quot;<br>    ]<br>  }<br></strong>}</pre><p>… and make import path modifications in some files.</p><pre>&gt;&gt;&gt; server/bin/www</pre><pre>var app = require(<strong>&#39;../lib/app&#39;</strong>);</pre><pre><br>&gt;&gt;&gt; server/src/paths.js</pre><pre>var BUILD_DIR = path.join(__dirname, <strong>&#39;..&#39;, </strong>&#39;..&#39;, &#39;client&#39;, &#39;build&#39;);<br>var PUBLIC_DIR = path.join(__dirname, <strong>&#39;..&#39;, </strong>&#39;public&#39;);</pre><pre><br>&gt;&gt;&gt; server/src/react-renderer.js</pre><pre>var App = require(<strong>&#39;../../client/src/App&#39;</strong>);</pre><h4>Migrating client code</h4><p>Just as with server migration, we will use babel to transform our code.</p><p>In addition to that, we must also transform the imports separately. This is because the babel preset babel-preset-react-app disables module transform (<a href="https://github.com/facebook/create-react-app/blob/50607682ef1c5e28c158a613051ddafb30567b72/packages/babel-preset-react-app/dependencies.js#L78">see here</a>). As a result, the code retains its import/export statements even after undergoing other babel transformations.</p><p>One more thing. Babel adds a number of “helper” packages into the code that it needs during runtime. For reasons unknown to me, babel is adding ES6 versions of those &amp; not CJ version. The only way I fix it is by recursively running regex replacements on the transformed code.</p><p>First, install required babel packages…</p><pre>npm i @babel/cli @babel/plugin-transform-modules-commonjs</pre><p>… add babel config and npm script …</p><pre>&gt;&gt;&gt; client/package.json</pre><pre>{<br>  ...<br>  &quot;scripts&quot;: {<br>    &quot;start&quot;: &quot;react-scripts start&quot;,<br>    &quot;build&quot;: &quot;react-scripts build<strong> &amp;&amp; npm run lib</strong>&quot;,</pre><pre><strong>    &quot;lib&quot;: &quot;rm -rf lib/ &amp;&amp; NODE_ENV=production babel src/ -d lib/ &amp;&amp; npm run lib:esm&quot;,</strong></pre><pre><strong>    &quot;lib:esm&quot;: &quot;find lib/ -type f -name *.js -exec sed -i&#39;&#39; -e &#39;s|</strong><a href="http://twitter.com/babel/runtime"><strong>@babel/runtime</strong></a><strong>/helpers/esm|</strong><a href="http://twitter.com/babel/runtime"><strong>@babel/runtime</strong></a><strong>/helpers|g&#39; {} +&quot;,<br></strong>    &quot;test&quot;: &quot;react-scripts test&quot;,<br>    &quot;eject&quot;: &quot;react-scripts eject&quot;<br>  },<br>  ...<br><strong>  &quot;babel&quot;: {<br>    &quot;plugins&quot;: [<br>      &quot;@babel/plugin-transform-modules-commonjs&quot;<br>    ],<br>    &quot;presets&quot;: [<br>      &quot;react-app&quot;<br>    ]<br>  }</strong><br>}</pre><p>… and make import path modifications in some files.</p><pre>&gt;&gt;&gt; server/src/react-renderer.js</pre><pre>...</pre><pre><strong>var App = require(&#39;../../client/lib/App&#39;).default;</strong></pre><pre>function reactRenderer(req, res) {<br>  var app = renderToString(<strong>&lt;App /&gt;</strong>);</pre><pre>  ...<br>}</pre><pre>module.exports = reactRenderer;</pre><h3>Wrapping up</h3><p>Yet again, our setup is, in theory, complete. We can build our client code …</p><pre># client/</pre><pre>npm run build</pre><pre>&gt; my-app--client@0.1.0 build /my-app/client<br>&gt; react-scripts build &amp;&amp; npm run lib</pre><pre>Creating an optimized production build...<br>Compiled successfully.</pre><pre>...</pre><pre>&gt; my-app--client@0.1.0 lib /my-app/client<br>&gt; rm -rf lib/ &amp;&amp; NODE_ENV=production babel src/ -d lib/ &amp;&amp; npm run lib:esm</pre><pre>Successfully compiled 4 files with Babel.</pre><pre>&gt; my-app--client@0.1.0 lib:esm /my-app/client<br>&gt; find lib/ -type f -name *.js -exec sed -i&#39;&#39; -e &#39;s|<a href="http://twitter.com/babel/runtime">@babel/runtime</a>/helpers/esm|<a href="http://twitter.com/babel/runtime">@babel/runtime</a>/helpers|g&#39; {} +</pre><p>… and our server code as well …</p><pre># server/</pre><pre>npm run lib</pre><pre>&gt; my-app--server@0.0.0 lib /my-app/server<br>&gt; rm -rf lib/ &amp;&amp; babel src/ -d lib/</pre><pre>Successfully compiled 5 files with Babel.</pre><p>… but starting our server still errors out. What gives?</p><pre>module.js:549<br>    throw err;<br>    ^</pre><pre>Error: Cannot find module &#39;./logo.svg&#39;</pre><p>Turns out that simple babel transformations require different setup for different types of imports. There are a few ways that I can think of to solve this issue. But this post has been going on for a while, so I will commenting out the pesky bits.</p><pre>&gt;&gt;&gt; client/src/App.js</pre><pre>import React, { Component } from &#39;react&#39;;<br><strong>// import logo from &#39;./logo.svg&#39;;<em><br></em>// import &#39;./App.css&#39;;</strong></pre><pre>class App extends Component {<br>  render() {<br>    return (<br>      &lt;div className=&quot;App&quot;&gt;<br>        &lt;header className=&quot;App-header&quot;&gt;<br><strong>          {/*&lt;img src={logo} className=&quot;App-logo&quot; alt=&quot;logo&quot; /&gt;*/}</strong><br>          &lt;p&gt;<br>            Edit &lt;code&gt;src/App.js&lt;/code&gt; and save to reload.<br>          &lt;/p&gt;<br>          &lt;a<br>            className=&quot;App-link&quot;<br>            href=&quot;https://reactjs.org&quot;<br>            target=&quot;_blank&quot;<br>            rel=&quot;noopener noreferrer&quot;<br>          &gt;<br>            Learn React<br>          &lt;/a&gt;<br>        &lt;/header&gt;<br>      &lt;/div&gt;<br>    );<br>  }<br>}</pre><pre>export default App;</pre><p>Let’s try it again.</p><pre># client/</pre><pre>npm run build<br>...</pre><pre># server/</pre><pre>npm start<br>...</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*t_pzgXcmLNlEs2Z9I-xosA.png" /></figure><h3>The End</h3><p>So, this is how you do CRA+SSR. Although the end result is pretty <em>lackluster</em>, this is just the beginning of longer process. In time, we will add extra packages for routing, data management and other stuff. You can find the code for this project <a href="https://github.com/zhirzh/cra-with-ssr">here on github</a>.</p><p><em>PS: I patched the asset imports. You can read about it in </em><a href="https://medium.com/@zhirzh/making-cra-apps-work-with-ssr-part-1-5-7b5a04e5415c"><em>part 1.5</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1e23d6b1603d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Calculating browser support for the web]]></title>
            <link>https://medium.com/hackernoon/calculating-browser-support-for-the-web-d7393934e3a5?source=rss-11f14fe74017------2</link>
            <guid isPermaLink="false">https://medium.com/p/d7393934e3a5</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[development]]></category>
            <dc:creator><![CDATA[Shirsh Zibbu]]></dc:creator>
            <pubDate>Tue, 03 Apr 2018 19:11:52 GMT</pubDate>
            <atom:updated>2019-04-26T11:52:56.919Z</atom:updated>
            <content:encoded><![CDATA[<p>As time moves forward, the web evolves, and brings new APIs with it. When working on a <em>product</em>, including one or two bleeding-edge APIs might throw some red flags in the user’s browser.</p><p>There are some preventive measures we, the developers, can take to ensure that our product doesn’t falter but it’s better said than done.</p><h3>Preventive Measures</h3><h4>Disclaimer</h4><p>Adding a disclaimer notice to warn the user about the product’s possible unstable or undefined behaviour on some platforms should be the first line of defense.</p><p>Most hacks, and even some polyfills, for some older / incompatible browsers cannot guarantee identical behaviour to native APIs. It is a good practice to inform the user of such possibilities.</p><h4>Can I Use</h4><p>If you ever wanted to use an emerging technology but weren’t sure if user’s machines support it then you should know about <a href="https://github.com/Fyrd/caniuse">caniuse</a>.</p><blockquote>“Can I use” provides up-to-date browser support tables for support of front-end web technologies on desktop and mobile web browsers.</blockquote><p>If this is something new to you, be sure to visit <a href="https://caniuse.com/">caniuse.com</a> the next time you work with modern web APIs to compare.</p><h4>Patching the Build Process</h4><p>This babel preset <a href="https://babeljs.io/docs/plugins/preset-env">babel-preset-env</a> automatically determines the Babel plugins you need based on the browsers you want support for. It does so by comparing the versions you want to support with a <a href="https://github.com/babel/babel-preset-env/blob/master/data/plugins.json">plugins list</a> and only pulls in polyfills if necessary.</p><p>I am fairly certain there may be some equivalent for other build pipelines that I don’t know of. If you know some, list them out in the comments.</p><h3>The missing piece</h3><p>When using babel preset, the <a href="https://hackernoon.com/tagged/developer">developer</a> must consciously provide the browser versions. This is a burden on the developer’s end and it’s relatively easy to miss out on a <a href="https://hackernoon.com/tagged/browser">browser</a> or include the wrong versions.</p><p>On the other hand, “can i use” only shows one feature at a time. It is rather difficult to decide on the common versions if you have more than a few bottleneck technologies.</p><p>Here’s something to try. Can you tell minimum versions of each browser that support <a href="https://www.caniuse.com/#feat=serviceworkers">service workers</a> and <a href="https://www.caniuse.com/#feat=css-display-contents">CSS display contents</a>?</p><h3>🗲 browser-support 🗲</h3><p>I made a simple website to address this issue, that I ever so smartly named “browser-support” (<a href="https://zhirzh.github.io/browser-support/build">website</a>, <a href="https://github.com/zhirzh/browser-support">source</a>).</p><p>This is pretty much the same as “can i use” with some extra features. You can load up multiple technologies and share the “checklist” via URL. Once you have the versions, you can just plug them in your build pipeline or put up a relevant notice at the top of the website, should that become necessary.</p><p><a href="https://zhirzh.github.io/browser-support/build">Browser Support</a></p><p><strong>PS</strong>: If you’re wondering about the exercise at the end of the previous section, you can have the answer <a href="https://zhirzh.github.io/browser-support/build/?checklist=serviceworkers,css-display-contents">here</a>.</p><h3>The End</h3><p>That’s it for today — just wanted to share something I made the other day that might save a developer some time.</p><p>In case someone missed it:</p><ul><li>Source code: <a href="https://github.com/zhirzh/browser-support">zhirzh/browser-support</a></li><li>Website: <a href="https://zhirzh.github.io/browser-support/build/?checklist=serviceworkers,css-display-contents">browser-support/</a></li><li>Demo: <a href="https://zhirzh.github.io/browser-support/build/?checklist=serviceworkers,css-display-contents">browser-support?checklist=serviceworkers,css-display-contents</a></li></ul><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fupscri.be%2Fdde502%3Fas_embed%3Dtrue&amp;dntp=1&amp;url=https%3A%2F%2Fupscri.be%2Fhackernoon%2F&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=upscri" width="800" height="400" frameborder="0" scrolling="no"><a href="https://medium.com/media/3c851dac986ab6dbb2d1aaa91205a8eb/href">https://medium.com/media/3c851dac986ab6dbb2d1aaa91205a8eb/href</a></iframe><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d7393934e3a5" width="1" height="1" alt=""><hr><p><a href="https://medium.com/hackernoon/calculating-browser-support-for-the-web-d7393934e3a5">Calculating browser support for the web</a> was originally published in <a href="https://medium.com/hackernoon">HackerNoon.com</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Negative Indexing Multi Arrays in C/++]]></title>
            <link>https://medium.com/hackernoon/negative-indexing-multi-arrays-in-c-b551ce252972?source=rss-11f14fe74017------2</link>
            <guid isPermaLink="false">https://medium.com/p/b551ce252972</guid>
            <category><![CDATA[arrays]]></category>
            <category><![CDATA[c-programming]]></category>
            <category><![CDATA[tips-and-tricks]]></category>
            <dc:creator><![CDATA[Shirsh Zibbu]]></dc:creator>
            <pubDate>Tue, 27 Mar 2018 09:14:44 GMT</pubDate>
            <atom:updated>2019-04-26T11:52:58.076Z</atom:updated>
            <content:encoded><![CDATA[<h4>A convenient untruth — Multi Arrays in C/++</h4><p><em>Inspired by </em><a href="https://blog.feabhas.com/2016/12/a-convenient-untruth/"><em>“A convenient untruth” by Glennan Carnie</em></a><em>.</em></p><p>When declaring a multi array (multi-dimensional array) in C/++, we end up with is a contiguous chunk of memory. This memory block spans over the size of the product of all the dimensions.</p><p>For a 2x3 array arr[2][3],we get a memory block of 6 units. I say units instead of the actual size (in bytes) because the size will be different depending on the data type of the array and the machine architecture.</p><p>When we query the array (i.e. access elements), we are performing pointer arithmetic to extract the value from a single 6 unit memory block.</p><pre>int arr[2][3] = {11,22,33,44,55,66};<br>cout &lt;&lt; arr[1][1]; // 55</pre><pre><br>int *ptr = &amp;arr[0][0];<br>cout &lt;&lt; *(ptr + 1*3 + 1*1); // 55</pre><pre><br>data      11  22  33  44  55  66<br>address  100 104 108 112 116 120<br>           ↑               ↑<br>         ptr            ptr+4</pre><p>This made me wonder — can I travel backwards?</p><h3>Negative Indexing</h3><p>Now here’s the fun part. In the 2x3 integer array given above, how can we query the number 33? The obvious answer would be arr[0][2]. And that’s correct.</p><p>In pointers, it becomes *(ptr + 0*3 + 2*1) which is just *(ptr + 2). So the next question is: in how many ways can we make x * 3 + y * 1equal to 2? In other words, for what values of x, y will the equality 3x + y == 2 hold?</p><p>Here’s a sample of solutions:</p><pre>x  0  1  2 -1 -2 ...<br>y  1 -1 -4  5  8 ...</pre><p>And we can use any of these (x, y) pairs to query the number 33:</p><pre>int arr[2][3] = {11,22,33,44,55,66};</pre><pre>cout &lt;&lt; arr[0][2];  // 33<br>cout &lt;&lt; arr[1][-1]; // 33<br>cout &lt;&lt; arr[2][-4]; // 33<br>cout &lt;&lt; arr[-1][5]; // 33<br>cout &lt;&lt; arr[-2][8]; // 33</pre><pre><br>data      11  22  33  44  55  66<br>address  100 104 108 112 116 120<br>           ↑       ↑<br>          ptr    ptr+2</pre><p>This behavior is true for all multi <a href="https://hackernoon.com/tagged/arrays">arrays</a> of n dimensions. The only problem is that it becomes rather cumbersome to visualize this principle in 3D and above arrays. Fortunately, I made a tiny utility that does the job for you :)</p><p>This tool helps create a multi array up to 5D array and each “level” can hold up to 4 “cells”. After generating an array, you can run a query on it and the tool will highlight the memory cells used to arrive at the <a href="https://hackernoon.com/tagged/output">output</a> value.</p><p><strong><em>Note:</em></strong> What I mean by the words “levels” and “cells” is explained later on.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fcodepen.io%2Fzhirzh%2Fembed%2Fpreview%2FyKPNjo%3Fheight%3D600%26slug-hash%3DyKPNjo%26default-tabs%3Djs%2Cresult%26host%3Dhttps%3A%2F%2Fcodepen.io%26embed-version%3D2&amp;url=https%3A%2F%2Fcodepen.io%2Fzhirzh%2Ffull%2FyKPNjo%2F&amp;image=https%3A%2F%2Fs3-us-west-2.amazonaws.com%2Fm.cdpn.io%2Fscreenshot-coming-soon-small.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=codepen" width="800" height="600" frameborder="0" scrolling="no"><a href="https://medium.com/media/5c48d88ea91685c3717d116b886dd63c/href">https://medium.com/media/5c48d88ea91685c3717d116b886dd63c/href</a></iframe><h3>Show and Tell</h3><p>To explain things better, I will use the following memory map of a 2x3x2 array. Have a look at it and convince yourself of the following equality arr[0][2][0] == arr[0][0][4] == arr[1][0][-2]</p><pre> _____________________________________________________________<br>|        | L0 |           0           |          1            |<br>|        |----|-----------------------------------------------|<br>| Memory | L1 |   0   |   1   |   2   |   0   |   1   |   2   |<br>| Levels |----|-----------------------------------------------|<br>|        | L2 | 0 | 1 | 0 | 1 | 0 | 1 | 0 | 1 | 0 | 1 | 0 | 1 |<br>|=============|===============================================|<br>|  Data Level | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10| 11| 12|<br> ‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾</pre><p>Also, I am using functions PROD() and SUM() that give the product and sum of an array range.</p><pre>prod(i, [a..b], arr) = arr_a * arr_(a+1) * ... * arr_(b-1)<br>prod(arr) = arr_0 * arr_1 * ... * arr_(n-1)</pre><pre>sum(i, [a..b], arr) = arr_a + arr_(a+1) + ... + arr_(b-1)<br>sum(arr) = arr_0 + arr_1 + ... + arr_(n-1)</pre><pre>where n = size of array</pre><h4>Cells and Levels</h4><p>Both these terms are made up. These are just notations I use to refer to a specific memory location.</p><p>A <strong>Memory Cell</strong> is just a memory location that can be pointed to by a pointer or array index. When we access element arr[0][2][1], we end up with the data value 6.</p><p>But what does [0][2][1] represent? I answer this by saying that they are pointers to “memory cells”. One way to read it is:</p><pre>* access 0th cell in the block<br>* access 2nd cell in the 0th cell<br>* access 1st cell in the 2nd cell<br>* retrieve the value</pre><p>A <strong>Memory Level</strong> is a collection of memory cells that reside in the same memory dimension.</p><h4>Observations</h4><p>The first observations are the more obvious ones:</p><ul><li>Dimension Count: <strong>N</strong> = 3</li><li>Dimension Sizes: <strong>D</strong> = [2, 3, 2]</li></ul><p>If we access arr[1][2][1] then Query will be: <strong>Q</strong> = [1, 2, 1]</p><h4>Cell Stride (S)</h4><p>Standing at the ith memory level, if I move by 1 cell, the size of jump in the data level is the <strong>Cell Stride</strong> for that memory level.</p><p>Cell strides at levels are:</p><ul><li>L0: 6 = 1*2*3</li><li>L1: 2 = 1*2</li><li>L2: 1 = 1</li></ul><p>This gives us the relation that for the ith memory level, the stride length is product of all dimension sizes above that level.</p><pre>S_i = 1 * prod(j, [i+1..N], D)<br>or<br>S_i = S_(i+1) * D_(i+1)</pre><h4>Query Match (M)</h4><p>When we run a query, we match a memory cell at each level. This forms a chain of jumps <strong>across the levels</strong>, ending in the data level and results in a data value.</p><p>This gives us the relation that for the ith memory level, the matching cell is:</p><pre>M_i = (1 / S_i) * sum(j, [1..N], S_j * Q_j)<br>or simply<br>M_i = (1 / S_i) * sum(S_j * Q_j)</pre><p>Unfortunately, my journey to this relation is pretty unwieldy to explain. So I’ll just skip it.</p><p>It is this value — the query match — that I use to highlight the memory cells and the final data value that result from the query.</p><h4>Misc</h4><p><strong>Cell Count</strong>: The number of cells in the ith memory level<br><strong>C_i</strong> = prod(j, [0..i], D) = C_(i-1) * D_i</p><p><strong>Data Count</strong>: The total number of data values stored<br><strong>n</strong> = prod(i, [0..N], D) = prod(D)</p><p>By comparing relations C_i, S_i and n, get the relation n = C_i * S_i because:</p><ul><li>n = prod(i, [0..N], D)</li><li>C_i = prod(j, [0..i], D)</li><li>S_i = prod(j, [i+1..N], D)</li></ul><h3>The End</h3><p>C/++ allows negative indexes in multi arrays since it is just a contiguous chunk of memory and index lookups is just pointer arithmetic on it.<br>There. That’s a thing you now know.</p><p>You can find the code <a href="https://gist.github.com/zhirzh/aa02be34407eebe8998d2ff35946cdc9">here</a> or on <a href="https://codepen.io/zhirzh/pen/yKPNjo">codepen</a>.</p><p>Also, if you’re wondering whether it would be possible in some other language, that answer is “it depends”. Languages that implement multi arrays as true multi arrays — arrays of arrays — cannot have negative indexes. Languages that implement multi arrays like C/++ does <em>might</em> support it.</p><h3>Bonus</h3><p>Say we have an integer array arr[3] and we access the element arr[1], what do we get? Well, we get the 2nd value. That’s not interesting.</p><p>What <em>is</em> interesting is how the compiler works this out by re-writing the query as *(arr + 1). This is simple pointer addition. And since addition is commutative, we can do …</p><pre>arr[1]     -&gt; *(arr + 1)<br>*(arr + 1) -&gt; *(1 + arr)<br>*(1 + arr) -&gt; 1[arr]</pre><p>… and conclude that arr[i] is the same as i[arr]. This bit is also true for multi arrays.</p><pre>int main () {<br>  int arr[2][3] = {11,22,33,44,55,66};</pre><pre>cout&lt;&lt;arr[0][2]; // good<br>  cout&lt;&lt;2[0[arr]]; // bad<br>  cout&lt;&lt;2[arr[0]]; // also bad<br>  cout&lt;&lt;0[arr][2]; // ???<br>}</pre><p>There’s a whole lot more where that came from. Checkout the article<br><a href="https://blog.feabhas.com/2016/12/a-convenient-untruth/">“A convenient untruth” by Glennan Carnie</a>.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fupscri.be%2Fdde502%3Fas_embed%3Dtrue&amp;dntp=1&amp;url=https%3A%2F%2Fupscri.be%2Fhackernoon%2F&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=upscri" width="800" height="400" frameborder="0" scrolling="no"><a href="https://medium.com/media/3c851dac986ab6dbb2d1aaa91205a8eb/href">https://medium.com/media/3c851dac986ab6dbb2d1aaa91205a8eb/href</a></iframe><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b551ce252972" width="1" height="1" alt=""><hr><p><a href="https://medium.com/hackernoon/negative-indexing-multi-arrays-in-c-b551ce252972">Negative Indexing Multi Arrays in C/++</a> was originally published in <a href="https://medium.com/hackernoon">HackerNoon.com</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>