<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>DEV Community: Rajnish Katharotiya</title>
    <description>The latest articles on DEV Community by Rajnish Katharotiya (@rajnishkatharotiya).</description>
    <link>https://dev.to/rajnishkatharotiya</link>
    <image>
      <url>https://media2.dev.to/dynamic/image/width=90,height=90,fit=cover,gravity=auto,format=auto/https:%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F357564%2Ff9e3881a-cf48-4b5a-a499-13d7bad7742c.png</url>
      <title>DEV Community: Rajnish Katharotiya</title>
      <link>https://dev.to/rajnishkatharotiya</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://dev.to/feed/rajnishkatharotiya"/>
    <language>en</language>
    <item>
      <title>Omit unwanted data from Object using JavaScript</title>
      <dc:creator>Rajnish Katharotiya</dc:creator>
      <pubDate>Sun, 24 May 2020 11:24:29 +0000</pubDate>
      <link>https://dev.to/rajnishkatharotiya/omit-unwanted-data-from-object-using-javascript-3b58</link>
      <guid>https://dev.to/rajnishkatharotiya/omit-unwanted-data-from-object-using-javascript-3b58</guid>
      <description>&lt;p&gt;&lt;em&gt;Photo by &lt;a href="https://unsplash.com/@socialcut?utm_source=unsplash&amp;amp;utm_medium=referral&amp;amp;utm_content=creditCopyText"&gt;S O C I A L . C U T&lt;/a&gt; on &lt;a href="https://unsplash.com/s/photos/code-girl?utm_source=unsplash&amp;amp;utm_medium=referral&amp;amp;utm_content=creditCopyText"&gt;Unsplash&lt;/a&gt;&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;Remove particular data from an object is still an easy task to do. But guess you want to remove all data which not matched with your condition like an example, you want only positive values from the object and omit all negative once, how you'll do it? &lt;/p&gt;

&lt;p&gt;Before going further, I would like to welcome you to a new episode of series call Javascript Useful Snippets. In this series, I'm sharing some shortcodes and useful functions that can let you make your code faster and neat. So, if you haven't read my previous episodes' articles please check it out &lt;a href="https://dev.to/rajnishkatharotiya"&gt;here&lt;/a&gt; or else stay tuned till the end to learn something new 😋 .&lt;/p&gt;

&lt;p&gt;&lt;em&gt;Also check out my youtube channel for video tutorials : &lt;a href="https://www.youtube.com/channel/UCvNjso_gPQIPacA6EraoZmg?sub_confirmation=1"&gt;Subscribe me to support 🙏&lt;/a&gt;&lt;/em&gt;&lt;/p&gt;

&lt;h2&gt;
  
  
  How to Omit unwanted key-value pairs from the object?
&lt;/h2&gt;

&lt;p&gt;Guess, you have an object which has values in the data type of &lt;code&gt;number&lt;/code&gt; and &lt;code&gt;string&lt;/code&gt; and you only want numbers. So, in cases like this you can use this custom javascript function called &lt;strong&gt;omitBy()&lt;/strong&gt;. This javascript snippet will take two arguments first one will be your object and second will be your prediction &lt;em&gt;(in our case value should be in number)&lt;/em&gt;. And in result, it'll return an object with only number values with it's key. Let's take a look at the function:-&lt;/p&gt;

&lt;h3&gt;
  
  
  How omitBy() function works ?
&lt;/h3&gt;



&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const omitBy = (obj, fn) =&amp;gt;
  Object.keys(obj)
    .filter(k =&amp;gt; !fn(obj[k], k))
    .reduce((acc, key) =&amp;gt; ((acc[key] = obj[key]), acc), {});
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;



&lt;p&gt;Here In function, I've first created an array of all keys of an object by using &lt;code&gt;Object.keys()&lt;/code&gt; method. Once I have a collection of keys, I've executed the filter method on the array to filter out keys that don't satisfy the given function. And by using a reduced method, I've created a new collection of all keys which returned after filter method execution. So, as output, we will have an object with all key-value pairs which didn't match without given function or except those value which matched with our function.&lt;/p&gt;

&lt;h3&gt;
  
  
  How to use omitBy() function ?
&lt;/h3&gt;



&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;omitBy({ a: 1, b: '2', c: 3 }, x =&amp;gt; typeof x !== 'number');  // Output :- { a: 1, c: 3 }
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;



&lt;p&gt;As we talked above, here I've passed one object which content string and number type of values and out of all we want only those pair which content number values. So, I've added function in the second argument which checks if &lt;code&gt;type of x&lt;/code&gt; shouldn't be number. So, in return as we see we have objects with omitted pairs by a given function.&lt;/p&gt;

&lt;p&gt;This, helped me a lot to optimize objects before passing down to trees in development. So, I thought to share it with you guys too. I hope you liked my explanation (if yes, hit like  ❤️ button ) and if you found it informative then do follow from &lt;a href="https://dev.to/rajnishkatharotiya"&gt;here&lt;/a&gt; because I'll learn and share every day.😋&lt;/p&gt;

&lt;p&gt;Also follow/subscribe me on my social media account to connect with me : &lt;a href="https://twitter.com/RajnishK00"&gt;twitter&lt;/a&gt;, &lt;a href="https://www.youtube.com/channel/UCvNjso_gPQIPacA6EraoZmg?sub_confirmation=1"&gt;youtube&lt;/a&gt;&lt;/p&gt;

</description>
      <category>javascript</category>
      <category>codenewbie</category>
      <category>node</category>
      <category>webdev</category>
    </item>
    <item>
      <title>Best practice to handle input change requests with Google Custom Search</title>
      <dc:creator>Rajnish Katharotiya</dc:creator>
      <pubDate>Wed, 13 May 2020 12:01:41 +0000</pubDate>
      <link>https://dev.to/rajnishkatharotiya/best-practice-to-handle-input-change-requests-with-google-custom-search-1eh0</link>
      <guid>https://dev.to/rajnishkatharotiya/best-practice-to-handle-input-change-requests-with-google-custom-search-1eh0</guid>
      <description>&lt;p&gt;&lt;em&gt;Photo by &lt;a href="https://unsplash.com/@benchaccounting?utm_source=unsplash&amp;amp;utm_medium=referral&amp;amp;utm_content=creditCopyText" rel="noopener noreferrer"&gt;Bench Accounting&lt;/a&gt; on &lt;a href="https://unsplash.com/s/photos/typing-girl?utm_source=unsplash&amp;amp;utm_medium=referral&amp;amp;utm_content=creditCopyText" rel="noopener noreferrer"&gt;Unsplash&lt;/a&gt;&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;In many projects, we would have search input that returns a list (via any external APIs) of data related to the keyword you are entering into the input. so, what's your way to request continuous data from the same end-point?&lt;/p&gt;

&lt;p&gt;Before going further, Let me introduce myself. I'm a javascript developer and learner. here, I'm sharing some shortcodes and useful functions that can let you make your code faster and neat. So, if you haven't read my previous episodes' articles please check it out &lt;a href="https://dev.to/rajnishkatharotiya"&gt;here&lt;/a&gt; or else stay tuned till the end to learn something new 😋 .&lt;/p&gt;

&lt;p&gt;Well, let's see one normal example to google search anything on input change. And display it into list below. &lt;em&gt;( in many cases we list out those items below input )&lt;/em&gt; Here's I've given HTML and JS code with the result.&lt;/p&gt;

&lt;h3&gt;
  
  
  index.html
&lt;/h3&gt;

&lt;p&gt;In HTML, I've just defined one input to take value from the user and passed it &lt;code&gt;searchOnGoogle&lt;/code&gt; function. And defined one unordered list element to list out results after a query from the server. Also with that, I've imported Axios Library to make Http requests from the browser &lt;em&gt;( read more about it from &lt;a href="https://github.com/axios/axios" rel="noopener noreferrer"&gt;here&lt;/a&gt; )&lt;/em&gt;.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;lt;!DOCTYPE html&amp;gt;
&amp;lt;html lang="en"&amp;gt;
&amp;lt;head&amp;gt;
  &amp;lt;meta charset="UTF-8"&amp;gt;
  &amp;lt;meta name="viewport" content="width=device-width, initial-scale=1.0"&amp;gt;
  &amp;lt;script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"&amp;gt;&amp;lt;/script&amp;gt;
  &amp;lt;title&amp;gt;Best practice - search input&amp;lt;/title&amp;gt;
&amp;lt;/head&amp;gt;
&amp;lt;body&amp;gt;

    &amp;lt;input type="text" name="searchInput" placeholder="Google anything..." oninput="searchOnGoogle(this.value)"&amp;gt;
    &amp;lt;ul id="result-list"&amp;gt;&amp;lt;/ul&amp;gt;

    &amp;lt;script src="https://code.jquery.com/jquery-1.12.4.min.js"&amp;gt;&amp;lt;/script&amp;gt;
    &amp;lt;script src="./index.js"&amp;gt;&amp;lt;/script&amp;gt;
