<?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 Abhishek Raj on Medium]]></title>
        <description><![CDATA[Stories by Abhishek Raj on Medium]]></description>
        <link>https://medium.com/@abhishekraj_14802?source=rss-b85e7e75917b------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*4vdbnw3WPAOy0WiodnU7iw@2x.jpeg</url>
            <title>Stories by Abhishek Raj on Medium</title>
            <link>https://medium.com/@abhishekraj_14802?source=rss-b85e7e75917b------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 29 Nov 2026 17:58:25 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@abhishekraj_14802/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[Birthday Problem(Paradox):]]></title>
            <link>https://medium.com/@abhishekraj_14802/birthday-problem-paradox-60157f76076c?source=rss-b85e7e75917b------2</link>
            <guid isPermaLink="false">https://medium.com/p/60157f76076c</guid>
            <category><![CDATA[birthday-paradox]]></category>
            <category><![CDATA[probability]]></category>
            <category><![CDATA[birthdayproblem]]></category>
            <dc:creator><![CDATA[Abhishek Raj]]></dc:creator>
            <pubDate>Mon, 22 Jun 2020 05:29:09 GMT</pubDate>
            <atom:updated>2020-07-07T01:46:17.973Z</atom:updated>
            <content:encoded><![CDATA[<p>Most of you may have heard about the birthday problem a.k.a birthday paradox at some point in time. The paradox stems from the fact that even though a person can be born in <strong>1</strong> out of <strong>365</strong> days (<em>ignoring leap year for simplicity</em>), with just a group of <strong>23</strong> people, there is approximately <strong>50%</strong> chance that there would be at least<strong> 2</strong> people sharing the same birthday. This is of course on assumptions that all days are equally likely for a person to be born, there are no twins, and so on. It is not as much a paradox as it is non-intuitive at a first glance. Let’s take a step back and start with the basics:</p><h4>Tl;dr</h4><p>In a group of 23 people, the number of ways you can form a pair of 2 people to check if at least one pair has the same birthday is 23 choose 2 a.k.a <strong>23C2</strong> = <strong>253</strong>. To give a perspective, this is much more than half the days in the year (~183). This can give us a good intuition that the chances of a match are indeed not as low as we would expect when we first saw the number 23. To see the probability calculations for a group of 23, head over to <a href="#d900">this</a> section (<em>The link only works in web browsers. If you are using the mobile app, head over to the </em><strong><em>Original Problem</em></strong><em> section</em>). For a longer explanation (<em>building from a group of 1 and onwards</em>), continue reading.</p><p>We define probability (<em>in the classical sense</em>) of an event E as follows:</p><blockquote><em>The ratio of number of outcomes favorable to the occurrence of E to the total number of possible outcomes (</em>sample space<em>)</em>.</blockquote><p><strong>Probability of a person’s birthday occurring in a given year (ignoring leap year):</strong></p><p>Sample space: <strong>365 (</strong><em>365 possible days</em><strong>)</strong></p><p>Number of occurrences favorable for a person’s birthday to occur: <strong>365 (</strong><em>The person could have been born in any of the 365 days</em><strong>)</strong></p><p>Hence, the probability of a person’s birthday occurring in a given year is <strong>365/365 or 1. </strong>There is 100% chance that your birthday will occur in a given year. We will see how this is useful as we add more people to the group.</p><h4>Collision (same birthday) probability</h4><p>The simplest case where there is a chance of a collision (same birthday) needs a group of 2 people. Let’s calculate the probability as follows:</p><p>Sample space for 2 persons: 3<strong>65 * 365 (</strong>each<strong> </strong>person has 365 days to be born from, independent of other’s birthdays)</p><p>Number of occurrences when a collision happens: <strong>365</strong> (The 2 people can share a birthday in any of the 365 days)</p><p>Hence, the Probability of sharing a birthday between 2 people = <strong>365/(365*365) = 1/365</strong> ~ <strong>0.0027</strong></p><p>Another way to calculate the above is using the probability of a single person’s birthday occurring in a year, which is <strong>1 </strong>AND multiplying with the probability of a match with the second person, which is <strong>1/365</strong>. The second person has exactly <strong>1</strong> choice out of <strong>365</strong>, to match with the first person’s birthday:</p><p><strong>1 * 1/365 = 1/365 (</strong><em>joint probability)</em></p><p>Now let’s try the same exercise with 3 people (A, B and C),</p><p>Sample space for 3 persons: <strong>365 * 365 * 365</strong> (each person has 365 days to be born from, independent of other’s birthdays)</p><p>Number of occurrences when a collision happens: This comes down to the following cases:</p><ol><li><strong>A and B can share the same birthday, but not C</strong></li><li><strong>A and C can share the same birthday, but not B</strong></li><li><strong>B and C can share the same birthday, but not A</strong></li><li><strong>A, B and C can all share the same birthday</strong></li></ol><p>Let’s calculate each of them:</p><p><strong>1. P(A and B can share the same birthday, but not C) = 365*364/(365*365*365) = 364/(365*365)</strong></p><blockquote>Explanation:</blockquote><blockquote><strong>Numerator</strong> — A and B can share their birthdays in any of the 365 days, AND C can have the birthday on all days except the day in which A and B are born (365 -1 = 364)</blockquote><blockquote><strong>Denominator</strong> — sample space for 3 persons, where each person has 365 days to choose from = 365 * 365 * 365.</blockquote><blockquote>Yet another way to think about this, is building on top of the group of 2 people scenario discussed above: probability of a collision between 2 people is <strong>1/365</strong> AND probability of the 3rd persons birthday to not collide with the first 2 is <strong>364/365</strong>. Multiplying both, we get the same result as above: <strong>364/(365*365)</strong></blockquote><p>The next 2 cases are same like the above:</p><p><strong>2. P(A and C can share the same birthday, but not B) = 365*364/(365*365*365) = 364/(365*365)</strong></p><p><strong>3. P(B and C can share the same birthday, but not A) = 365*364/(365*365*365) = 364/(365*365)</strong></p><p><strong>4. P(A, B and C can all share the same birthday) = 365/(365*365*365) = 1/(365*365)</strong></p><blockquote>Explanation: The 4th case is where all 3 persons share their birthdays, and they can share them in any of the 365 days. Denominator is same as the first 3 cases</blockquote><p>Let’s all add these up:</p><p>(364*3 + 1) / 365*365 = <strong>1093 / 365*365 = 0.0082</strong></p><p>An easier way to look at this problem, is to find the probability that A, B and C don’t share birthdays, and then subtract the value from 1, since the events of sharing a birthday and not sharing a birthday are complementary to each other.</p><p>1 - (365/365 * 364/365 * 363/365)</p><blockquote>Explanation: A has 365 choices, while B has 364 choices to not collide with A, and C has 363 choices to not collide with A or B. This simplifies to:</blockquote><p>1 - ((364 * 363) / (365 * 365))</p><p>= (365*365 - 364*363) / (365*365)</p><p>= 1093 / (365 * 365) ~ <strong>0.0082</strong></p><p>If you compare this result with that of the group of 2 people, we have increased by <strong>0.0055</strong>. Not a big jump so far. But, let’s take a closer look at the number of comparisons we need to make if we were to conduct an experiment to find at least a pair of birthday matches with different group sizes:</p><p>Group size of 1: <strong>0</strong> comparisons</p><p>Group size of 2: <strong>1</strong> comparison (A has to compare with B)</p><p>Group size of 3: <strong>3</strong> comparisons (A with B, A with C, and B with C)</p><p>Group size of 4: <strong>6</strong> comparisons (A with B,C,D, B with C and D, C with D)</p><p>We can generalize the above for a group of size ‘n’ as equal to n * (n-1)/2 comparisons (<em>For every person, we compare with every other one, and we divide by 2 to eliminate duplicate comparisons</em>)</p><blockquote>For a group of 23, when we plug the formula, we get <strong>23 *22/2</strong> = <strong>253</strong> comparisons. This is well over half the days in a year (365/2 ~ 183)</blockquote><h4>Original problem</h4><p>We can compute the probability of a birthday collision for a group of 23, by calculating the event when there is no match among all of them and subtracting the answer from 1:</p><p>P(at least one birthday collision between 23 people) = 1- P(no birthday collision between 23 people)</p><p>Let’s say there are 23 people named A to W in a line. Starting with A, and ending in W, let’s calculate the probability that none of their birthdays collide with each other:</p><p>A has 365 choices,</p><p>B has 365 - 1 choices (cannot collide with A)</p><p>C has 365 - 2 choices (cannot collide with A or B)</p><p>…</p><p>W has 365 - 22 choices (cannot collide with any of the 22 people who already chose their birthdays )</p><p>Multiplying all of their probabilities, we get:</p><p><strong>365/365 * 364/365 * … * 343/365</strong></p><p>= <strong>0.492703</strong></p><p>Subtracting it from 1, we get <strong>0.507297 (50.7297%)</strong></p><p>This can be generalized to a group of <strong>n</strong> as follows:</p><p><strong>1 — (365 * 364 * … * (365 - n+1)) / 365^n</strong></p><p>= 1 — <strong>365! / ((365 - n)! * 365^n)</strong></p><p>= 1 — <strong>365Pn/365^n</strong></p><p>I have created a sample website where you can play around with the parameters, run trails (<em>tested up to 100,000 trails, might not work consistently after this limit for rendering the graphs</em>) to verify if our intuition matches with the experiments. We can observe that as our number of trials increases, our probability gets closer to our theoretical value (~50% in the case of 23 people). This method of running independent random experiments under identical conditions for a large number of times, and computing the relative frequency (ratio of number of favorable outcomes to the total number of trials) is known as the <a href="https://en.m.wikipedia.org/wiki/Law_of_large_numbers">frequentist</a> interpretation of probability. The relative frequency represents our desired probability. This interpretation is based on the <a href="https://en.m.wikipedia.org/wiki/Law_of_large_numbers">law of large numbers</a>, which states that in performing a large number of trials, our relative frequency will get closer to the expected value.</p><p><a href="https://birthday-paradox-graph.firebaseapp.com/">Birthday paradox</a></p><h4>Looking back</h4><p>Why did our intuition not work at the first glance? Note that our mind can easily capture the edge cases:</p><ol><li>How many people do you need in a group, such that there can be <strong>no (0% chance) pair of birthdays which are the same</strong>?</li></ol><p><strong>Answer</strong>: 1 person. Since that’s the only case where there is no possibility of a pair</p><p>2. How many people do you need in a group, to <strong>always (100% chance) </strong>get <strong>at least one pair of birthdays the same</strong>?</p><p><strong>Answer</strong>: By (<a href="https://en.wikipedia.org/wiki/Pigeonhole_principle">pigeonhole principle</a>), we would need as many people as the total number of choices + 1 = 365 + 1 = <strong>366</strong> people. This way, in the worst case if the first 365 people have unique birthdays, the 366th person will need to share a birthday among 1 of the first 365 people.</p><p>Its just that our mind initially struggles to comprehend the in-between cases (<em>in this problem, 50%</em>): How many people do you need in a group, to get <strong>at least one pair of birthdays the same with a 50% chance</strong>?</p><p>If you read the question carefully, it doesn’t have the following constraint:</p><p><strong>No specific person/date given, to match with the group </strong>(<em>for e.g. Person A could be born in any of the 365 days. From the group of n persons, there should be at least one match with Person A. Using the complement formula, 1 — P(no match with Person A)</em></p><p><em>= 1 — ((364 /365)^n)</em></p><p>This means, <strong>ANY</strong> person’s birthday can match with <strong>ANY</strong> of the other persons’s birthdays, which gives rise to the large number of combinations we need to consider :)</p><p><strong>References</strong>: <a href="https://en.m.wikipedia.org/wiki/Birthday_problem">https://en.m.wikipedia.org/wiki/Birthday_problem</a></p><p>This post would not have been possible without the help of my aunt, Dr. Revathy Sundararajan</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=60157f76076c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Async/await = generator + promise]]></title>
            <link>https://medium.com/@abhishekraj_14802/async-await-generator-promise-6f6eda8be17?source=rss-b85e7e75917b------2</link>
            <guid isPermaLink="false">https://medium.com/p/6f6eda8be17</guid>
            <category><![CDATA[asyncawait]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[generator]]></category>
            <category><![CDATA[es6]]></category>
            <category><![CDATA[promises]]></category>
            <dc:creator><![CDATA[Abhishek Raj]]></dc:creator>
            <pubDate>Sat, 19 May 2018 17:51:42 GMT</pubDate>
            <atom:updated>2018-05-19T17:56:23.128Z</atom:updated>
            <content:encoded><![CDATA[<p>If you have read the documentation of <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function">async/await</a> in MDN, you would come across this ‘note’ at the end of the Description section:</p><blockquote>The purpose of async/await functions is to simplify the behavior of using promises synchronously and to perform some behavior on a group of Promises. Just as Promises are similar to structured callbacks, async/await is similar to combining generators and promises.</blockquote><p>Note the last part of the last sentence: ‘<strong><em>async</em>/</strong><strong><em>await</em> is similar to combining generators and promises.</strong>’</p><p>That’s exactly what async/await is under the hood!</p><p>They combine a generator, <em>that helps pause a function and execute synchronously</em>, and a promise, <em>that helps execute asynchronous code with the promise that it will return the result sometime in the future.</em></p><p>Let’s take a look at an example with promises.</p><h4>Promise</h4><p>You have 2 promises. You need to execute the second one after the first one completes. You might probably being doing this:</p><pre>const p1= Promise.resolve(5)<br>p1.then(val =&gt; {<br>    const p2= Promise.resolve(val*10)<br>    p2.then(val =&gt; console.log(val))   //output: 50</pre><p>If you wanted to make this code more flat, you would do this:</p><pre>const p1 = Promise.resolve(5)<br>const p2 = p1.then(val =&gt; Promise.resolve(val*10))<br>p2.then(val =&gt; console.log(val))   //output: 50</pre><p>What if you could do something like this(<em>Imagine p1 magically gets the resolved value for the first promise, and p2 gets the resolved value for the second promise</em>):</p><pre>const p1 = Promise.resolve(5)<br>const p2 = Promise.resolve(p1*10)<br>console.log(p2) //output: 50</pre><h4>Async/await</h4><p>This is where async/await comes into picture. If you mark the function as ‘<strong>async</strong>’ and add the ‘<strong>await</strong>’ keyword, p1 and p2 will always get the resolved values instead of the promises.</p><pre>const myAsync = async () =&gt; {<br>  const p1 = await Promise.resolve(5)<br>  const p2 = await Promise.resolve(p1*10)<br>  console.log(p2) //output: 50<br>}</pre><p>Before we dive into how this works, let’s look at a generator.</p><h4>Generator</h4><blockquote>A generator is essentially a lazy function which ‘generates’ values on ‘demand’ .</blockquote><p>In JavaScript, you can mark a function as a generator with a “<strong>*</strong>”. This gives the ability for the function to generate values through the ‘<strong>yield</strong>’ keyword. In order to receive a value, the requester should invoke the ‘<strong>next</strong>’ method, which is available from calling the generator function. The result of the next() function is an object with two properties: <strong>value</strong>, and <strong>done</strong>. Value stores the yield value returned, and done indicates if there is any more yield left in the function.</p><p>Example:</p><pre>const gen = function* () {<br>  yield 1<br>  yield 2<br>  yield 3<br>}</pre><pre>const receiver = gen()  //returns an object with a next fn<br>receiver.next()   //returns an object {value: 1, done: false}<br>receiver.next() //returns an object {value: 2, done: false}<br>receiver.next() //returns an object {value:3, done: false}<br>receiver.next() //returns an object {value: undefined, done: true}</pre><blockquote>The key takeaway here is the first yield in the gen function is not executed until the first next() is called. The function is essentially ‘<strong>paused</strong>’. In general, the ‘nth’ yield is not executed until the ‘nth’ next() is called.</blockquote><p>In this example, the state of the generator is maintained internally. This means the requester cannot change the values.</p><p>Fortunately, there is an option to pass values via the next method. The only point to note here is the value passed in next() will be assigned to the ‘result of the previous yield’. What does this even mean?</p><p>Let’s look at an example:</p><pre>const gen = function* () {<br>  let a = yield 1<br>  let b = yield 2 + a<br>  let c = yield 3 + b<br>}</pre><pre>const receiver = gen()  //returns an object with a next fn<br>receiver.next()   //returns an object {value: 1, done: false}<br>receiver.next(3) //returns an object {value: 5, done: false}<br>receiver.next(6) //returns an object {value:9, done: false}<br>receiver.next() //returns an object {value: undefined, done: true}</pre><p>If you look at the second next, we are passing the value of ‘3’. What essentially happens, is that the result of the previous yield i.e. ‘a’ gets assigned the value passed in the second next function i.e. 3 . The variable a’s value has now changed from 1 to 3. Similarly, we reassign b’s value to be ‘6’. Hence ‘c’ becomes 9, which is the last yield.</p><blockquote>The key takeaway here is we cannot pass the value to the first next function, since there is no previous yield at this point.</blockquote><p>Let’s zoom out one level and try to ask a question from what we just learnt about a generator and a promise:</p><p>What if the generator could pause the execution of some code until a promise finishes(resolved/rejected)?</p><h4>Asynchronous Generator</h4><p>Now that we know what a generator is, let’s look at an <strong>asynchronous </strong>generator.</p><blockquote>A generator is said to be async when its yielding an asynchronous operation (e.g. a promise)</blockquote><p>Let’s look at an example. Say, we have 3 promises: a,b, and c. Every time a next() is called, a promise is returned from the generator. What do you think the order of execution of these Promises will be here?</p><pre>const gen = function* () {<br>  let a = yield Promise.resolve(5)<br>  let b = yield new Promise((res, rej) =&gt; setTimeout(() =&gt; res(6), 3000))<br>  let c = yield Promise.resolve(7)<br>}</pre><pre>const receiver = gen()<br>let p1 = receiver.next(<br>p1.value.then(val =&gt; console.log(val))   <em>//returns 5  </em><br>let p2 = receiver.next()<br>p2.value.then(val =&gt; console.log(val))   <em>//returns 6</em><br>let p3 = receiver.next()<br>p3.value.then(val =&gt; console.log(val)) <em>//returns 7</em><br>receiver.next()</pre><p>Here is the console output:</p><pre><em>Promise {&lt;resolved&gt;: 5}<br>Promise {&lt;pending&gt;}__proto__: Promise[[PromiseStatus]]: &quot;resolved&quot;[[PromiseValue]]: 6<br>Promise {&lt;resolved&gt;: 7}__proto__: Promise[[PromiseStatus]]: &quot;resolved&quot;[[PromiseValue]]: 7<br>{value: undefined, done: true}<br>5<br>7<br>6</em></pre><p>Since we call next() immediately one after the other, the Promises start executing concurrently. In this case since ‘b’ has a delayed resolution(minimum of 3 seconds), it’s value(6) is resolved in the end, after ‘a’ (5) and ‘c’ (7). We don’t care about the ‘done’ state here too, since we know the promises would eventually get resolved.</p><p>But, what if we had a requirement that ‘b’ should be executed only after ‘a’ resolves, and ‘c’ should be executed only after ‘b’ resolves.</p><p>Let’s reiterate two facts about a generator:</p><ol><li><em>The only way to pause a generator function is to not call ‘next()’</em></li><li><em>We also know we can pass values inside next(), except for the very first time</em></li></ol><p>Let’s build a new function, which takes a promise and calls the ‘next()’ method of the generator only after the promise is resolved. In other words, it ‘waits’ for the promise to get resolved:</p><pre>const await = p =&gt; p.then(val =&gt; receiver.next(val)</pre><p>Here is the full refactored code:</p><pre>let receiver = null<br>const <strong>await</strong> = p =&gt; p.then(val =&gt; receiver.next(val))<br>const <strong>async</strong> = function* () {<br>    let a = yield <strong>await</strong>(Promise.resolve(5))<br>    console.log(a)<br>    let b = yield <strong>await</strong>(new Promise((res, rej) =&gt;  setTimeout(() =&gt; res(6), 3000)))<br>    console.log(b)<br>    let c = yield <strong>await</strong>(Promise.resolve(7))<br>    console.log(c)<br>}</pre><pre>receiver = <strong>async</strong>()<br>let promise = receiver.next()) //invoke the first yield<br>promise.then(val =&gt; console.log(&quot;resolved all promises:&quot; + val)</pre><p>Here is the console output from our custom async/await:</p><pre>{value: Promise, done: false}<br>5<br>resolved all promises: undefined<br>6<br>7<br></pre><p>Now how does this look when compared to our native ES6 async/await usage:</p><pre>const gen = <strong>async</strong> function() {<br>    let a = <strong>await</strong> Promise.resolve(5)<br>    console.log(a)<br>    let b = <strong>await</strong> new Promise((res, rej) =&gt;  setTimeout(() =&gt; res(6), 3000))<br>    console.log(b)<br>    let c = <strong>await</strong> Promise.resolve(7)<br>    console.log(c)<br>    return c<br>}</pre><pre>let promise = gen()<br>console.log(promise)<br>promise.then(val =&gt; console.log(&#39;resolved all promises:&#39; + val)</pre><p>Here is the console output:</p><pre>Promise<br>5<br>6<br>7<br>resolved all promises: 7</pre><p>Don’t they look a lot similar? This is exactly what’s happening under the hood for async/await. They combine a generator function with promises. Every time the await keyword is used before a promise, it makes sure the code after it, is not ‘yielded’, until the promise is resolved.</p><p>In other words, async/await facilitates synchronous usage between 1 or more promises.</p><h4>A small difference…</h4><p>There is a small difference between our custom implementation and the native one. When the first next() is called , a promise is returned. But it get’s resolved immediately after the first one completes, and returns undefined. This is not what the async function does. It returns a promise initially, but waits for all the promises inside its function to resolve, and then resolves the initial promise with the return value of the function.</p><p>Let’s refactor our code a little further:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/133c355dbdafeaadca6f2ef1198e8629/href">https://medium.com/media/133c355dbdafeaadca6f2ef1198e8629/href</a></iframe><p>What we have essentially done, is to wrap our initial async method with a wrapper that returns an initial promise to the caller. This promise is only resolved after all the promises inside the async function is resolved. This is achieved by passing the ‘res, and rej’ callbacks to the async generator through the next() method (line numbers: 37–40).</p><p>Here is the console output now:</p><pre>resolved: 5<br>resolved: 6<br>resolved: 7<br>all promises resolved</pre><p>Here is the jsfiddle if you want to play with: <a href="https://jsfiddle.net/abh7cr/w50we39d/">https://jsfiddle.net/abh7cr/w50we39d/</a></p><h4>Conclusion</h4><p>Async/await are a great addition to ES6. They make our code a lot cleaner when executing promises in a synchronous fashion. But, it’s important to understand that it is not a replacement for <strong>Promise.all</strong>. Promise.all allows concurrent execution of promises, while async/await only allows synchronous execution of promises.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6f6eda8be17" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A vue on Reactivity in Vue.js]]></title>
            <link>https://medium.com/@abhishekraj_14802/a-vue-on-reactivity-in-vue-js-293676d623ff?source=rss-b85e7e75917b------2</link>
            <guid isPermaLink="false">https://medium.com/p/293676d623ff</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[vuejs]]></category>
            <category><![CDATA[vue]]></category>
            <category><![CDATA[change-detection]]></category>
            <category><![CDATA[es2015]]></category>
            <dc:creator><![CDATA[Abhishek Raj]]></dc:creator>
            <pubDate>Tue, 15 May 2018 23:17:01 GMT</pubDate>
            <atom:updated>2018-05-16T14:12:49.383Z</atom:updated>
            <content:encoded><![CDATA[<p>Change is constant in a dynamic world. With respect to front-end app development, if you wanted to make your app dynamic, you would need to keep track of these changes in a very efficient manner.</p><p>Most likely you would not be using vanilla JS to build your complex apps. Instead, you would be using a framework of your choice: Angular, React, Vue etc. The way these frameworks handle changes are quite different, but their end goal is the same: Minimize the number of DOM manipulations as much as possible since they are quite expensive.</p><h4>What causes a state change in JavaScript?</h4><p>Anything that is asynchronous in nature is going to cause a change in the state. They can be any of the following:</p><ol><li><em>Events (user interactions, custom events)</em></li><li><em>setTimeout, setIntervals</em></li><li><em>Network Requests</em></li></ol><p>Lets take a look at the change detection mechanisms used by some of the popular JS frameworks.</p><blockquote>Angular relies on an awesome library called <a href="https://github.com/angular/zone.js/">zone.js</a>, which keeps track of all the async calls, and thus tells Angular when things change. Angular then runs change detection for that component and all its children.</blockquote><blockquote>React, on the other hand relies on the ‘setState’ method to know when something changes(it still doesn’t know what exactly has changed), and creates a new <strong>Virtual DOM</strong> with these changes. It then efficiently compares this vDOM with its previous one to get the diff, and finally apply this diff to the real DOM.</blockquote><blockquote>Vue.js follows a mechanism similar to that found in Knockout, Ember, Meteor to detect changes at a property level, and in addition uses Virtual DOM (from version 2 on-wards) to improve performance.</blockquote><p>The mechanism used by Vue is a <strong>dependency tracking system, </strong>which is made possible by this concept: <strong>Interception</strong>. With the advent of <strong>ES5</strong>, <strong>getters </strong>and <strong>setters </strong>were introduced in JS. This gives an opportunity to control (intercept) when a property is accessed or changed.</p><p>Let’s take an example: There is a variable named ‘a’. You can think of this as a ‘<strong>data</strong>’ property in a Vue component. You might want to display ‘a’ in your template. You would probably be doing something like this: &lt;p&gt;<strong>{{a}}&lt;/p&gt;</strong>. At this point, the data property ‘a’ is ‘<strong>bound</strong>’ to the template using <strong>interpolation</strong>. We now need to know whenever ‘a’ changes, and update its template correspondingly. In other words, <em>the binding expression is now </em><strong><em>dependent </em></strong><em>on ‘a’</em>. And there could be many more properties/expressions that depend on ‘a’ too. So now what we essentially need is a <em>list of dependencies on ‘a’</em>, and in that way whenever ‘a’ changes, it can <strong>notify </strong>all its dependents. In Vue, these dependencies are nothing but binding template expressions, and computed properties. Computed properties depend on other data/computed properties for their existence(<em>e.g. b = a * 10</em>).</p><p>Going back to our simple example of &lt;p&gt;{{a}}&lt;/p&gt;, when we first see this binding, we are going to convert it into a <strong>render function</strong>. The reason we are doing this, is so that this function can be set as a ‘<strong>callback</strong>’ function, which can be called later when we want to re-render the template.</p><h4>Dependency registrations</h4><p>When a property/expression is dependent on another property, it needs to follow 3 steps in order for it to track changes:</p><ol><li><em>Sets its callback function to a global active target property. The reason this is going to be a global property is because of the fact that JavaScript is single threaded and at any point in time, there is really going to be only one object which can access this target</em></li><li><em>Access the property its dependent on. In case of the binding expression, it would be running the render function, and in case of computed properties, it would be calling its computed function, both of which would invoke their dependent properties</em></li><li><em>Reset the global active target to null, so that other properties can use this, to register themselves as dependencies</em></li></ol><h4>Reactive properties</h4><p>In order to add its dependencies and inform them when it changes, every property would have its own dependency tracking object with 2 main functions: <strong>subscribe</strong> &amp; <strong>notify</strong>. Since we have the opportunity to intercept a property’s access and change phases, we are going to do a couple of things:</p><ol><li><em>In the property’s getter, we are going to check if there is any global active target. If so, we add that target’s value(which is essentially the callback fn) into the property’s list of dependencies using the subscribe function.</em></li><li><em>In the property’s setter, we are going to call the notify function, which would in-turn call the callback functions for all its dependents</em></li></ol><h4>Dependency chart</h4><p>Here is a simple example of a dependency chart with 1 data property, 3 binding template expressions and 2 computed properties:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RBONymlPrGWkTEjzkS49ww.png" /><figcaption>Dependency chart in Vue</figcaption></figure><p>You can infer from this graph a slight difference between a computed property and the binding expression. Lets say for a property A, the<strong> out-bound</strong> arrow from A to B means A is dependent on B, and <strong>in-bound </strong>from C to A means C depends on A. <em>At a minimum, there is always going be one out-bound arrow and one in-bound arrow for a computed property, while for a binding template there is never an in-bound arrow.</em> In other words, a computed property would have maintain its own list of properties that depend on it, in addition to itself being dependent on other properties. They are also different from the ‘data’ properties in the sense that, the ‘data’ properties are not dependent on anything else (<strong>0<em> outbound arrows</em></strong>).</p><h4>The code…</h4><p>Enough talking. Lets try to code these concepts.</p><p>We are going to create a <strong>Dependency Tracker</strong> class, which would have an <strong>active target</strong> as its global property. In addition, it would have 2 functions: <strong>subscribe </strong>and <strong>notify</strong>. The subscribe function would add the ‘active target’ callback to its list of subscribers. The notify function would the callback function for each subscriber.</p><p>PS:<em>I have added the name property for logging purposes</em></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/77d3a848437e2b6b133aeafa931d8166/href">https://medium.com/media/77d3a848437e2b6b133aeafa931d8166/href</a></iframe><p>Now that we have a dependency tracking mechanism, we are going to use this in our properties to make them ‘<strong>reactive</strong>’. We are first going to look at the ‘data’ properties of a Vue component, since they are the easiest to explain.</p><p>The <strong><em>initData</em></strong> function in the below code does the following: <em>Walks through each ‘data’ property in the component (including nested properties), and for each of them:</em></p><ol><li><em>create a dependency tracker object</em></li><li><em>initialize a ‘getter’ and ‘setter’ for each of them. The getter would check for an ‘active’ target, and if exists, would add it to its list of dependents. The setter would assign the new value (if the new value is an object, it re-initializes the value recursively), and would then notify all its dependents</em></li></ol><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5d728d8aea9032afdd4562807e138694/href">https://medium.com/media/5d728d8aea9032afdd4562807e138694/href</a></iframe><p>We have looked at adding dependencies and notifying them in data properties, using a dependency tracker object. We still have 2 missing pieces in our code:</p><blockquote><em>How does a property which is dependent on another property register itself?</em></blockquote><blockquote><em>Who will execute the callback function to re-render the template/ re compute the computed fn?</em></blockquote><p>Since we are not concerned about the template binding part(<em>v-bind or mustache</em>), I have used an extra property in the Component, called ‘<strong><em>templates</em></strong>’ to know which property to bind to which template:</p><pre><strong>HTML</strong></pre><pre>&lt;div id=&quot;a&quot;&gt;&lt;/div&gt;</pre><pre><strong>JS</strong></pre><pre>let templateForA = function() {<br>  return `&lt;p&gt;Hello, I am a &lt;i&gt;data&lt;/i&gt; prop. You can call me &lt;strong&gt;A&lt;/strong&gt;: ${this.a}&lt;/p&gt;`<br>}</pre><pre>templates: [{<br>      html: templateForA,<br>      prop: &quot;a&quot;<br>    },</pre><p>For 1, we are going to follow the 3 steps which we discussed in our <strong>Dependency registrations</strong> section. The <strong><em>bindPropToTemplate </em></strong>function<strong><em> </em></strong>does exactly that in line 7,8, and 9. Let’s walk line by line:</p><p><strong>Line number 7</strong>: <em>Assign the active target the ‘callback’ we discussed before. That callback here is stored in a ‘</em><strong><em>Watcher</em></strong><em>’ object. We will discuss this object in detail shortly.</em></p><p><strong>Line number 8:</strong><em> Run the render function, which invokes all the necessary property access</em></p><p><strong>Line number 9:</strong> <em>Reset the target to null, so other properties can use it</em></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a02c73dc5b259fc39d88d211bf210424/href">https://medium.com/media/a02c73dc5b259fc39d88d211bf210424/href</a></iframe><p>The <strong>Watcher</strong>: Answer to our second missing piece! It does the following:</p><blockquote><em>stores the callback, and wraps it in a function called ‘</em><strong><em>update</em></strong><em>’.</em></blockquote><p>The update function would be triggered by the ‘notify’ function (in the dependency tracker object function) for all its subscribers.</p><p><strong>Note</strong>: <em>The actual Watcher implementation in Vue is a lot more complex. It is responsible for collecting,and clearing dependencies. It is also responsible for the $watch object.</em></p><p>For simplicity sake, here is the bare minimum function we will be using:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/cac6b3e80b3edf3fbe58d937c7e12b67/href">https://medium.com/media/cac6b3e80b3edf3fbe58d937c7e12b67/href</a></iframe><p>Here is our simple render function that applies the template to the DOM:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/466a7079bf6b5da81e304e5fae8f55a9/href">https://medium.com/media/466a7079bf6b5da81e304e5fae8f55a9/href</a></iframe><p>Note: The <em>addAndRemoveClass</em> is used for the demo to highlight the changes in the DOM</p><h4><strong>So what about Computed properties?</strong></h4><p>When we were discussing the <strong>Dependency chart</strong>, we inferred that Computed properties would need to be notified when their dependencies change, and they should in turn notify their dependents. For this reason, every computed property would have its own ‘Watcher’ object. The callback for the watcher would do 2 things:</p><ol><li>Recompute the function, and cache the latest result (<strong>line no. 10</strong>). We cache it, so that we don’t recompute the function when its dependencies don’t change</li><li>Notify its dependents (<strong>line no. 11</strong>)</li></ol><p>Line <strong>14, 15 ,and 16</strong> are similar to the 3 steps we saw in the <strong><em>bindingPropToTemplate</em></strong> function:</p><ol><li><em>Assign the Watcher to the active target</em></li></ol><p><em>2. Run the computed function (this is only for the first time), and assign it to the cache</em></p><p><em>3. Reset the active target to ‘null’</em></p><p>The rest of the code is similar to that of a data property. It defines a getter ( Note: <em>I haven’t used a setter here since computed properties are generally getters</em>)</p><p>When a property tries to access the computed property, it’s going to be added to the list of dependents in its getter</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/04f5317651115d5c81a56b920961da06/href">https://medium.com/media/04f5317651115d5c81a56b920961da06/href</a></iframe><p>As far as ‘<strong>props</strong>’ are concerned, its going to behave similar to a data property, but without a ‘setter’, since they just inherit their values from their parent components.</p><h4>What about arrays and dynamic property additions?</h4><p>Arrays are a little tricky when it comes to change detection. We can patch its native methods like ‘<em>push, splice, pop, unshift, shift, reverse’ </em>and notify its dependents when the array changes using these methods.</p><p>However, it’s impossible to detect changes when the array is accessed by its index, or you change the length of the array directly (as discussed here: <a href="https://vuejs.org/v2/guide/list.html#Caveats">https://vuejs.org/v2/guide/list.html#Caveats)</a></p><p>That’s why Vue asks you to use the ‘<em>splice</em>’ method or the <em>Vue.set</em> method so that it can notify the array’s dependents on its change.</p><p>It is for the same reason that you cannot dynamically add new properties to an object, since they are not ‘reactive’ yet. You can either use the Vue.set method or declare all the properties during the initialization (as discussed here: <a href="https://vuejs.org/v2/guide/reactivity.html#Change-Detection-Caveats">https://vuejs.org/v2/guide/reactivity.html#Change-Detection-Caveats</a>)</p><p>With the advent of <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Proxy">ES2015 Proxies</a> in JavaScript, it becomes a lot easier to intercept properties at the object level (especially manipulating arrays), and Vue is going to be using them in v3!</p><p>Note that the demo source code does not cover arrays., and its just a very basic version of the reactive system.</p><p><strong>Demo</strong>: <a href="https://reactive-framework.firebaseapp.com/">https://reactive-framework.firebaseapp.com/</a></p><p><strong>Demo Source Code:</strong> <a href="https://github.com/abhi7cr/reactive">https://github.com/abhi7cr/reactive</a></p><p><strong>Presentation Link (from the recent Chicago Vue.js meetup): </strong><a href="https://gitpitch.com/abhi7cr/reactive#/">https://gitpitch.com/abhi7cr/reactive#/</a></p><p><strong>References:</strong></p><ul><li><a href="https://teropa.info/blog/2015/03/02/change-and-its-detection-in-javascript-frameworks.html">Change Detection</a></li><li><a href="https://vuejs.org/v2/guide/reactivity.html">Vuejs Reactivity</a></li><li><a href="https://www.youtube.com/watch?v=r4pNEdIt_l4&amp;t=914s">Reactivity in Front-End JS Frameworks</a></li><li><a href="https://dev.to/koehr/vuejs-reactivity-from-scratch">Vue.js reactivity from scratch</a></li><li><a href="https://skyronic.com/blog/vuejs-internals-computed-properties">Vue.js internals computed properties</a></li><li><a href="https://frontendmasters.com/courses/advanced-vue/introducing-reactivity/">Front-End-Masters Advanced Vue Course</a></li></ul><p>If you want to dig deep into how reactivity is tackled in the vue source code, you can find it here:</p><p><a href="https://github.com/vuejs/vue/tree/dev/src/core/observer">vuejs/vue</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=293676d623ff" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>