{"data":{"allBlogJson":{"edges":[{"node":{"title":["Child Process in Nodejs"],"link":["https://medium.com/@gkverma1094/child-process-in-nodejs-b2cd17c76830?source=rss-445df3ce30f2------2"],"content_encoded":["<figure><img alt=\"\" src=\"https://cdn-images-1.medium.com/max/1024/1*zS_WaV3gt7sl88loHHxYqw.jpeg\" /></figure><p>I have been working on nodejs for a long time. Since we all know Nodejs is not made for heavy server-side calculations. Node.js processes IOs in a non-blocking way, meaning that its single thread can manage several IO requests at the same time.</p><p>But sometimes we have to do some heavy calculations on the server-side, since nodejs is single-threaded, we can’t block the main thread for these kinds of calculations.</p><p>For these kinds of computations, we need to use the inbuilt library called<strong><em> child_process. </em></strong>Let&#39;s see why?</p><p>Child_process opens a process by creating a pipe, forking, and invoking the shell. Since a pipe is by definition unidirectional, the <em>type</em> argument may specify only reading or writing, not both the resulting stream is correspondingly read-only or write-only.</p><p>In simple words, <strong>child_process</strong> enable you for doing heavy computation by creating native OS or kernel threads. So, you can execute any script which that system (where you running your node script) supports.</p><p>I’m going to discuss some of the main methods from these libraries which save you from a lot of hell.</p><h3>child_process.spawn</h3><p>The child_process.spawn() method spawns the child process asynchronously, without blocking the Node.js event loop. The child_process.spawnSync() function provides equivalent functionality in a synchronous manner that blocks the event loop until the spawned process either exits or is terminated.</p><p>Let’s take an example</p><pre>const { spawn } = require(&quot;child_process&quot;);</pre><pre>const ls = spawn(&quot;cat&quot;, [&quot;index.js&quot;]);</pre><pre>ls.stdout.on(&quot;data&quot;, (data) =&gt; {<br>console.log(`stdout: ${data}`);<br>});</pre><pre>ls.stderr.on(&quot;data&quot;, (data) =&gt; {<br>console.error(`stderr: ${data}`);<br>});</pre><pre>ls.on(&quot;close&quot;, (code) =&gt; {<br>console.log(`child process exited with code ${code}`);<br>});</pre><p>Here, if we save above code as index.js, we get an output as</p><pre>&gt;&gt; node index.js </pre><pre>stdout: const { spawn } = require(&quot;child_process&quot;);<br>const ls = spawn(&quot;cat&quot;, [&quot;index.js&quot;]);</pre><pre>ls.stdout.on(&quot;data&quot;, (data) =&gt; {<br>  console.log(`stdout: ${data}`);<br>});</pre><pre>ls.stderr.on(&quot;data&quot;, (data) =&gt; {<br>  console.error(`stderr: ${data}`);<br>});</pre><pre>ls.on(&quot;close&quot;, (code) =&gt; {<br>  console.log(`child process exited with code ${code}`);<br>});</pre><p>We are here just running a shell command inside nodejs (shell-command because I&#39;m running the script on my Linux machine).</p><h3>child_process.exec</h3><p>`child_process.exec() spawns a shell and runs a command within that shell, passing the stdout and stderr to a callback function when complete. It spawns a shell then executes the command within that shell, buffering any generated output.</p><p>Let’s see an example</p><pre>const { exec } = require(&#39;child_process&#39;);<br>exec(&#39;python run.py&#39;, (err, stdout, stderr) =&gt; {<br>  if (err) {<br>    console.error(err);<br>    return;<br>  }<br>  console.log(stdout);<br>});</pre><pre>//output v12.16.3</pre><p>Here, with the help of the exec method, you can run any script just passing the command as a first parameter, and second as a callback so we can get the output from that file.</p><h3>child_process.execFile</h3><p>The child_process.execFile() is similar to child_process.exec() except that it does not spawn a shell by default. Rather, the specified executable file is spawned directly as a new process making it slightly more efficient than child_process.exec().</p><p>Let’s see an example</p><pre>const { execFile } = require(&#39;child_process&#39;);<br>const child = execFile(&#39;node&#39;, [&#39;--version&#39;], (error, stdout, stderr) =&gt; {<br>  if (error) {<br>    throw error;<br>  }<br>  console.log(stdout);<br>});<br>//output<br>v12.16.3</pre><h3>child_process.fork</h3><p>The child_process.fork() method is a special case of child_process.spawn() used specifically to spawn new Node.js processes. Like child_process.spawn(), a ChildProcess object is returned. The returned ChildProcess will have an additional communication channel built-in that allows messages to be passed back and forth between the parent and child. See subprocess.send() for details.</p><p>By default, child_process.fork() will spawn new Node.js instances using the process.execPath of the parent process. The execPath property in the options object allows for an alternative execution path to be used.</p><pre>//index.js</pre><pre>const { fork } = require(&quot;child_process&quot;);<br>const ls = fork(&quot;./child.js&quot;);</pre><pre>let count = 0;</pre><pre>//exiting the thread when child process ended</pre><pre>ls.on(&quot;exit&quot;, (code) =&gt; {<br>console.log(`child_process exited with code ${code}`);<br>});</pre><pre>ls.on(&quot;message&quot;, (msg) =&gt; {<br>console.log(`PARENT: message from child process is ${msg}`);<br>count = parseInt(msg) + 1;<br>console.log(&quot;PARENT: +1 from parent&quot;);<br>ls.send(count);<br>});</pre><pre>//child.js<br>var count = Math.floor(Math.random() * 100);</pre><pre>process.on(&quot;message&quot;, (msg) =&gt; {<br>console.log(&quot;CHILD: message received from parent process&quot;, msg);</pre><pre>count = parseInt(msg) + 1;</pre><pre>console.log(&quot;CHILD: +1 from child&quot;);<br>if (count &lt;= 100) process.send(count);<br>else process.exit(1);<br>});</pre><pre>console.log(count);</pre><pre>process.send(count);</pre><p>Well, this code simply passing messages back and forth between child process and its parent. The output will be something like this:</p><pre>&gt;&gt; node index.js<br>89<br>PARENT: message from child process is 89<br>PARENT: +1 from parent<br>CHILD: message received from parent process 90<br>CHILD: +1 from child<br>PARENT: message from child process is 91<br>PARENT: +1 from parent<br>CHILD: message received from parent process 92<br>CHILD: +1 from child<br>PARENT: message from child process is 93<br>PARENT: +1 from parent<br>CHILD: message received from parent process 94<br>CHILD: +1 from child<br>PARENT: message from child process is 95<br>PARENT: +1 from parent<br>CHILD: message received from parent process 96<br>CHILD: +1 from child<br>PARENT: message from child process is 97<br>PARENT: +1 from parent<br>CHILD: message received from parent process 98<br>CHILD: +1 from child<br>PARENT: message from child process is 99<br>PARENT: +1 from parent<br>CHILD: message received from parent process 100<br>CHILD: +1 from child<br>child_process exited with code 1</pre><p>I tried to explain as simple as I can. But if you found anything missing just reach out to me in comments.</p><p>If you want to support me, please give claps to my blog and follow me,</p><p><strong>“Lets code better”</strong></p><img src=\"https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b2cd17c76830\" width=\"1\" height=\"1\" alt=\"\">"]}},{"node":{"title":["A simple rectangles problem"],"link":["https://medium.com/@gkverma1094/a-simple-rectangles-problem-1b37964857f4?source=rss-445df3ce30f2------2"],"content_encoded":["<p><strong>Problem Statement -</strong></p><p>Find the total area covered by rectangles on given axis?</p><p>Well, it seems easy, but its not. Think about what if multiple rectangle overlapping on it. We need to remove the areas of overlapping on each others. But still we need to include those area which is removed many times because of multiple rectangle overlap. Sounds Complicated ?</p><figure><img alt=\"\" src=\"https://cdn-images-1.medium.com/max/800/1*Nk1oS_Wu5lK7e2UFLNn6KQ.png\" /><figcaption>Overlapping Rectangles</figcaption></figure><p>So, in here if we try to calculate total area covered by rectangles, that will be something like this :</p><p><strong>Total Area covered by Rectangles = </strong>area(A1) + area(A2) + area(A3) + area(A4) — area(A1 overlap A2) — area(A1 overlap A3) — area(A2 overlap A3) + Area(A1 overlap A2 and A2)</p><p>So, i guess now you got the idea what we are talking here. Right ?</p><p>Mathematically, it seems easy to calculate but its not. Atleast for me.</p><p>I’m going to solve it with a different approach. I called it Cover Box Algorithm, you can call whatever you want.</p><p>Basically, i’m going to make a rectangle which contains all these rectangle and then i’m going to clip the area which is not covered by rectangles. Simple right</p><figure><img alt=\"\" src=\"https://cdn-images-1.medium.com/max/800/1*ehAGHoaJV923wpFmBJ92VQ.png\" /><figcaption>Boundary Rectangle deleting white area</figcaption></figure><p>So we are going to remove the white part from the boundary rectangle to get the total area. Python code for algorithm is:</p><iframe src=\"\" width=\"0\" height=\"0\" frameborder=\"0\" scrolling=\"no\"><a href=\"https://medium.com/media/99191986e48163362408838f289784a8/href\">https://medium.com/media/99191986e48163362408838f289784a8/href</a></iframe><p>or you can go <a href=\"https://gist.github.com/glearner/1ea67478d10fccf5e47cee1ab2908886.js\">https://gist.github.com/glearner/1ea67478d10fccf5e47cee1ab2908886.js</a></p><p>Thanks for reading.</p><img src=\"https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1b37964857f4\" width=\"1\" height=\"1\" alt=\"\">"]}},{"node":{"title":["WHEN TO USE USESTATE OR USEREDUCER?"],"link":["https://medium.com/@gkverma1094/when-to-use-usestate-or-usereducer-26e01d8a2187?source=rss-445df3ce30f2------2"],"content_encoded":["<figure><img alt=\"\" src=\"https://cdn-images-1.medium.com/max/1024/1*_Vmk5Hs_6dqbf-lqF92IKg.jpeg\" /></figure><p>Everyone starting out with React Hooks quickly gets to know the useState hook. It’s there to update state in functional components by setting the initial state and returning the actual state and an updater function.</p><pre>import React, { useState } from &#39;react&#39;;</pre><pre>const Counter = () =&gt; {<br>const [count, setCount] = useState(0);</pre><pre>const handleIncrease = () =&gt; {<br>setCount(count =&gt; count + 1);<br>};</pre><pre>const handleDecrease = () =&gt; {<br>setCount(count =&gt; count - 1);<br>};</pre><pre>return (<br>&lt;div&gt;<br>&lt;h1&gt;Counter with useState&lt;/h1&gt;<br>&lt;p&gt;Count: {count}&lt;/p&gt;<br>&lt;div&gt;<br>&lt;button <em>type</em>=&quot;button&quot; <em>onClick</em>={handleIncrease}&gt;+&lt;/button&gt;<br>&lt;button <em>type</em>=&quot;button&quot; <em>onClick</em>={handleDecrease}&gt;-&lt;/button&gt;<br>&lt;/div&gt;<br>&lt;/div&gt;<br>);<br>};</pre><pre>export default Counter;</pre><p>The useReducer hook also can be used to update the state, but it does so in a <strong>more sophisticated</strong> way: it accepts a reducer function and an initial state, and it returns the actual state and a dispatch function. The dispatch function alters state in an implicit way by <strong>mapping actions to state transitions:</strong></p><pre>import React, { useReducer } from &#39;react&#39;;</pre><pre>const counterReducer = (state, action) =&gt; {<br>switch (action.type) {<br>case &#39;INCREASE&#39;: return { ...state, count: state.count + 1 };</pre><pre>case &#39;DECREASE&#39;: return { ...state, count: state.count - 1 };<br>default: throw new Error();<br>}<br>};</pre><pre>const Counter = () =&gt; {<br>const [state, dispatch] = useReducer(counterReducer, { count: 0 });<br>const handleIncrease = () =&gt; {<br>dispatch({ type: &#39;INCREASE&#39; });<br>};</pre><pre>const handleDecrease = () =&gt; {<br>dispatch({ type: &#39;DECREASE&#39; });<br>};</pre><pre>return (<br>&lt;div&gt;<br>&lt;h1&gt;Counter with useReducer&lt;/h1&gt;<br>&lt;p&gt;Count: {state.count}&lt;/p&gt;<br>&lt;div&gt;<br>&lt;button <em>type</em>=&quot;button&quot; <em>onClick</em>={handleIncrease}&gt;+&lt;/button&gt;<br>&lt;button <em>type</em>=&quot;button&quot; <em>onClick</em>={handleDecrease}&gt;-&lt;/button&gt;<br>&lt;/div&gt;<br>&lt;/div&gt;<br>);<br>};<br>export default Counter;</pre><h3>SIMPLE VS. COMPLEX STATE WITH HOOKS</h3><p>The reducer example encapsulated the count property into a state object, but we could have done this more simply by using count as the actual state. Refactoring to eliminate the state object and code count as a JavaScript integer primitive, we see that this use case doesn&#39;t involve managing a complex state:</p><pre>import React, { useReducer } from &#39;react&#39;;<br>const counterReducer = (state, action) =&gt; {<br>switch (action.type) {</pre><pre>case &#39;INCREASE&#39;:<br>return state + 1;</pre><pre>case &#39;DECREASE&#39;:<br>return state - 1;</pre><pre>default:throw new Error();<br>}<br>};</pre><pre>const Counter = () =&gt; {</pre><pre>const [count, dispatch] = useReducer(counterReducer, 0);</pre><pre>const handleIncrease = () =&gt; {</pre><pre>dispatch({ type: &#39;INCREASE&#39; });</pre><pre>};</pre><pre>const handleDecrease = () =&gt; {</pre><pre>dispatch({ type: &#39;DECREASE&#39; });</pre><pre>};</pre><pre>return (<br>&lt;div&gt;<br>&lt;h1&gt;Counter with useReducer&lt;/h1&gt;<br>&lt;p&gt;Count: {count}&lt;/p&gt;<br>&lt;div&gt;<br>&lt;button <em>type</em>=&quot;button&quot; <em>onClick</em>={handleIncrease}&gt;+&lt;/button&gt;</pre><pre>&lt;button <em>type</em>=&quot;button&quot; <em>onClick</em>={handleDecrease}&gt;-&lt;/button&gt;<br>&lt;/div&gt;<br>&lt;/div&gt;<br>);<br>};</pre><pre>export default Counter;</pre><p>Anyway, I would argue that <strong>once you move past managing a primitive (i.e. a string, integer, or boolean) and instead must manage a complex object (e.g. with arrays and additional primitives), you may be better of using useReducer</strong>. Perhaps a good rule of thumb is:</p><ul><li>Use useState whenever you manage a JS primitive</li><li>Use useReducer whenever you manage an object or array</li></ul><p>The decision of whether to use useState or useReducer isn’t always black and white; there are many shades of grey. I hope this article has given you a better understanding of when to use useState or useReducer.</p><p>If you want to support me, please give claps to my blog and follow me,</p><p><strong>“Lets code better”</strong></p><img src=\"https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=26e01d8a2187\" width=\"1\" height=\"1\" alt=\"\">"]}},{"node":{"title":["Service workers: A detailed look"],"link":["https://medium.com/@gkverma1094/service-workers-a-detailed-look-83336036c1af?source=rss-445df3ce30f2------2"],"content_encoded":["<p>Whenever I use CRA(Create React App), I always wonder why we use <a href=\"https://developer.mozilla.org/en-US/docs/Web/API/ServiceWorkerRegistration/unregister\"><strong>serviceWorker.unregister()</strong></a>.</p><figure><img alt=\"\" src=\"https://cdn-images-1.medium.com/max/700/1*djvSG40sdF6WCPTGrn9VWg.png\" /><figcaption>Lifecycle of service worker</figcaption></figure><p>I am going to take you through what a service worker is, why it was created, and how you can use it in your apps.</p><h3>What is a service worker?</h3><p>A service worker is a script that the client (your browser) runs in the background separate from the web page. Operating in the background separate from the web page enables you to use features that don’t actually require a web page or user interaction to trigger — like a <a href=\"https://developers.google.com/web/fundamentals/push-notifications/\">push notification</a> or <a href=\"https://developers.google.com/web/updates/2015/12/background-sync\">background sync</a>.</p><p>Why is this API such an exciting development? Because it allows you to support offline experiences, giving engineers and developers end-to-end control over the user’s interactions with the app. A service worker enables you to run JavaScript before a page even exists, makes your site faster, and allows you to display content even if there is no internet connection.</p><h3><strong>Key Properties of the </strong>service worker</h3><p>As you can tell, service workers are extremely important in creating a Progressive Web App (learn more about PWA’s <a href=\"https://developers.google.com/web/progressive-web-apps/\">here</a>). Before I dive into how to implement a service worker, here are some <a href=\"https://github.com/w3c/ServiceWorker/blob/master/explainer.md\">key traits and properties</a> that it has:</p><ul><li>Runs in its own global script context</li><li>Is not directly tied to any particular page</li><li>Cannot access the DOM</li><li>Is event-driven (it’s terminated when it’s not in use and run again when needed)</li><li>Is <strong>HTTPS</strong> only</li></ul><p>Quick Note: Service workers in Mozilla are not accessible in the private window, and chrome is also removing support.</p><p>There are some pretty interesting things to note about a service worker. Since it can’t access the DOM directly, it needs a workaround to communicate with the pages it controls. It does this by responding to messages sent via the <a href=\"https://html.spec.whatwg.org/multipage/workers.html#dom-worker-postmessage\">postMessage</a> interface (through a MessagePort), allowing those pages it’s controlling to manipulate the DOM as directed. Additionally, being event-driven, you can’t rely on the state in a service worker’s onfetch and onmessage handlers to persist any data. According to the React documentation, if there is information that you need to persist and reuse across restarts, service workers have access to the <a href=\"https://developer.mozilla.org/en-US/docs/Web/API/IndexedDB_API\">IndexedDB API</a>.</p><p>It’s clear that service workers are complicated yet powerful tools that we have at our disposal. What’s even better? React sets us up for success with implementing them just by running create-react-app. In this next section, I’ll walk you through how to set up a service worker with your React app.</p><h3>How do I use a service worker?</h3><p>After creating a new React app, you’ll see the following file structure created for you:</p><figure><img alt=\"\" src=\"https://cdn-images-1.medium.com/max/700/1*U-_GWWNd5aU_OKW3_addpg.png\" /><figcaption>The file structure automatically created for you when you build a new React app.</figcaption></figure><p>By default, the React build process will generate a serviceWorker.js file in your src folder. However, the default for the service worker is unregistered, meaning that it won’t yet be able to take control of your web app.</p><p>So, we’ll need to first opt-in to the offline-first behavior. In your code look forsrc/index.As it states, switching serviceWorker.unregister() to serviceWorker.register() will allow you to opt into using the service worker.</p><p>Without React’s handy provided code, you’d have to code the entire service worker lifecycle. Here’s a brief overview on what that looks like <a href=\"https://developers.google.com/web/fundamentals/primers/service-workers/\">via Google documentation</a>:</p><figure><img alt=\"\" src=\"https://cdn-images-1.medium.com/max/700/1*nXBPefTxfOZpcQ5YKiw60A.png\" /></figure><p>So, you’d have to manually code the register → install → cache &amp; return requests → so on and so forth process.</p><p>Luckily, we have React! If you pop into your src/serviceWorker.js file, you can see a lot of things are going there.</p><p>The benefits of opting-in to using the service worker are great, including creating faster and more reliable web apps and providing a more engaging mobile experience. However, just like most functionalities, there are some things to take into account if you decide to opt-in to service worker registration. You can learn about those in the official React.js documentation <a href=\"https://facebook.github.io/create-react-app/docs/making-a-progressive-web-app#offline-first-considerations\">here</a>.</p><p>So, the next time you get a push notification when your friend likes your Instagram or you start receiving ads for a local business the minute you set foot in that store’s town — you have service helpers to thank for that!</p><img src=\"https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=83336036c1af\" width=\"1\" height=\"1\" alt=\"\">"]}},{"node":{"title":["What new features added to ES2020?"],"link":["https://medium.com/@gkverma1094/what-new-features-added-to-es2020-7e7d4d70184e?source=rss-445df3ce30f2------2"],"content_encoded":["<figure><img alt=\"\" src=\"https://cdn-images-1.medium.com/max/1024/1*_1yUVJY6cDvLNc0ISUKPbQ.png\" /></figure><p>So, it has been a while ES20 features around us, but we are not using it. Some of us know about them but some may not. So, I’m just giving you the basic idea about new features which is going to make your life easier as a developer. So, let’s begin.</p><h3>Dynamic Import</h3><p>This is my most favorites feature in all of them. So, dynamic Import introduces a new function-like form of import that unlocks new capabilities compared to static import. Dynamic Import introduces a new function-like form of import that caters to those use cases.</p><pre>&lt;script type=&quot;module&quot;&gt;<br>  const moduleSpecifier = &#39;./utils.mjs&#39;;<br>  import(moduleSpecifier)<br>    .then((module) =&gt; {<br>      module.default();<br>      // → logs &#39;Hi from the default export!&#39;<br>      module.doStuff();<br>      // → logs &#39;Doing stuff…&#39;<br>    });<br>&lt;/script&gt;</pre><p>Since import() returns a promise, it’s possible to use async/await instead of the then-based callback style:</p><pre>&lt;script type=&quot;module&quot;&gt;<br>  (async () =&gt; {<br>    const moduleSpecifier = &#39;./utils.mjs&#39;;<br>    const module = await import(moduleSpecifier)<br>    module.default();<br>    // → logs &#39;Hi from the default export!&#39;<br>    module.doStuff();<br>    // → logs &#39;Doing stuff…&#39;<br>  })();<br>&lt;/script&gt;</pre><p>FYI, import() <em>looks</em> like a function call, it is specified as <em>syntax</em> that just happens to use parentheses (similar to super()).</p><h3>Nullish coalescing</h3><p>As we all know, sometimes we need to handle null and undefined conditions separately, but in general, how we do that is demoed below</p><pre>const enable = props.enabled || true; <br>//if props.enabled undefined, it will take true as its value</pre><p>Now, there’s an issue, props.enabled will assign true even if props.enabled is false or 0 but here, we only want to handle only null and undefined, then we have manually check typeof or we do another check but nullish coalescing (??) will solve this issue very easily.</p><pre>false ?? true;   // =&gt; false<br>0 ?? 1;          // =&gt; 0<br>&#39;&#39; ?? &#39;default&#39;; // =&gt; &#39;&#39;</pre><pre>null ?? [];      // =&gt; []<br>undefined ?? []; // =&gt; []</pre><h3><strong>Promise combinators</strong></h3><p>Promise combinators like <strong>Promise.all</strong> and <strong>Promise.race</strong>. But now, we got 2 new more static methodsPromise.allSettled and Promise.any .With those additions, there’ll be a total of four promise combinators in JavaScript, each enabling different use cases.Promise.allSettled gives you a signal when all the input promises are <em>settled</em>, which means they’re either <em>fulfilled</em> or <em>rejected</em>. This is useful in cases where you don’t care about the state of the promise, you just want to know when the work is done, regardless of whether it was successful.</p><pre>const promises = [<br>  fetch(&#39;/api-call-1&#39;),<br>  fetch(&#39;/api-call-2&#39;),<br>  fetch(&#39;/api-call-3&#39;),<br>];<br>// Imagine some of these requests fail, and some succeed.</pre><pre>await Promise.allSettled(promises);<br>// All API calls have finished (either failed or succeeded).<br>removeLoadingIndicator();</pre><p>Promise.any gives you a signal as soon as one of the promises fulfills. This is similar to Promise.race, except any doesn’t reject early when one of the promises rejects.</p><pre>const promises = [<br>  fetch(&#39;/endpoint-a&#39;).then(() =&gt; &#39;a&#39;),<br>  fetch(&#39;/endpoint-b&#39;).then(() =&gt; &#39;b&#39;),<br>  fetch(&#39;/endpoint-c&#39;).then(() =&gt; &#39;c&#39;),<br>];<br>try {<br>  const first = await Promise.any(promises);<br>  // Any of the promises was fulfilled.<br>  console.log(first);<br>  // → e.g. &#39;b&#39;<br>} catch (error) {<br>  // All of the promises were rejected.<br>  console.log(error);<br>}</pre><h3>String.matchAll</h3><p>For me, it is very common to repeatedly apply the same regular expression on a string to get all the matches. To some extent, this is already possible today by using the String#match method. Something like this.</p><pre>const string = &#39;Magic hex numbers: DEADBEEF CAFE&#39;;<br>const regex = /\\b\\p{ASCII_Hex_Digit}+\\b/gu;<br>for (const match of string.match(regex)) {<br>  console.log(match);<br>}</pre><pre>// Output:<br>// &#39;DEADBEEF&#39;<br>// &#39;CAFE&#39;</pre><p>However, this only gives you the <em>substrings</em> that match. Usually, you don’t just want the substrings, you also want additional information such as the index of each substring, or the capturing groups within each match.</p><p>It’s already possible to achieve this by writing your own loop, and keeping track of the match objects yourself, but it’s a little annoying and not very convenient:</p><pre>const string = &#39;Magic hex numbers: DEADBEEF CAFE&#39;;<br>const regex = /\\b\\p{ASCII_Hex_Digit}+\\b/gu;<br>let match;<br>while (match = regex.exec(string)) {<br>  console.log(match);<br>}</pre><pre>// Output:<br>// [ &#39;DEADBEEF&#39;, index: 19, input: &#39;Magic hex numbers: DEADBEEF CAFE&#39; ]<br>// [ &#39;CAFE&#39;,     index: 28, input: &#39;Magic hex numbers: DEADBEEF CAFE&#39; ]</pre><p>But now, new String#matchAll API makes this easier than ever before: you can now write a simple for-of loop to get all the match objects.</p><pre>const string = &#39;Magic hex numbers: DEADBEEF CAFE&#39;;<br>const regex = /\\b\\p{ASCII_Hex_Digit}+\\b/gu;<br>for (const match of string.matchAll(regex)) {<br>  console.log(match);<br>}</pre><pre>// Output:<br>// [ &#39;DEADBEEF&#39;, index: 19, input: &#39;Magic hex numbers: DEADBEEF CAFE&#39; ]<br>// [ &#39;CAFE&#39;,     index: 28, input: &#39;Magic hex numbers: DEADBEEF CAFE&#39; ]</pre><p>String#matchAll is especially useful for regular expressions with capture groups.</p><h3>globalThis</h3><p>If I’ve written JavaScript for use in a web browser before, I have used window to access the global this. In Node.js, I have used global. If you’ve written code that must work in either environment, you may have detected which of these is available, and then used that — but the list of identifiers to check grows with the number of environments and use cases you want to support.</p><p>Some of my naive attempt to get ‘this’. Please don’t judge me.</p><pre>const getGlobalThis = () =&gt; {<br>  if (typeof globalThis !== &#39;undefined&#39;) return globalThis;<br>  if (typeof self !== &#39;undefined&#39;) return self;<br>  if (typeof window !== &#39;undefined&#39;) return window;<br>  if (typeof global !== &#39;undefined&#39;) return global;<br>  // Note: this might still return the wrong result!<br>  if (typeof this !== &#39;undefined&#39;) return this;<br>  throw new Error(&#39;Unable to locate global `this`&#39;);<br>};<br>const theGlobalThis = getGlobalThis();</pre><p>The globalThis proposal introduces a <em>unified</em> mechanism to access the global this in any JavaScript environment (browser, Node.js, or something else?), regardless of the script goal (classic script or module?).</p><p>And now that ugly code can be written in one line of code.</p><pre>const theGlobalThis = globalThis;</pre><p>First, I looked at this, it looks like magic to me.</p><h3>Optional chaining</h3><p>We all know, long chains of property accesses in JavaScript can be error-prone, as any of them might evaluate to null or undefined (also known as “nullish” values). Checking for property existence on each step easily turns into a deeply-nested structure of if-statements or a long if-condition replicating the property access chain:</p><pre>// Error prone-version, could throw.<br>const nameLength = db.user.name.length;</pre><pre>// Less error-prone, but harder to read.<br>let nameLength;<br>if (db &amp;&amp; db.user &amp;&amp; db.user.name)<br>  nameLength = db.user.name.length;</pre><p>The above can also be expressed using the ternary operator, which doesn’t exactly help readability:</p><pre>const nameLength =<br>  (db<br>    ? (db.user<br>      ? (db.user.name<br>        ? db.user.name.length<br>        : undefined)<br>      : undefined)<br>    : undefined);</pre><p>But now, optional chaining comes for us to rescue. The above ugly code can be written as:</p><pre>const nameLength = db?.user?.name?.length;</pre><p>For me, its lifesaver, like checking a method exist in nested object and then executing it. Like:</p><pre>const adminOption = db?.user?.validate?.()</pre><p>Here, we can execute validate once validate exist and not undefined.</p><h3>BigInt: arbitrary-precision integers</h3><p>Finally, we got bigInt in javascript. BigIntis a new primitive in the JavaScript language.BigInt is a new numeric primitive in JavaScript that can represent integers with arbitrary precision. With BigInts, you can safely store and operate on large integers even beyond the safe integer limit for Numbers. This article walks through some use cases and explains the new functionality in Chrome 67 by comparing BigInts to Numbers in JavaScript.</p><p>BigInts make it possible to correctly perform integer arithmetic without overflowing. Example:</p><pre>const max = Number.MAX_SAFE_INTEGER;<br>// → 9_007_199_254_740_991</pre><p>So, what’s the issue. Let see what happen when we add 1 and 2</p><pre>max + 1;<br>// → 9_007_199_254_740_992 (correct)</pre><pre>max + 2;<br>// → 9_007_199_254_740_992 (false)</pre><p>So now BigInt is here to save us:</p><pre>BigInt(Number.MAX_SAFE_INTEGER) + 2n;<br>// → 9_007_199_254_740_993n (correct)</pre><pre>Don&#39;t try to multiply like this<br>1234567890123456789 * 123;<br>// → 151851850485185200000 (wrong)</pre><pre>1234567890123456789n * 123n;<br>// → 151851850485185185047n (correct)</pre><p>The safe integer limits for Numbers don’t apply to BigInts. Therefore,with BigInt we can perform correct integer arithmetic without having to worry about losing precision.</p><h3>Module namespace exports</h3><p>Last but not least, we use the default exports to export only a single value. During import, we can omit the curly braces, and we can use the name that we want:</p><pre>//------ utils.js ------<br>export default 10;<br>//------ main.js ------<br>import aValue from &#39;utils.mjs&#39;;//------ utils.js ------<br>export default class MyClass {}<br>//------ main.js ------<br>import oneClass from &#39;utils.mjs&#39;;</pre><p>But now we can also do something like this:</p><pre>//------ utils.js ------<br><strong>export * as utils from &#39;./utils.mjs&#39;</strong></pre><p>Namespace exports introduce the same usage style for import/export keywords to the developer, obtaining symmetrical behavior, and helping to avoid errors.</p><p>That’s all, now you know more about Javascript and its new features which made you a better coder than before.</p><p>If you want to support me, please give claps to my blog and follow me,</p><p><strong>“Lets code better”</strong></p><img src=\"https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7e7d4d70184e\" width=\"1\" height=\"1\" alt=\"\">"]}},{"node":{"title":["What’s new in React 16.13.0"],"link":["https://medium.com/@gkverma1094/whats-new-in-react-16-13-0-b730f2ef0b4f?source=rss-445df3ce30f2------2"],"content_encoded":["<p>Well, Reactjs become one of best javascript framework, i ever used. It’s simple and elegant. But we have also accept the framework fatigue with it. React is changing very rapidly with every version of it. Most of people have no idea what we got in new version of Reactjs.</p><p>So, we are going to see new features which added to Reactjs 16.13.0.</p><h3>Introducing Concurrent Mode (Experimental)</h3><p>By the way if you don’t know what is concurrency in reactjs mean, let me explain you. So, concurrent mode is a set of new features that help React apps stay responsive and gracefully adjust to the user’s device capabilities and network speed. You can check react fiber for this new feature implementation.</p><h4>Blocking vs Interruptible Rendering</h4><p>To explain Concurrent Mode, i’ll use version control as a metaphor. If you work on a team, you probably use a version control system like Git and work on branches. When a branch is ready, you can merge your work into master so that other people can pull it.</p><p>Before version control existed, the development workflow was very different. There was no concept of branches. If you wanted to edit some files, you had to tell everyone not to touch those files until you’ve finished your work. You couldn’t even start working on them concurrently with that person — you were literally <em>blocked</em> by them.</p><p>This illustrates how UI libraries, including React, typically work today. Once they start rendering an update, including creating new DOM nodes and running the code inside components, they can’t interrupt this work. I’ll call this approach “blocking rendering”.</p><p>In Concurrent Mode, rendering is not blocking. It is interruptible. This improves the user experience. It also unlocks new features that weren’t possible before.</p><p>You can check more on <a href=\"https://reactjs.org/docs/concurrent-mode-patterns.html\">here</a>.</p><h3>Renaming Unsafe Lifecycle Methods</h3><p>Since last year, react developers made some lifecycle to unsafe. Basically three of them, i remember :</p><p>componentWillMount → UNSAFE_componentWillMount</p><p>componentWillReceiveProps → UNSAFE_componentWillReceiveProps</p><p>componentWillUpdate → UNSAFE_componentWillUpdate</p><p>React 16.9 does not know componentWillMount anymore, and the old names are going to break your code. So now what, our code is going to break because we used these cycles in many components. The answer is NO. How ?</p><p>Well, react provided a tool called codemod. So if you are using earlier version of react 16.9 and you want to update to latest version, and you have to convert all componentWill to UNSAFE_componentWill.</p><p>Just run a simple command</p><pre>npx react-codemod rename-unsafe-lifecycles</pre><figure><img alt=\"\" src=\"https://cdn-images-1.medium.com/max/884/1*onn2uqFFuTX-9fBJu3HBaw.gif\" /></figure><p>The new names like UNSAFE_componentWillMount <strong>will keep working in both React 16.9 and in React 17.x</strong>.</p><h3>Scheduler (Experimental)</h3><p>So, these experimental feature are planned to get merge in React 17.x.</p><p>Scheduler is added to react because they want to improve queue performance by switching its internal data structure to a min binary heap. Till now, you can usepostMessage loop with short intervals instead of attempting to align to frame boundaries with requestAnimationFrame. But since its in experimental, I will not like to add this in my project because who know when they might get dropped.</p><p>But if they included it in react, our render performance will increased and animation will be more smoother. FYI, they just trying to change slower algorithm to faster one.</p><h3>Normal Bug Fixes</h3><p>Lots of bug fixed now which where in earlier version. Some of fixes are :-</p><p>Deprecate React.createFactory()</p><p>Warn when changes in style may cause an unexpected collision</p><p>Warn when a function component is updated during another component’s render phase</p><p>Fixed onMouseEnter being fired on disabled buttons.</p><p>Call shouldComponentUpdate twice when developing in StrictMode.</p><p>Show component stacks in more warnings.</p><p>Adjust SuspenseList CPU bound heuristic.</p><p>Fixed React.memo components dropping updates when interrupted by a higher priority update.</p><p>And many others. If you want to see full list, visit <a href=\"https://github.com/facebook/react/blob/master/CHANGELOG.md#16130-february-26-2020\">here</a></p><p>If you like this blog, please give me a clap. :)</p><img src=\"https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b730f2ef0b4f\" width=\"1\" height=\"1\" alt=\"\">"]}},{"node":{"title":["Writing a custom render method in Reactjs."],"link":["https://medium.com/@gkverma1094/writing-a-custom-render-method-in-reactjs-8ccb9d3782e?source=rss-445df3ce30f2------2"],"content_encoded":["<figure><img alt=\"\" src=\"https://cdn-images-1.medium.com/max/1024/1*mO5MIGY-R4jrDaplzAwP1A.png\" /></figure><p>This implementation of render just a demo, how render method is implemented. You can’t replace the real render method by this.</p><p>When I see all lifecycle methods in react and I always wondered how they’re implemented. So, I tried to implement my own custom render method.</p><p>Let’s see what a render method does in React.</p><p>Render method used to render a React element into the DOM in the supplied container and return a <a href=\"https://reactjs.org/docs/more-about-refs.html\">reference</a> to the component (or returns null for <a href=\"https://reactjs.org/docs/components-and-props.html#function-and-class-components\">stateless components</a>).</p><pre>ReactDOM.render(element, container[, callback])</pre><p>From the above declaration, I know the render method takes 2 arguments, element whom I want to render and container which is previously rendered element or basically its parent.</p><p>Let’s set up the project by running a create-react-app command.</p><pre>npx create-react-app my-app<br>cd my-app<br>npm start</pre><p>Now, I have to remove the default render method from <strong>Index.js </strong>and adding my own render method.</p><pre>import React from &#39;react&#39;;<br><em>// import ReactDOM from &#39;react-dom&#39;;<br></em>import ReactDomMini from &#39;./ReactDomMin&#39;;<br>import &#39;./index.css&#39;;<br>import App from &#39;./App&#39;;<br>import * as serviceWorker from &#39;./serviceWorker&#39;;<br>ReactDomMini.render(&lt;App /&gt;, document.getElementById(&#39;root&#39;));<br>serviceWorker.unregister();</pre><p>Now create a new file in the <strong>src</strong> folder, named RectDomMin. Now, we going to add one npm library which helps us for reconciliation. React-reconciler provides a declarative API so that you don’t have to worry about exactly what changes on every update.</p><pre>npm i react-reconciler</pre><p>Now, I added the react-reconciler for accessing some important methods. Adding import in ReactDomMin.js.</p><pre>import ReactReconciler from &#39;react-reconciler&#39;;</pre><p>Our render method looks like this.</p><pre>let ReactDomMini = {<br>render(whatToRender,div){<br>let container = reconciler.createContainer(div,false,false);<em> <br>//first false for concurrent and second false for hydration<br></em>reconciler.updateContainer(whatToRender,container,null,null)<br>},<br>};</pre><p>Our reconciler method will look like this.</p><pre>let reconciler = ReactReconciler({})</pre><p>Now, start passing methods to the ReactReconciler.</p><p><strong>createInstance</strong>, is a method that takes your element and converts the instance which we can add up to our parent tree (made by react).</p><pre>createInstance(type,props,rootContainerInstance,hostContext, internalInstanceHandle,)</pre><p>So, let see the arguments of the above method:-</p><ol><li><strong>type: </strong>what type of element is passed. Like h1, p, etc.</li></ol><p><strong>2. props</strong>: props basically contains the properties of elements like alt, href, etc.</p><p><strong>3. rootContainerInstance: </strong>root parent of the element or instance.</p><p><strong>4. hostContext</strong>: basically contains the access of passed context to the element from its parent.</p><p><strong>5. internalInstanceHandle</strong>: returns obj which is a type of React fiber node. So it can add to virtual dom. React fiber node basically contains state property, listeners and access of other variables which needed for reconciliation.</p><p>So, now we have to create an element with the help of <strong>document.create().</strong></p><pre>let el = document.createElement(type);</pre><p>Now, with the help of props, we going to map properties from props.</p><pre>if (props.className) el.className = props.className;<br>if (props.src) el.src = props.src;<br>if (props.bgColor){<br>el.style.backgroundColor = props.bgColor;<br>}</pre><p>Now, we loop through the list of properties to map the props to the created instance.</p><pre><em>//tags of react element(dom element)</em></pre><pre>[&#39;alt&#39;,&#39;className&#39;,&#39;href&#39;,&#39;rel&#39;,&#39;src&#39;,&#39;target&#39;].forEach(k=&gt;{<br>if(props[k]) el[k] = props[k];<br>});</pre><p>Now, we want to add an event listener to the created instance.</p><pre>if(props.onClick){<br> el.addEventListener(&#39;click&#39;,props.onClick);<br>}</pre><p>So, now my createInstance method looks like below :</p><pre>createInstance(type,props,rootContainerInstance,hostContext, internalInstanceHandle,){<br>let el = document.createElement(type);<br>if (props.className) el.className = props.className;<br>if (props.src) el.src = props.src;<br>if (props.bgColor){<br>el.style.backgroundColor = props.bgColor;<br>}<br><em>//tags of react element(dom element)</em>[&#39;alt&#39;,&#39;className&#39;,&#39;href&#39;,&#39;rel&#39;,&#39;src&#39;,&#39;target&#39;].forEach(k=&gt;{<br>if(props[k]) el[k] = props[k];<br>});<br>if(props.onClick){<br>el.addEventListener(&#39;click&#39;,props.onClick);<br>}<br>return el;<br>},</pre><p><strong>createTextInstance, </strong>is a method to create an instance of the text node because reactjs handle those element separately which enable us for injecting dynamic text in the tags.</p><pre>createTextInstance(text,rootContainerInstance,hostContext,internalInstanceHandle){<br> return document.createTextNode(text);<br>}</pre><p><strong>appendChildToContainer, </strong>is a method to append the child node or instance to the react parent container. It takes 2 parameters one is container (parent container) and child (which we going to append).</p><pre>appendChildToContainer(container,child){<br>  container.appendChild(child)<br>}</pre><p><strong>appendInitialChild</strong>, is a method to create and initialize the root node or instance.</p><pre>appendInitialChild(parent,child){<br>  parent.appendChild(child)<br>}</pre><p><strong>removeChildFromContainer, </strong>is a method to remove the child from the container(react-dom tree).</p><pre>removeChildFromContainer(container,child){<br>   container.removeChild(child)<br>}</pre><p><strong>removeChild, </strong>is a method of react-reconciler, is a method to remove the child from dom.</p><pre>removeChild(parent,child){<br>   parent.removeChild(child)<br>}</pre><p>We have to also need to pass the default parameters, like commitUpdate, finalizeInitialChildren, getChildHostContext, etc.</p><p>So implementing these methods, our RectDomMin.js file looks like this.</p><pre>import ReactReconciler from &#39;react-reconciler&#39;;<br>let reconciler = ReactReconciler({<br>supportsMutation : true,<br>createInstance(type,props,rootContainerInstance,hostContext, internalInstanceHandle,){<br>let el = document.createElement(type);<br>if (props.className) el.className = props.className;<br>if (props.src) el.src = props.src;<br>if (props.bgColor){<br>el.style.backgroundColor = props.bgColor;<br>}<br><em>//tags of react element(dom element)</em>[&#39;alt&#39;,&#39;className&#39;,&#39;href&#39;,&#39;rel&#39;,&#39;src&#39;,&#39;target&#39;].forEach(k=&gt;{<br>if(props[k]) el[k] = props[k];<br>});<br>if(props.onClick){<br>el.addEventListener(&#39;click&#39;,props.onClick);<br>}<br>return el;<br>},</pre><pre>createTextInstance(text,rootContainerInstance,hostContext,internalInstanceHandle){<br>console.log(text)<br>return document.createTextNode(text);<br>},</pre><pre>appendChildToContainer(container,child){<br>container.appendChild(child)<br>},</pre><pre>appendInitialChild(parent,child){<br>parent.appendChild(child)<br>},<br>commitUpdate(instance,updatePayload,type,oldProps,newProps,finishedWork){},<br>finalizeInitialChildren(){},<br>getChildHostContext(){},<br>getPublicInstance(){},<br>getRootHostContext(){},<br>prepareForCommit(){},<br>resetAfterCommit(){},<br>shouldSetTextContent(){<br>     return false<br>},<br>removeChildFromContainer(container,child){<br>container.removeChild(child)<br>},<br>removeChild(parent,child){<br>parent.removeChild(child)<br>},<br>insertInContainerBefore(container,child,before){<br>container.insertBefore(child,before)<br>},<br>insertBefore(parent,child,before){<br>parent.insertBefore(child,before)<br>},</pre><pre>prepareUpdate(instance,type,oldProps,newProps,rootContainerInstance,currentHostContainer){<br>let payload;<br>if(oldProps.bgColor !== newProps.bgColor){<br>    payload = { newBgColor: newProps.bgColor}<br>}<br>return payload<br>},<br>commitUpdate(instance,updatePayload,type,oldProps,newProps,finishedWork){<br>if(updatePayload.newBgColor){<br>instance.style.backgroundColor = updatePayload.newBgColor;<br>}<br>}<br>});</pre><pre>let ReactDomMini = {<br>render(whatToRender,div){<br>let container = reconciler.createContainer(div,false,false);<em> <br>//first false for concurrent and second false for hydration<br></em>reconciler.updateContainer(whatToRender,container,null,null)<br>},<br>};</pre><pre>export default ReactDomMini;</pre><figure><img alt=\"\" src=\"https://cdn-images-1.medium.com/max/1024/1*zg2rr5pL6RXgahdOxHW3yw.gif\" /></figure><p>If, you want to clone, please go to my <a href=\"https://github.com/glearner/React-Render\">GitHub</a> repo.</p><p>Please give a clap if you like the post.</p><img src=\"https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8ccb9d3782e\" width=\"1\" height=\"1\" alt=\"\">"]}}]}}}