&amp;lt;/body&amp;gt;
&amp;lt;/html&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;h3&gt;
  
  
  index.js
&lt;/h3&gt;

&lt;p&gt;In Javascript, I've defined &lt;code&gt;searchOnGoogle&lt;/code&gt; function to make requests on google search engine with the user's query. &lt;em&gt;( You read more about google search API form &lt;a href="https://developers.google.com/custom-search/v1/using_rest" rel="noopener noreferrer"&gt;here&lt;/a&gt; )&lt;/em&gt;. Where, I've used Axios library to make https request via get method. And in response I've set all received items into our unordered result list element.&lt;br&gt;
&lt;/p&gt;
&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;function searchOnGoogle(query) {

   const GoogleAPIKey = "YOUR_GOOGLE_API_KEY"
   const SearchEngine = "YOUR_SEARCH_ENGINE_KEY"

    const RequestURL = `https://www.googleapis.com/customsearch/v1?key=${GoogleAPIKey}&amp;amp;cx=${SearchEngine}`

    const ResultList = $("#result-list");
    ResultList.empty();
    // Make a request for a user with a given Query
    axios.get(`${RequestURL}&amp;amp;q=${query}`)
    .then(({ data = {} }) =&amp;gt; {
        if(data.items){
            data.items.map(({ title }) =&amp;gt; ResultList.append(`&amp;lt;li&amp;gt;${title}&amp;lt;/li&amp;gt;`))
        }
    })
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;h3&gt;
  
  
  Result
&lt;/h3&gt;

&lt;p&gt;Here, I've search a word with 9 characters from input and you can see network besides it which is triggering API calls on google search on each character input.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fi%2Fvjd9kl0c9nl14otb0fua.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fi%2Fvjd9kl0c9nl14otb0fua.png" alt="google-custom-search" width="800" height="374"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;In the above scenario, guess user/ourselves type input like this!! -- which will crash our normal server and exceed limit for free google search. 🤷‍♂️ &lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fi%2Fvtu20vpunhh8l74h9wzw.gif" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fi%2Fvtu20vpunhh8l74h9wzw.gif" alt="speedy_typing_computer" width="500" height="278"&gt;&lt;/a&gt;&lt;/p&gt;
&lt;/blockquote&gt;
&lt;h2&gt;
  
  
  So, what's a better way to request data on input change?
&lt;/h2&gt;
&lt;h3&gt;
  
  
  index.js
&lt;/h3&gt;

&lt;p&gt;Here is one solution, request cancellation ( abort controller for many other request handlers). With Axios, we can create cancel token and for individual request and pass it to it. So, whenever we want to cancel that request while it's in the &lt;em&gt;pending state&lt;/em&gt; we need to just execute cancel token.&lt;br&gt;
&lt;/p&gt;
&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;let cache = [];
const cancel = [];

function searchOnGoogle(query) {

   const GoogleAPIKey = "YOUR_GOOGLE_API_KEY"
   const SearchEngine = "YOUR_SEARCH_ENGINE_KEY"

    const RequestURL = `https://www.googleapis.com/customsearch/v1?key=${GoogleAPIKey}&amp;amp;cx=${SearchEngine}`

    // Check if current url is in cache and execute abort controller via respective cancel tolken 
    // Or else pushed into cache array for next requestes
        if (cache.indexOf(RequestURL) !== -1) {
            const controller = cancel.filter(i =&amp;gt; i.url === RequestURL);
            controller.map(item =&amp;gt; item.c());
        } else {
            cache.push(RequestURL);
        }

        const ResultList = $("#result-list");
        ResultList.empty();

        // Make a request for a user with a given Query 
        // Create and added cancel token to abort request anytime.
        const cancelToken = new axios.CancelToken(((c) =&amp;gt; {
            cancel.push({ url: RequestURL, c });
        }));   
        axios.get(`${RequestURL}&amp;amp;q=${query}`, { cancelToken })
        .then(({ data = {} }) =&amp;gt; {
            if(data.items){
                data.items.map(({ title }) =&amp;gt; ResultList.append(`&amp;lt;li&amp;gt;${title}&amp;lt;/li&amp;gt;`))
            }
        })
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;


&lt;p&gt;In our case, I've created to empty collection in global scope; where one is to store all request URLs ( as caching ) and another one is to store all cancel tokens with request URLs. And whenever, user change value in input function will first check if we have the same URL in a cache, find it's cancel controller from cancel collection and execute it &lt;em&gt;( in our case URL will be always same )&lt;/em&gt; otherwise, just store it into a cache. &lt;/p&gt;

&lt;p&gt;And before requesting results through Axios, I'm creating cancel token for upcoming requests and in callback stored it into our cancel collection for next request use. And passed cancelToken to it's option of get method as second argument. that's it! ( you can read more about in detail from &lt;a href="https://github.com/axios/axios#cancellation" rel="noopener noreferrer"&gt;here&lt;/a&gt;. ) &lt;/p&gt;
&lt;h4&gt;
  
  
  Now, let's see a difference?
&lt;/h4&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fi%2F3j5f8yjvchua9b35lpek.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fi%2F3j5f8yjvchua9b35lpek.png" alt="axios-request-call" width="800" height="374"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Did you figure it out right? As you see in-network when I was entering 9 characters, it requests each time on google search with updated queries but in this case as soon as a new request being made my all previous pending request canceled and stoped from hitting server unwantedly. So, your server will never know about those previous 8 requests. &lt;/p&gt;


&lt;div class="ltag-github-readme-tag"&gt;
  &lt;div class="readme-overview"&gt;
    &lt;h2&gt;
      &lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev.to%2Fassets%2Fgithub-logo-5a155e1f9a670af7944dd5e12375bc76ed542ea80224905ecaf878b9157cdefc.svg" alt="GitHub logo"&gt;
      &lt;a href="https://github.com/RajnishKatharotiya" rel="noopener noreferrer"&gt;
        RajnishKatharotiya
      &lt;/a&gt; / &lt;a href="https://github.com/RajnishKatharotiya/google-search-input" rel="noopener noreferrer"&gt;
        google-search-input
      &lt;/a&gt;
    &lt;/h2&gt;
    &lt;h3&gt;
      It's google custom search input, were I've tired to explain better way to handle request calling on change of input.
    &lt;/h3&gt;
  &lt;/div&gt;
&lt;/div&gt;



&lt;p&gt;This was all about Axios request handler, but if you are using any other one - I'm sure it'll have an abort controller for the same. &lt;em&gt;( let me know in a comment if you find any difficulty for finding it )&lt;/em&gt; &lt;/p&gt;

&lt;p&gt;I found it one of the better ways to handle search input requests. so, I thought to share it with you guys too. I hope you liked my explanation (if yes, hit like  ❤️ button ) and if you found it informative then do follow from &lt;a href="https://dev.to/rajnishkatharotiya"&gt;here&lt;/a&gt; because I'll learn and share every day.😋&lt;/p&gt;

&lt;p&gt;Also follow/subscribe me on my social media account to connect with me : &lt;br&gt;
👨‍💻  &lt;a href="https://twitter.com/RajnishK00" rel="noopener noreferrer"&gt;twitter&lt;/a&gt;, &lt;br&gt;
👨‍💻  &lt;a href="https://www.youtube.com/channel/UCvNjso_gPQIPacA6EraoZmg" rel="noopener noreferrer"&gt;youtube&lt;/a&gt;&lt;/p&gt;

</description>
      <category>javascript</category>
      <category>codenewbie</category>
      <category>productivity</category>
      <category>react</category>
    </item>
    <item>
      <title>How to execute functions via pipeline? </title>
      <dc:creator>Rajnish Katharotiya</dc:creator>
      <pubDate>Sat, 09 May 2020 10:50:52 +0000</pubDate>
      <link>https://dev.to/rajnishkatharotiya/how-to-execute-functions-via-pipeline-38g8</link>
      <guid>https://dev.to/rajnishkatharotiya/how-to-execute-functions-via-pipeline-38g8</guid>
      <description>&lt;p&gt;&lt;em&gt;Photo by &lt;a href="https://unsplash.com/@vantaymedia?utm_source=unsplash&amp;amp;utm_medium=referral&amp;amp;utm_content=creditCopyText"&gt;Van Tay Media&lt;/a&gt; on &lt;a href="https://unsplash.com/s/photos/girl-computer?utm_source=unsplash&amp;amp;utm_medium=referral&amp;amp;utm_content=creditCopyText"&gt;Unsplash&lt;/a&gt;&lt;/em&gt;&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;Guess we have three functions, where one's result is being passed as second's input and so on. In this scenario how you will call all those functions?  &lt;em&gt;( Share your thoughts on possible ways by commenting here 🤗  )&lt;/em&gt;&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;Before going further, I would like to welcome you to a new episode of series call Javascript Useful Snippets. In this series, I'm sharing some shortcodes and useful functions that can let you make your code faster and neat. So, if you haven't read my previous episodes' articles please check it out &lt;a href="https://dev.to/rajnishkatharotiya"&gt;here&lt;/a&gt; or else stay tuned till the end to learn something new 😋 .&lt;/p&gt;

&lt;p&gt;To call all functions in series or one by one, I've defined one simple function called &lt;strong&gt;pipe()&lt;/strong&gt; which will take all functions as arguments in the same order of execution. And in return, it'll trigger left-to-right all functions in series by passing left one's result value to the right one's argument. Let me make it easy for you to explaining the snippet itself.&lt;/p&gt;

&lt;h2&gt;
  
  
  How pipe() function works ?
&lt;/h2&gt;



&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const pipe = (...fns) =&amp;gt; fns.reduce((fn, g) =&amp;gt; (...args) =&amp;gt; g(fn(...args)));
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;



&lt;p&gt;As first, i've stored all functions arguments into array called fns by using spreading operator &lt;em&gt;( it's an concept of ES6 if you new to this word please check &lt;a href="https://youtu.be/Z5FxVKRfocw"&gt;this&lt;/a&gt; first to learn in detail )&lt;/em&gt; and in return i've called &lt;a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce"&gt;reduce method&lt;/a&gt; of array to execute every functions one by one and pass results one to another. And for same i've used again spreading operator to clone all results and passed it to current function. Let's use to know more it.&lt;/p&gt;

&lt;h2&gt;
  
  
  How to use pipe() function ?
&lt;/h2&gt;



&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const add = (x, y) =&amp;gt; x + y
const square = (x) =&amp;gt; x * x
const display = (x) =&amp;gt; console.log(x)
const addNSquare = pipe(add, square, display);  

addNSquare(6,5)   // 121 in console
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;



&lt;p&gt;Here, I've first defined three functions to add a number, to square number, and just display number into the console. where I needed to pass add the result as a square argument and square result to display argument.  So next, I've defined a new function using pipe function and passed all three functions as an argument in the same order of execution I want. Now, I can call addNSquare() function with two values and it'll do it's the best job by executing all three functions in the order I passed functions as arguments.&lt;/p&gt;

&lt;p&gt;&lt;iframe width="710" height="399" src="https://www.youtube.com/embed/zRW1-SfBvWE"&gt;
&lt;/iframe&gt;
&lt;/p&gt;

&lt;p&gt;This snippet helped me to call multi functions in series at many scenarios, so, I thought to share it with you guys too. I hope you liked my explanation (if yes, hit like  ❤️ button ) and if you found it informative then do follow from &lt;a href="https://dev.to/rajnishkatharotiya"&gt;here&lt;/a&gt; because I'll learn and share every day.😋&lt;/p&gt;

&lt;p&gt;Also follow/subscribe me on my social media account to connect with me : &lt;a href="https://twitter.com/RajnishK00"&gt;twitter&lt;/a&gt;, &lt;a href="https://www.youtube.com/channel/UCvNjso_gPQIPacA6EraoZmg"&gt;youtube&lt;/a&gt;&lt;/p&gt;

</description>
      <category>javascript</category>
      <category>webdev</category>
      <category>codenewbie</category>
      <category>productivity</category>
    </item>
    <item>
      <title>Call function only when a value passed validation in javascript </title>
      <dc:creator>Rajnish Katharotiya</dc:creator>
      <pubDate>Wed, 06 May 2020 12:03:40 +0000</pubDate>
      <link>https://dev.to/rajnishkatharotiya/call-function-only-when-a-value-passed-validation-in-javascript-2pid</link>
      <guid>https://dev.to/rajnishkatharotiya/call-function-only-when-a-value-passed-validation-in-javascript-2pid</guid>
      <description>&lt;blockquote&gt;
&lt;p&gt;In the normal app, we always came across to function call only if one function returns positive or desired value. Yes? if yes, comment me on how you'd achieve it? 🤗&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;Before going further, I would like to welcome you to a new episode of series call Javascript Useful Snippets. In this series, I'm sharing some shortcodes and useful functions that can let you make your code faster and neat. So, if you haven't read my previous episodes articles please check it out &lt;a href="https://dev.to/rajnishkatharotiya"&gt;here&lt;/a&gt; or else stay tuned till the end to learn something new 😋 .&lt;/p&gt;

&lt;p&gt;I hope you have shared your answers in a comment. Well, mine is, I've defined one function called &lt;em&gt;when()&lt;/em&gt;. This method will take two arguments one will be prediction function and another will be a function ( which needs to call after ). &lt;/p&gt;

&lt;h2&gt;
  
  
  How does this when() function works?
&lt;/h2&gt;



&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const when = (pred, whenTrue) =&amp;gt; x =&amp;gt; (pred(x) ? whenTrue(x) : x);
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;



&lt;p&gt;Here, as you see we have passed two arguments, prediction ( as pred ) and function ( as whenTrue ) in first arguments list. Before explaining further let me clerify one concept called carried function.&lt;/p&gt;

&lt;h3&gt;
  
  
  What is carried function?
&lt;/h3&gt;

&lt;p&gt;It's a way to call multi-functions in one call. Let me provide one example, guess you want to add two numbers...&lt;/p&gt;

&lt;h4&gt;
  
  
  adding numbers:
&lt;/h4&gt;



&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const add = (a, b) =&amp;gt; a + b;
add(3, 2) // 5
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;



&lt;h4&gt;
  
  
  adding numbers in a carried way :
&lt;/h4&gt;



&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const add = a =&amp;gt; (b =&amp;gt; a+b);
const add3  = add(3)
add3(2) //5
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;



&lt;p&gt;&lt;em&gt;which means we are simply calling a function inside a function or returning function inside function&lt;/em&gt; let's see a normal way of doing it is:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const add = function (a) {
  return function (b) {
    return a + b
  }
}
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;



&lt;p&gt;Now, you have an idea about carried function syntex &lt;em&gt;( feel free to comment if it's unclear )&lt;/em&gt; you can see I've defined when as a carried function which means it'll pass when function call parameters as first arguments list and call of this function will be passed as second argument list &lt;em&gt;( explain more clearly in function usage section )&lt;/em&gt; and return of function, I've called &lt;code&gt;pred&lt;/code&gt; function with an argument &lt;code&gt;x&lt;/code&gt; and checked if it's true then returning &lt;code&gt;whenTrue(x)&lt;/code&gt; ( callback/after function ) otherwise &lt;code&gt;x&lt;/code&gt; itself is returned. Let's use it with one example.&lt;/p&gt;

&lt;h2&gt;
  
  
  How to use When() function ?
&lt;/h2&gt;



&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const divideNumber = when(x =&amp;gt; x % 2 === 0, x =&amp;gt; x / 2);
divideNumber(4); // 2
divideNumber(3); // 3
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;



&lt;p&gt;So, here i've first difined one function by using when() to divide integer by two if it's dividable with two &lt;em&gt;( means it should return integer only after dividation )&lt;/em&gt; and when i passed first value, it's returing value after divition it but in case of secound value it's returing same as output.&lt;/p&gt;

&lt;p&gt;&lt;iframe width="710" height="399" src="https://www.youtube.com/embed/eOWCLuBC33M"&gt;
&lt;/iframe&gt;
&lt;/p&gt;

&lt;p&gt;I found When() function useful to validate value before passing it to other functions. So, I thought to share it with you too. I hope you liked my explanation (if yes, hit like  ❤️ button ) and if you found it informative then do follow from &lt;a href="https://dev.to/rajnishkatharotiya"&gt;here&lt;/a&gt; because I'll learn and share every day.😋&lt;/p&gt;

&lt;p&gt;Also follow/subscribe me on my social media account to connect with me : &lt;a href="https://twitter.com/RajnishK00"&gt;twitter&lt;/a&gt;, &lt;a href="https://www.youtube.com/channel/UCvNjso_gPQIPacA6EraoZmg"&gt;youtube&lt;/a&gt;&lt;/p&gt;

</description>
      <category>javascript</category>
      <category>productivity</category>
      <category>codenewbie</category>
      <category>codequality</category>
    </item>
    <item>
      <title>Select a nested value from the object in javascript</title>
      <dc:creator>Rajnish Katharotiya</dc:creator>
      <pubDate>Fri, 01 May 2020 13:14:09 +0000</pubDate>
      <link>https://dev.to/rajnishkatharotiya/select-a-nested-value-from-the-object-in-javascript-2fjd</link>
      <guid>https://dev.to/rajnishkatharotiya/select-a-nested-value-from-the-object-in-javascript-2fjd</guid>
      <description>&lt;p&gt;Selecting a nested value from an object is a common thing for any javascript application, and when you do deep nesting selection like (user.profile.address.city) it's risky and increases chances of throwing an exception if any one node is undefined which will terminate your process and break page with a white screen. So, what you'd for a solution? ( 🤠 please leave it in comment box ).&lt;/p&gt;

&lt;p&gt;Before going further, I would like to welcome you to a new episode of series call &lt;em&gt;Javascript Useful Snippets&lt;/em&gt;. In this series, I'm sharing some shortcodes and useful functions that can let you make your code faster and neat.  So, if you haven't read my previous episodes &lt;a href="https://dev.to/rajnishkatharotiya"&gt;articles&lt;/a&gt; please check it out here or else stay tuned till the end to learn something new 😋 .&lt;/p&gt;

&lt;p&gt;Well, there are various ways to prevent exceptions, let me write some of popular once here:-&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;&lt;code&gt;user &amp;amp;&amp;amp; user.profile &amp;amp;&amp;amp; user.profile.address &amp;amp;&amp;amp; user.profile.address.&lt;/code&gt;&lt;/li&gt;
&lt;li&gt;&lt;code&gt;user?.profile?.address?.city&lt;/code&gt;&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Maybe to deal with it, the most common way is the first one. But recently a new operator introduced to handle it in a better way is called operational Channing operator &lt;em&gt;(?. - you can read it more on &lt;a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Optional_chaining"&gt;here&lt;/a&gt; )&lt;/em&gt; So, this two can make it little easier to handle nesting selection. But I think I found one much better function to handle it. &lt;em&gt;( excited? 😀 - stay tuned if yes )&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;get(), this function has two types of argument one is an object of records, and the rest are strings &lt;em&gt;(like this "profile.address.city")&lt;/em&gt; to selection from an object. So, in return, you will receive a collection of selected values.&lt;/p&gt;

&lt;h2&gt;
  
  
  How does this get() works?
&lt;/h2&gt;



&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const get = (obj, ...selectors) =&amp;gt;
  [...selectors].map(s =&amp;gt;
    s
      .replace(/\[([^\[\]]*)\]/g, '.$1.')
      .split('.')
      .filter(t =&amp;gt; t !== '')
      .reduce((prev, cur) =&amp;gt; prev &amp;amp;&amp;amp; prev[cur], obj)
  );

&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;



&lt;p&gt;As mentioned above, the first argument will be the object and rest argument I've stored into &lt;code&gt;selectors&lt;/code&gt; with the use of spreading operator &lt;em&gt;( it's a concept to clone object/array - find out in more detail from &lt;a href="https://youtu.be/Z5FxVKRfocw"&gt;here&lt;/a&gt; )&lt;/em&gt; and stored it into an array. And in return of this function, I've used a map method to select the individual record and with that first, I've replaced regex match string with spinal tap case operator &lt;em&gt;( please find a detailed explanation from &lt;a href="https://www.freecodecamp.org/forum/t/spinal-tap-case-operator/56148"&gt;here&lt;/a&gt; )&lt;/em&gt; then second used split method to divide sting from "." which will return an array of strings, so in the third step filtered all empty record form collection and in the last step, by using reduce method I'm selecting values from value until I reach to the last location. And using a double end operator (&amp;amp;&amp;amp;) to prevent exception like if I don't any result from the second step then it'll make it &lt;code&gt;undefined&lt;/code&gt; from there and stop looking for further node.&lt;/p&gt;

&lt;h2&gt;
  
  
  How to use get() ?
&lt;/h2&gt;



&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const obj = { 
  profile : { user : { name: "xyz", surname: "abc" }}, 
  relations: [ { name: 'one' }, { name: 'two' } ] 
};
get(obj, 'profile.user.name', 'relations[0]', 'relations[2].name'); 
// ['xyz', { name: 'one' }, undefined]
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;



&lt;p&gt;So, as you see 2-4 arguments are differents selctors i've used here while 4th selector expect name from second indexed data of relations (relations[2]) whereas relation collection doesn't have second index at all with data so in result get function stop selection of name and just throw undefined without error. &lt;/p&gt;

&lt;p&gt;&lt;iframe width="710" height="399" src="https://www.youtube.com/embed/xQZWsCQYxwk"&gt;
&lt;/iframe&gt;
&lt;/p&gt;

&lt;p&gt;I found this function very useful while selecting from deep nested object especially with uncertain nodes in the object. So, I thought to share it with you too. I hope you liked my explanation (if yes, hit like  ❤️ button ) and if you found it informative then do follow from &lt;a href="https://dev.to/rajnishkatharotiya"&gt;here&lt;/a&gt; because I'll learn and share every day.😋&lt;/p&gt;

&lt;p&gt;Also follow/subscribe me on my social media account to connect with me : &lt;a href="https://twitter.com/RajnishK00"&gt;twitter&lt;/a&gt;, &lt;a href="https://www.youtube.com/channel/UCvNjso_gPQIPacA6EraoZmg"&gt;youtube&lt;/a&gt;&lt;/p&gt;

</description>
      <category>webdev</category>
      <category>javascript</category>
      <category>codenewbie</category>
      <category>productivity</category>
    </item>
    <item>
      <title>Pick desired key-value pair from an object </title>
      <dc:creator>Rajnish Katharotiya</dc:creator>
      <pubDate>Tue, 28 Apr 2020 12:12:27 +0000</pubDate>
      <link>https://dev.to/rajnishkatharotiya/pick-desired-key-value-pair-from-an-object-48aa</link>
      <guid>https://dev.to/rajnishkatharotiya/pick-desired-key-value-pair-from-an-object-48aa</guid>
      <description>&lt;blockquote&gt;
&lt;p&gt;It's very common that in development we needed only a few key-value pairs from an object and still, we use the whole object or we create a new one with copy-pasting key-values from one to another. What's your solution to it?&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;Before going further, I would like to welcome you to a new episode of series call &lt;em&gt;Javascript Useful Snippets&lt;/em&gt;. In this series, I'm sharing some shortcodes and useful functions that can let you make your code faster and neat.  So, if you haven't read my previous episodes &lt;a href="https://dev.to/rajnishkatharotiya"&gt;articles&lt;/a&gt; please check it out here or else stay tuned till the end to learn something new 😋 .&lt;/p&gt;

&lt;p&gt;What if you can just have those key-value pair which you needed without doing the above-mentioned things! Well, I've defined one function for it called pick(). This function takes two arguments where the first one will object &lt;em&gt;(which we are filtering)&lt;/em&gt; and second will be a collection of key names which we want to extract from a given object. As a result, it'll return only those pairs with key names you passed.  &lt;/p&gt;

&lt;h2&gt;
  
  
  How do this pick() works?
&lt;/h2&gt;



&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const pick = (obj, arr) =&amp;gt;
  arr.reduce((acc, record) =&amp;gt; (record in obj &amp;amp;&amp;amp; (acc[record] = obj[record]), acc), {});
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;



&lt;p&gt;As mentioned above it'll take two arguments as parameters and call reduce method &lt;em&gt;( reduce method can be used to eliminate unwanted records or create a new type of data with some operations, you can read about it more from &lt;a href="https://www.w3schools.com/jsref/jsref_reduce.asp"&gt;here&lt;/a&gt; )&lt;/em&gt; on the collection we passed as second params, inside reduce method - I've first validated if given key includes into an object then store it into acc object as key and assigned value after selecting it from a given object. So, in return, you will have an object of key-value pairs of keys you provided form your provided object. Let's pass some values and try it ourselves...&lt;/p&gt;

&lt;h2&gt;
  
  
  How to use pick() ?
&lt;/h2&gt;



&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;pick({ a: '1', b: '2', c: '3' }, ['a', 'c']);   // { 'a': 1, 'c': 3 }
pick({ a: 1, b: '2', c: 3 }, ['x', 'c']);   // { 'c': 3 }
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;



&lt;p&gt;In the first call, I've passed an object with a collection of a key that includes inside objects and received relative pairs to those keys in a result object. While in next call I've passed "x" &lt;em&gt;( knowingly to check function capability)&lt;/em&gt; so, in return I've received only those pair which includes the inside object. That means, with this function you can easily extract your desired pair from an object in no time and if any key doesn't exist then it'll skip without any exceptions.&lt;/p&gt;

&lt;p&gt;&lt;iframe width="710" height="399" src="https://www.youtube.com/embed/NMau19gGdfs"&gt;
&lt;/iframe&gt;
&lt;/p&gt;

&lt;p&gt;At many places in a single app, we won't need the whole objects still we pass to child-to-child without filtering it &lt;em&gt;(especially in technology like react.js)&lt;/em&gt; which can affect our app performance. I think this can help you in with that, so I shared it with you here. I hope you liked my explanation (if yes, hit like  ❤️ button ) and if you found it informative then do follow from &lt;a href="https://dev.to/rajnishkatharotiya"&gt;here&lt;/a&gt; because I'll learn and share every day.😋&lt;/p&gt;

&lt;p&gt;Also follow/subscribe me on my social media account to connect with me : &lt;a href="https://twitter.com/RajnishK00"&gt;twitter&lt;/a&gt;, &lt;a href="https://www.youtube.com/channel/UCvNjso_gPQIPacA6EraoZmg"&gt;youtube&lt;/a&gt;&lt;/p&gt;

</description>
      <category>javascript</category>
      <category>webdev</category>
      <category>productivity</category>
      <category>codenewbie</category>
    </item>
    <item>
      <title>Fetch query data from URL using javascript</title>
      <dc:creator>Rajnish Katharotiya</dc:creator>
      <pubDate>Mon, 27 Apr 2020 14:47:38 +0000</pubDate>
      <link>https://dev.to/rajnishkatharotiya/fetch-query-data-from-url-using-javascript-1853</link>
      <guid>https://dev.to/rajnishkatharotiya/fetch-query-data-from-url-using-javascript-1853</guid>
      <description>&lt;p&gt;&lt;em&gt;Photo by &lt;a href="https://unsplash.com/@timmykp?utm_source=unsplash&amp;amp;utm_medium=referral&amp;amp;utm_content=creditCopyText"&gt;Tim van der Kuip&lt;/a&gt; on &lt;a href="https://unsplash.com/s/photos/web-location?utm_source=unsplash&amp;amp;utm_medium=referral&amp;amp;utm_content=creditCopyText"&gt;Unsplash&lt;/a&gt;&lt;/em&gt;&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;Have you ever used the URL's query parameter into a page? I'm sure most of us did, share me in a comment how'd you done it.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;Before going ahead, I would like to welcome you to a new episode of series call &lt;em&gt;Javascript Useful Snippets&lt;/em&gt;. In this series, I'm sharing some shortcodes and useful functions that can let you make your code faster and neat.  So, if you haven't read my previous episodes &lt;a href="https://dev.to/rajnishkatharotiya"&gt;articles&lt;/a&gt; please check it out here or else stay tuned till the end to learn something new 😋 .&lt;/p&gt;

&lt;p&gt;Getting query parameters from URL is not a hard job but if you are writing it all again-n-again then it's bad practice. So in solution, I defined one global function into an app called getUrlParams(). This function takes URL and in output, returns object with key-value pair of parameters &lt;em&gt;( data of URL )&lt;/em&gt; if any consist into URL else returns an empty object.&lt;/p&gt;

&lt;h2&gt;
  
  
  What is inside getUrlParams() ?
&lt;/h2&gt;



&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const getUrlParams = url =&amp;gt; {
  const paramsData = url.match(/([^?=&amp;amp;]+)(=([^&amp;amp;]*))/g) || []        // [ "key=value", "key2=value2"]

  return paramsData.reduce(
    (a, v) =&amp;gt; ((a[v.slice(0, v.indexOf('='))] = v.slice(v.indexOf('=') + 1)), a),
    {}
  );
}
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;



&lt;p&gt;In function first, I used regex (&lt;code&gt;/([^?=&amp;amp;]+)(=([^&amp;amp;]*))/g&lt;/code&gt;) to get an array of data with match() method of string &lt;em&gt;( this method will create a collection of records which match with given string - in our case, it's the regex for &lt;code&gt;key=value&lt;/code&gt; formatted data)&lt;/em&gt; and stored into one constant with fallback value as [].&lt;/p&gt;

&lt;p&gt;Next, By using the reduced method on an extracted collection of data I've created an object with key-value pair. To do that, inside of reduce I'm first finding an index of "=" into each record and from 0 to founded index string; I stored it as key, and after the founded index data; I stored it as the value of that key. In last just returned the whole function's output as a result of this function. &lt;/p&gt;

&lt;h2&gt;
  
  
  How to use getUrlParams() ?
&lt;/h2&gt;



&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;getUrlParams('http://dev.to/page?name=Rajnish&amp;amp;surname=Katharotiya'); // {name: 'Rajnish', surname: 'Katharotiya'}
getUrlParams('dev.to'); // {}
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;



&lt;p&gt;As you have seen, with the first URL input it's returning an object with key-value pair of provided data into the path whereas the next given empty object because location path doesn't have any params present in it.&lt;br&gt;
&lt;iframe width="710" height="399" src="https://www.youtube.com/embed/COPgOrnt0E4"&gt;
&lt;/iframe&gt;
&lt;br&gt;
This function becomes very useful for me wherever I need to extract data from URL just pass it to this and in return, I'll get the organized object without hurdle 😀. So, I thought to share it with you guys too. I hope you liked my explanation ( if yes, please hit like ❤️ button ) and if you learned something new or found informative then hit the follow button too from &lt;a href="https://dev.to/rajnishkatharotiya"&gt;here&lt;/a&gt; to stay updated with me as I'm learning &amp;amp; sharing every day something useful. 😋&lt;/p&gt;

&lt;p&gt;Also follow/subscribe me on my social media account to connect with me : &lt;a href="https://twitter.com/RajnishK00"&gt;twitter&lt;/a&gt;, &lt;a href="https://www.youtube.com/channel/UCvNjso_gPQIPacA6EraoZmg"&gt;youtube&lt;/a&gt;&lt;/p&gt;

</description>
      <category>javascript</category>
      <category>webdev</category>
      <category>codenewbie</category>
      <category>productivity</category>
    </item>
    <item>
      <title>Extract data from document using javascript</title>
      <dc:creator>Rajnish Katharotiya</dc:creator>
      <pubDate>Sun, 26 Apr 2020 12:25:38 +0000</pubDate>
      <link>https://dev.to/rajnishkatharotiya/copy-data-from-image-using-javascript-2ai0</link>
      <guid>https://dev.to/rajnishkatharotiya/copy-data-from-image-using-javascript-2ai0</guid>
      <description>&lt;p&gt;&lt;em&gt;Photo by &lt;a href="https://unsplash.com/@amyhirschi?utm_source=unsplash&amp;amp;utm_medium=referral&amp;amp;utm_content=creditCopyText" rel="noopener noreferrer"&gt;Amy Hirschi&lt;/a&gt; on &lt;a href="https://unsplash.com/s/photos/extract-document-data?utm_source=unsplash&amp;amp;utm_medium=referral&amp;amp;utm_content=creditCopyText" rel="noopener noreferrer"&gt;Unsplash&lt;/a&gt;&lt;/em&gt;&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;Have you ever tried to typed data from the image for creating an excel sheet? Yes, How'd you done that?&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;Before going further welcomes you all to read this blog, I usually write articles about short-codes and some useful javascript functions. These functions can help you to make your code faster and efficient. So, if you haven't read the previous article please check it out from &lt;a href="https://dev.to/rajnishkatharotiya"&gt;here&lt;/a&gt; otherwise stay tuned till the end to learn something new 😀&lt;/p&gt;

&lt;p&gt;When I faced the same situation*(mentioned in the quote above)* a few days ago, I tried to look alternatives and found word called OCR &lt;em&gt;(optical character recognition - it is a technology that involves reading text from paper and translating the images into a form that the computer can manipulate)&lt;/em&gt; then I looked more about integration with javascript and found one easy/shortest way to implement. which I'll share here.&lt;/p&gt;

&lt;p&gt;I hope you have little idea about &lt;a href="https://nodejs.org/en/" rel="noopener noreferrer"&gt;nodejs&lt;/a&gt; and &lt;a href="https://www.npmjs.com/" rel="noopener noreferrer"&gt;NPM&lt;/a&gt;. let's dive in.&lt;/p&gt;

&lt;p&gt;First, we need to create an empty directory and initialize npm from root directory like below:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;npm init
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Once it's done, create one empty file called &lt;code&gt;app.js&lt;/code&gt; for now.&lt;/p&gt;

&lt;h2&gt;
  
  
  So, to make this thing possible I've used some libraries which are:
&lt;/h2&gt;

&lt;h3&gt;
  
  
  1. Express.js
&lt;/h3&gt;

&lt;p&gt;Express is a minimal and flexible Node.js web application framework that provides a robust set of features for web and mobile applications. you can read more from &lt;a href="https://expressjs.com/" rel="noopener noreferrer"&gt;here&lt;/a&gt;&lt;/p&gt;

&lt;h4&gt;
  
  
  Install express by following command
&lt;/h4&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;npm install express --save
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  2. fs
&lt;/h3&gt;

&lt;p&gt;The fs module provides an API for interacting with the file system, it comes with nodejs installation so no need to install individually to use. you can read more in detail from &lt;a href="https://nodejs.org/api/fs.html" rel="noopener noreferrer"&gt;here&lt;/a&gt;&lt;/p&gt;

&lt;h3&gt;
  
  
  3. multer
&lt;/h3&gt;

&lt;p&gt;Multer is a node.js middleware for handling multipart/form-data, which will be used here to upload a file into our app directory. you can read more in detail from &lt;a href="https://www.npmjs.com/package/multer" rel="noopener noreferrer"&gt;here&lt;/a&gt;&lt;/p&gt;

&lt;h4&gt;
  
  
  Install multer by following command
&lt;/h4&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;npm install multer --save
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  4. tesseract.js
&lt;/h3&gt;

&lt;p&gt;This library plays the main role to build this module because tesseract is a javascript library of popular one of &lt;br&gt;
OCR engine called a tesseract. This provides any type of data from images and more, you can read about more on &lt;a href="https://tesseract.projectnaptha.com/" rel="noopener noreferrer"&gt;here&lt;/a&gt; &lt;/p&gt;
&lt;h4&gt;
  
  
  Install tesseract.js by following command
&lt;/h4&gt;


&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;npm install tesseract.js
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;


&lt;p&gt;That's it we are pretty much set up now, let's do some code to make the operation successful 😎. I hope you have an &lt;code&gt;app.js&lt;/code&gt; file created into your root directory.  &lt;/p&gt;
&lt;h2&gt;
  
  
  Creating a view for file upload
&lt;/h2&gt;

&lt;p&gt;Before that, we need a view too. to get a file from a user via file input. So, create one &lt;code&gt;index.ejs&lt;/code&gt; the file inside &lt;code&gt;/views&lt;/code&gt; directory. &lt;em&gt;(EJS is a simple templating language that lets you generate HTML markup with plain JavaScript)&lt;/em&gt; and write code as follow:-&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;lt;!DOCTYPE html&amp;gt;
&amp;lt;html&amp;gt;
    &amp;lt;head&amp;gt;
        &amp;lt;title&amp;gt;OCR Demo&amp;lt;/title&amp;gt;
    &amp;lt;/head&amp;gt;
    &amp;lt;body&amp;gt;
        &amp;lt;h1&amp;gt;Image to PDF&amp;lt;/h1&amp;gt;
        &amp;lt;form action="/upload" method="POST" enctype="multipart/form-data"&amp;gt;
            &amp;lt;input type="file" name="avatar" /&amp;gt;
            &amp;lt;input type="submit" name="submit" /&amp;gt;
        &amp;lt;/form&amp;gt;
    &amp;lt;/body&amp;gt;
&amp;lt;/html&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  Write code for document extraction
&lt;/h2&gt;

&lt;h3&gt;
  
  
  app.js
&lt;/h3&gt;

&lt;h4&gt;
  
  
  1. Import all dependencies
&lt;/h4&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const express = require('express');
const app = express();
const fs = require('fs');
const multer = require('multer');
const { createWorker } = require('tesseract.js');
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h4&gt;
  
  
  2. Initialize tesseract worker and setup logger to monitor the process
&lt;/h4&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const worker = createWorker({
    logger: m =&amp;gt; console.log(m)
});
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h4&gt;
  
  
  3. Setup uploader using multer to upload all files into &lt;code&gt;/uploads&lt;/code&gt; directory.
&lt;/h4&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// Setup storage options to upload file inside upload directoty
const storage = multer.diskStorage({    
    destination: (req, file, cd) =&amp;gt; {
        cd(null, './uploads')
    },
    filename: (req, file, cb) =&amp;gt; {
        cb(null, file.originalname)
    }
});

// Intailized upload with storage options
const upload = multer({ storage }).single('avatar');
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h4&gt;
  
  
  4. Setup view engine to support ejs files render on view and render index.ejs on default route ('/').
&lt;/h4&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;app.set("view engine", "ejs");
app.get('/', (req, res) =&amp;gt; res.render('index'))
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h4&gt;
  
  
  5. Setup upload method, to handle all requests after submitting click from our view.
&lt;/h4&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// Defined API for handle all requests comes on /upload route (or from index's submit btn click)
app.post('/upload', (req, res) =&amp;gt; {

    // Stored file into upload directory
    upload(req, res, err =&amp;gt; {

        // Reading uploaded file from upload directory
        fs.readFile(`./uploads/${req.file.originalname}`, (err, data) =&amp;gt; {

            // Displaying error if anything goes wrong 
            if(err) return console.error("this is error", err);

             // Self execution function to use async await 
              (async () =&amp;gt; {
                // Tesseract worker loaded with langague option
                await worker.load();
                await worker.loadLanguage('eng');
                await worker.initialize('eng');

                // Document extraction by recognize method of Tesseract and console result
                const { data: { text } } = await worker.recognize(data);
                console.log(text);

                // Used getPDF method to genrate pdf and stored it into app directory by using writeFileSync method
                const { data : pdfData } = await worker.getPDF('Tesseract OCR Result');
                fs.writeFileSync(`${req.file.originalname}.pdf`, Buffer.from(pdfData));
                console.log(`Generate PDF: ${req.file.originalname}.pdf`);

                // Respond send to view with result text and terminated worker after porcess complete
                res.send(text)
                await worker.terminate();
              })();
        })
    })
})
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;em&gt;Please read comments in code to understand more about it&lt;/em&gt;&lt;/p&gt;

&lt;h4&gt;
  
  
  6. Define port and initialize the app by using listen() method.
&lt;/h4&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const PORT = 5000;
app.listen(PORT, () =&amp;gt; console.log("App is running on", PORT))
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  Start the app and extract data from a document
&lt;/h2&gt;

&lt;p&gt;From root directory start your app by the following command:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;node index.js
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Now, open &lt;code&gt;http://localhost:5000/&lt;/code&gt; to use your own OCR app. Once you upload and submit your file you will get a result in few seconds till then you can check your terminal to see processing logs. &lt;em&gt;( if you want a more specific type of extraction then there are many more functionalities provided by tesseract like extract data from a particular region, multi-language support.)&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fi%2Ft902zcsc9jaqn63omy60.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fi%2Ft902zcsc9jaqn63omy60.png" alt="extract data from document" width="800" height="450"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;em&gt;Full source code is &lt;a href="https://github.com/RajnishKatharotiya/node-ocr-sample" rel="noopener noreferrer"&gt;here&lt;/a&gt;.&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;&lt;iframe width="710" height="399" src="https://www.youtube.com/embed/LsO1Mvn8M0I"&gt;
&lt;/iframe&gt;
&lt;/p&gt;

&lt;p&gt;This solution really worked for me, it's not very accurate for low-quality images though. So, I thought to share it with you too. I hope you understood my explanation ( if yes, please hit like ❤️ button ) and you learned something new or found informative then hit the follow button too from &lt;a href="https://dev.to/rajnishkatharotiya"&gt;here&lt;/a&gt;. Because I'm sharing every day something useful. 😋&lt;/p&gt;

&lt;p&gt;Also follow/subscribe me on my social media account to connect with me : &lt;a href="https://twitter.com/RajnishK00" rel="noopener noreferrer"&gt;twitter&lt;/a&gt;, &lt;a href="https://www.youtube.com/channel/UCvNjso_gPQIPacA6EraoZmg" rel="noopener noreferrer"&gt;youtube&lt;/a&gt;&lt;/p&gt;

</description>
      <category>javascript</category>
      <category>webdev</category>
      <category>node</category>
      <category>codenewbie</category>
    </item>
    <item>
      <title>Remember frequent input for faster execution of a function in javascript</title>
      <dc:creator>Rajnish Katharotiya</dc:creator>
      <pubDate>Thu, 23 Apr 2020 11:48:58 +0000</pubDate>
      <link>https://dev.to/rajnishkatharotiya/remember-frequent-input-for-faster-execution-of-a-function-in-javascript-3mbc</link>
      <guid>https://dev.to/rajnishkatharotiya/remember-frequent-input-for-faster-execution-of-a-function-in-javascript-3mbc</guid>
      <description>&lt;p&gt;&lt;em&gt;Photo by &lt;a href="https://unsplash.com/@jeshoots?utm_source=unsplash&amp;amp;utm_medium=referral&amp;amp;utm_content=creditCopyText"&gt;JESHOOTS.COM&lt;/a&gt; on &lt;a href="https://unsplash.com/collections/1527221/nerds?utm_source=unsplash&amp;amp;utm_medium=referral&amp;amp;utm_content=creditCopyText"&gt;Unsplash&lt;/a&gt;&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;In every project, we encounter anyone function which will be using frequently into the app or which have the possibility of the same input again-n-again. So, shouldn't we do something to prevent execution if give input already passed before? What you'll do it? ( please comment me down below, will love to get more solutions 😊 ).&lt;/p&gt;

&lt;p&gt;Before moving forward, let me welcome you in a new episode of series called &lt;em&gt;Javascript Useful Snippets&lt;/em&gt;, In this series, I'm sharing shortcodes and useful javascript functions which can help you to make your code more efficient and neat. So, if you haven't read previous articles please check it out &lt;a href="https://dev.to/rajnishkatharotiya"&gt;here&lt;/a&gt; otherwise stay tuned till the end to learn something new 🤩.&lt;/p&gt;

&lt;p&gt;Let's start with a very simple example, assume we have a function to get square of a given number. And we are passing random numbers from 1-10. and number 3 is passed through function five times for execution where on first execution the only system had found out that for input 3 output will be 9 still it'll execution square function and user have to wait unnecessarily four times of execution.&lt;/p&gt;

&lt;p&gt;In this situation, we can use a function called &lt;em&gt;memoize()&lt;/em&gt;, this function will remember input and respective output once it's passed through execution. so, we can save time. Now, let me show you what it does:-&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const memoize = fn =&amp;gt; {
  const cache = new Map();
  const cached = (val) =&amp;gt; {
    return cache.has(val) ? cache.get(val) : cache.set(val, fn.call(this, val)) &amp;amp;&amp;amp; cache.get(val);
  };
  cached.cache = cache;
  return cached;
};
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;



&lt;p&gt;So, here in function, i've created first empty object(cache) through map &lt;em&gt;( new Map() is a constructor to create object to store key-value pair data, you can read it more on &lt;a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map"&gt;here&lt;/a&gt; )&lt;/em&gt; and in next i've created another function called cached, which is using cache object to first validate if given input is stored into it and or not, if yes, return it direct from thier otherwise will execute function and set into cache with output of it. In last, it's just returning cached object with result value.  &lt;/p&gt;

&lt;h3&gt;
  
  
  Let's look it with an example:
&lt;/h3&gt;



&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;  const stringOne = "Hello World";
  const stringTwo = "😎";

  const byteSize = str =&amp;gt; new Blob([str]).size;
  const memoziedByteSize = memoize(byteSize)

  var t0 = performance.now();
  memoziedByteSize(stringOne)
  memoziedByteSize(stringTwo)
  var t1 = performance.now();
  console.log("First time took " + (t1 - t0) + " milliseconds.");

  var t2 = performance.now();
  memoziedByteSize(stringOne)
  memoziedByteSize(stringTwo)
  var t3 = performance.now();
  console.log("Second time took " + (t3 - t2) + " milliseconds.");
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;



&lt;p&gt;In the above example, I've used function to get a byte size of a given string. So first created two string constants and declared byteSize function. Next stored memorized function in new constant(memoziedByteSize) after wrapping operational function with memorize function. &lt;/p&gt;

&lt;p&gt;Next is the execution part, for monitor processing time I've used a function called &lt;em&gt;performance.now()&lt;/em&gt; &lt;em&gt;( it'll return current time, you can read about from &lt;a href="https://developer.mozilla.org/en-US/docs/Web/API/Performance/now"&gt;here&lt;/a&gt; )&lt;/em&gt; before and after the execution and console difference between them. And that same process I've done twice with the same input stings. Let's see what console look like:-&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;  First time took 1.0550000006332994 milliseconds.
  Second time took 0.005000001692678779 milliseconds.
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;



&lt;p&gt;Wow, clearly we can see difference right? So, this one was just a simple execution to get byteSize. but think if it could have complex process then how much time it can save. &lt;em&gt;( for me I had very complex execution and it'd work )&lt;/em&gt;.  This snippet work for me like a charm so, I thought to share it with you too. I hope you liked it ( if yes, hit like ❤️ button ) and I hope you learned something new. if yes? hit &lt;a href="https://dev.to/rajnishkatharotiya"&gt;follow&lt;/a&gt; to learn every day something new.😅&lt;/p&gt;

&lt;p&gt;check video tutorial on: &lt;br&gt;
&lt;iframe width="710" height="399" src="https://www.youtube.com/embed/ce_Ekx5ARCE"&gt;
&lt;/iframe&gt;
&lt;/p&gt;

</description>
      <category>javascript</category>
      <category>react</category>
      <category>webdev</category>
      <category>codenewbie</category>
    </item>
    <item>
      <title>import files without deep nesting relative path in next.js</title>
      <dc:creator>Rajnish Katharotiya</dc:creator>
      <pubDate>Tue, 21 Apr 2020 13:50:31 +0000</pubDate>
      <link>https://dev.to/rajnishkatharotiya/import-files-without-deep-nesting-relative-path-in-next-js-14ed</link>
      <guid>https://dev.to/rajnishkatharotiya/import-files-without-deep-nesting-relative-path-in-next-js-14ed</guid>
      <description>&lt;p&gt;Photo by &lt;a href="https://unsplash.com/@thisisengineering?utm_source=unsplash&amp;amp;utm_medium=referral&amp;amp;utm_content=creditCopyText"&gt;ThisisEngineering RAEng&lt;/a&gt; on &lt;a href="https://unsplash.com/s/photos/stressed-code?utm_source=unsplash&amp;amp;utm_medium=referral&amp;amp;utm_content=creditCopyText"&gt;Unsplash&lt;/a&gt;&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;Well best practices say, you should have widget, utility and shared components individually defined in your app. No hard to do it, but it is a hurdle to import sometimes. &lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;At the beginning, let me explain what I mean by deep nesting relative path in next.js? Assume as defined best practices ( it's standard defined by an expert to make code neater and organized ), we have the following file structure. &lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--QT1fxm_m--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/i/cimtixettknjg76l3kgi.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--QT1fxm_m--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/i/cimtixettknjg76l3kgi.png" alt="Alt Text"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;As we see, I've defined  &lt;code&gt;helper.js&lt;/code&gt;  inside the utility folder. Now, I have a component inside &lt;br&gt;
 &lt;code&gt;/components/widgets/priceTag.js&lt;/code&gt;  which looks like this :&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import React from 'react'
import { toCurrency } from '../../../utils/helper'

const priceTag = ({ text }) =&amp;gt; (
  &amp;lt;p className="price-tag"&amp;gt;
    {toCurrency(text, 'USD', 'en-us')}
  &amp;lt;/p&amp;gt;
)
export default priceTag

&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;



&lt;p&gt;Here, I needed to convert a number into USD currency format with a dollar sign before it. So, I've used toCurrancy which defined into the helper file. &lt;em&gt;( wonder, how I did it? check &lt;a href="https://rajnishkatharotiya.hashnode.dev/convert-numbers-to-desired-currency-format-in-javascript-ck98k4vfe00gscss1wmtnnj96"&gt;this&lt;/a&gt; out to know )&lt;/em&gt; and in order to import it I've used relative path here &lt;em&gt;( like this &lt;code&gt;../../.../utils/helper&lt;/code&gt; )&lt;/em&gt; so, it's it too much to write ?? &lt;em&gt;( i feel it 😅)&lt;/em&gt;&lt;/p&gt;

&lt;h3&gt;
  
  
  What's better way for it ?
&lt;/h3&gt;

&lt;p&gt;well, here module resolver comes in picture. we will basically create an alias name for pointing directory with help of babel config, after implementation of it. we can write out the import statement just like this:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import { toCurrency } from '@utils/helper'
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;



&lt;p&gt;&lt;em&gt;isn't it cool 😎 ?&lt;/em&gt;&lt;/p&gt;

&lt;h3&gt;
  
  
  How to implement it?
&lt;/h3&gt;

&lt;p&gt;We need to Install babel-plugin-module-resolver library first as follow.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;npm install babel-plugin-module-resolver --save-dev
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;



&lt;p&gt;Now Add .babelrc file in the root directory if you haven't &lt;em&gt;( Note- NextJS does not need .babelrc by default. It uses “next/babel” preset to transpile. so, you need to add it as preset. )&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;Here is how my &lt;code&gt;.babelrc&lt;/code&gt; looks like now :&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;{
  "presets": ["next/babel"],
  "plugins": [
    [
        "module-resolver",
        {
            "root": ["."],
            "alias": {
                "@utils": "./utils",   // will connect to all utiliy related functions
                "@components": "./components",  // to all defined components
                "@widgets": "./components/widgets",  //  to all defined widget components
                "@redux": "./redux",  //  redux related files like-  actions, reducers
            }
        }
    ]
  ]
}
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;



&lt;p&gt;I've defined few here as examples but you can add more as you like. and then you can start importing modules using this alias. &lt;/p&gt;

&lt;p&gt;So, I was using this technique many times but I saw one project where importing was defined in the relative path and I had to update it. So, it triggered me to share it with you too. I hope this was helpful to you too. ( if yes, hit like ❤️  button now ). With that, see you soon with something new so stay tuned and hit &lt;a href="https://dev.to/rajnishkatharotiya"&gt;follow&lt;/a&gt; too. 😋&lt;/p&gt;

</description>
      <category>javascript</category>
      <category>react</category>
      <category>codenewbie</category>
      <category>webdev</category>
    </item>
    <item>
      <title>Convert numbers to desired currency format in javascript</title>
      <dc:creator>Rajnish Katharotiya</dc:creator>
      <pubDate>Mon, 20 Apr 2020 14:14:22 +0000</pubDate>
      <link>https://dev.to/rajnishkatharotiya/convert-numbers-to-desired-currency-format-in-javascript-1cpb</link>
      <guid>https://dev.to/rajnishkatharotiya/convert-numbers-to-desired-currency-format-in-javascript-1cpb</guid>
      <description>&lt;p&gt;&lt;em&gt;Photo by &lt;a href="https://unsplash.com/@ggiqueaux?utm_source=unsplash&amp;amp;utm_medium=referral&amp;amp;utm_content=creditCopyText"&gt;Geronimo Giqueaux&lt;/a&gt; on &lt;a href="https://unsplash.com/s/photos/money?utm_source=unsplash&amp;amp;utm_medium=referral&amp;amp;utm_content=creditCopyText"&gt;Unsplash&lt;/a&gt;&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;While building a global eCommerce site we need to take care of price presentation in all possible currency, how you would covert &lt;code&gt;12345678&lt;/code&gt; string to &lt;code&gt;$12,345,678.00 (USD)&lt;/code&gt; or &lt;code&gt;₹12,345,678.00 (INR)&lt;/code&gt;? 🧐&lt;/p&gt;

&lt;p&gt;Before forging ahead, I would like to welcome you in a new episode of series call &lt;em&gt;Javascript Useful Snippets&lt;/em&gt;. In this series, I'm sharing some shortcodes and useful functions that can let you make your code faster and neat.  So, if you haven't read my previous episodes &lt;a href="https://dev.to/rajnishkatharotiya"&gt;articles&lt;/a&gt; please check it out here or else stay tuned till the end to learn something new 😋 .&lt;/p&gt;

&lt;p&gt;Now, Guess we have some numbers and want to show it in US/UK/EU currency in our view. toCurrency() function is good for the job, well this function will take Number, Currency Code, Langauge Code &lt;em&gt;(if you want to convert it into any particular language)&lt;/em&gt; as parameter's arguments and return your desired currency. Now, Let me share you a snippet now:-&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const toCurrency = (number, currency, language = undefined) =&amp;gt;
  Intl.NumberFormat(language, { style: 'currency', currency: currency }).format(number);
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;



&lt;p&gt;As I mentioned, I've taken number, currency, and language &lt;em&gt;( set it undefined as default )&lt;/em&gt; and in return, I've used Intl.NumberFormat to format-number &lt;em&gt;(for your info - this function has a verity of facility and format to convert number &lt;a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/NumberFormat#NumberFormat_instances"&gt;read more&lt;/a&gt; on)&lt;/em&gt;. Here, as the first argument, I've passed language if given or else undefined. and in the second argument passed an object with different options. For currency, I've passed 'currency' as the style and currency code as currency. And once initialize has done I've used format method and gave a number to it. &lt;/p&gt;

&lt;h3&gt;
  
  
  how to use toCurrency() function?
&lt;/h3&gt;



&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;toCurrency(123456.789, 'EUR'); // €123,456.79  | currency: Euro | language: Local
toCurrency(123456.789, 'USD', 'en-us'); // $123,456.79  | currency: US Dollar | language: English (United States)
toCurrency(123456.789, 'USD', 'fa'); // ۱۲۳٬۴۵۶٫۷۹ ؜$ | currency: US Dollar | language: Farsi
toCurrency(322342436423.2435, 'JPY'); // ¥322,342,436,423 | currency: Japanese Yen | language: Local
toCurrency(322342436423.2435, 'JPY', 'fi'); // 322 342 436 423 ¥ | currency: Japanese Yen | language: Finnish
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;



&lt;p&gt;As you see, in the first result I've not sent any language so it set as a local language. Then on the third result, I've passed 'fa'(for Farsi) it converted into Farsi language. And with that, if you see in all results, output contained symbol respective to a given code because we set currency as a style in our function's option. Same as that, there is a bunch of more options available to modify your NumberObject &lt;em&gt;( you can check it from &lt;a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/NumberFormat#NumberFormat_instances"&gt;here&lt;/a&gt; )&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;&lt;iframe width="710" height="399" src="https://www.youtube.com/embed/BvHuwz5pBUI"&gt;
&lt;/iframe&gt;
&lt;/p&gt;

&lt;p&gt;I wanted to present the number in different currency formats, at first I tried third-party libraries. But then I found this amazing function which turned into a snippet for my app. And it's really working like charm. So, I thought to share it with you guys too. I hope you liked ( if yes, hit like ❤️ button ) it and you learn something new. If yes, hit &lt;a href="https://dev.to/rajnishkatharotiya"&gt;follow&lt;/a&gt; to learn something new every day 😅.&lt;/p&gt;

</description>
      <category>javascript</category>
      <category>react</category>
      <category>codequality</category>
      <category>webdev</category>
    </item>
    <item>
      <title>Pause function execution for a certain time in javascript</title>
      <dc:creator>Rajnish Katharotiya</dc:creator>
      <pubDate>Sun, 19 Apr 2020 15:06:33 +0000</pubDate>
      <link>https://dev.to/rajnishkatharotiya/pause-function-execution-for-a-certain-time-in-javascript-9lj</link>
      <guid>https://dev.to/rajnishkatharotiya/pause-function-execution-for-a-certain-time-in-javascript-9lj</guid>
      <description>&lt;p&gt;&lt;em&gt;Photo by &lt;a href="https://unsplash.com/@nesabymakers?utm_source=unsplash&amp;amp;utm_medium=referral&amp;amp;utm_content=creditCopyText" rel="noopener noreferrer"&gt;NESA by Makers&lt;/a&gt; on &lt;a href="https://unsplash.com/s/photos/code?utm_source=unsplash&amp;amp;utm_medium=referral&amp;amp;utm_content=creditCopyText" rel="noopener noreferrer"&gt;Unsplash&lt;/a&gt;&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;Pausing function till one process ends is can be archive in various ways, well for some scenario what if we want to just pause our function for time or I say rest it a little while. how would you do it? 🤔&lt;/p&gt;

&lt;p&gt;On the move, I would like to welcome you in a new episode of &lt;strong&gt;Javascript Useful Snippets&lt;/strong&gt; where I'll share some shortcodes and function which will help you to make your code much efficient and neat. So, if you haven't read my previous episodes (articles) please check it out &lt;a href="https://dev.to/rajnishkatharotiya"&gt;here&lt;/a&gt; or else stay tuned till the end to learn something new 😋 .&lt;/p&gt;

&lt;p&gt;Are you familiar with word Promise? If you are not, I recommend the following post to check. &lt;em&gt;( see you in a bit 🤗 )&lt;/em&gt;&lt;/p&gt;


&lt;div class="ltag__link"&gt;
  &lt;a href="/lydiahallie" class="ltag__link__link"&gt;
    &lt;div class="ltag__link__pic"&gt;
      &lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F198900%2Fd19268b1-6b0b-4530-9889-64fcf0a19d6d.png" alt="lydiahallie"&gt;
    &lt;/div&gt;
  &lt;/a&gt;
  &lt;a href="/lydiahallie/javascript-visualized-promises-async-await-5gke" class="ltag__link__link"&gt;
    &lt;div class="ltag__link__content"&gt;
      &lt;h2&gt;⭐️🎀 JavaScript Visualized: Promises &amp;amp; Async/Await&lt;/h2&gt;
      &lt;h3&gt;Lydia Hallie ・ Apr 14 '20&lt;/h3&gt;
      &lt;div class="ltag__link__taglist"&gt;
        &lt;span class="ltag__link__tag"&gt;#javascript&lt;/span&gt;
        &lt;span class="ltag__link__tag"&gt;#node&lt;/span&gt;
        &lt;span class="ltag__link__tag"&gt;#webdev&lt;/span&gt;
      &lt;/div&gt;
    &lt;/div&gt;
  &lt;/a&gt;
&lt;/div&gt;


&lt;p&gt;Now, I hope you know about the promises. so you'd figured out a way to make the process the waiting until one is not done. But guess you need to pause execution for a certain amount of time by just passing that certain time when you don't have any particular other processes dependent in that function, at those times this &lt;strong&gt;pause()&lt;/strong&gt; function will work like charm.&lt;/p&gt;

&lt;p&gt;The function needs just time(ms) as parameter argument and in return, it will hold execution for that given a time period. Let me share you a snippet now:-&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;

const pause = ms =&amp;gt; new Promise(resolve =&amp;gt; setTimeout(resolve, ms));



&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;Inside a function, I created Promise as mentioned in the above blog &lt;em&gt;( i hope you have read it )&lt;/em&gt;. and just used resolve callback as setTimeout &lt;em&gt;(is a method to delay function for a time)&lt;/em&gt; callback and passed time as the second argument of it. So, resolve will trigger after that given amount of time.  &lt;/p&gt;

&lt;h4&gt;
  
  
  How to use pause() function?
&lt;/h4&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;

async function work() {
  console.log("Pausing execution for 1 second");
  await pause(1000);
  console.log('Resuming execution');
}


&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;Need to create async function, and put pause in await when we call it. So, here i've passed 1000ms inside pause function which will hold execution for one second, as soon as we get success response from our promise it'll move to next execution. &lt;/p&gt;

&lt;p&gt;&lt;em&gt;Here, if anything goes wrong with the function we have put in await then further execution will be auto terminated so be careful to use. ( you can use try .... catch block in such cases ).&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;I was making animation and wanted to add a delay in transition, so I was using setTimeout repeatedly and there I figured to have a function like this to hold my execution for a certain time without hurdles. So, I thought to share it with you too. I hope you learned something, if yes, hit the &lt;a href="https://dev.to/rajnishkatharotiya"&gt;follow button&lt;/a&gt; to learn every day 😅&lt;/p&gt;

</description>
      <category>javascript</category>
      <category>react</category>
      <category>node</category>
      <category>productivity</category>
    </item>
  </channel>
</rss>
