<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Yudhajit Adhikary on Medium]]></title>
        <description><![CDATA[Stories by Yudhajit Adhikary on Medium]]></description>
        <link>https://medium.com/@yudhajitadhikary?source=rss-f54a1f93756b------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*K25785nDLtH4vK6qwgMiDA.jpeg</url>
            <title>Stories by Yudhajit Adhikary on Medium</title>
            <link>https://medium.com/@yudhajitadhikary?source=rss-f54a1f93756b------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 05 Dec 2026 20:34:58 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@yudhajitadhikary/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Intermediate Sorting Algorithm in JavaScript]]></title>
            <link>https://yudhajitadhikary.medium.com/intermediate-sorting-algorithm-in-javascript-3133957c2d26?source=rss-f54a1f93756b------2</link>
            <guid isPermaLink="false">https://medium.com/p/3133957c2d26</guid>
            <category><![CDATA[algorithms]]></category>
            <category><![CDATA[sorting-algorithms]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[pagespeed-performance]]></category>
            <dc:creator><![CDATA[Yudhajit Adhikary]]></dc:creator>
            <pubDate>Thu, 01 May 2025 10:44:22 GMT</pubDate>
            <atom:updated>2025-05-01T11:07:38.391Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qR5RVrQOU7w2I9yrhzCAUg.jpeg" /></figure><p>Hi , in the previous blog we have discussed about elementary search algorithm where we are having some limitation like those don’t scale well , like if we try our bubble sort on an array of 100000 elements , it will take a good amount of time to execute. So we have find some alternative to sort large array quickly . So intermediate sorting algorithm is a family of sorting algorithms that can improve time complexity from O(n) to O(n log n) , but there is few tradeoff between efficiency and simplicity , that is the more efficient algorithms are much less simple and generally take longer to understand , so please be patient and be with me through out the blog so that we can successfully go through the core concept of the intermediate sorting algorithm in javascript .</p><p>So first we will start with <strong>Merge sort</strong>:</p><p>So merge sort is a combination of two things , merging and sorting , it is based on a simple fact that array having 0 or 1 element are always sorted . Merge sort uses this concept of decomposing an array into smaller arrays of 0 or 1 elements , then building up a newly sorted array .</p><p>Now let us how it works , lets see we are having array with elements :</p><p>[ 8,3,5, 4,7,6,1,2] , so in merge sort our first aim will be to segregate the entire array into arrays having single element, then we will be sorting those single element arrays and will merge together to get a sorted array as a final result . The sorting process happen like below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HTXkwduCHchCsGFGkSK6Ug.png" /><figcaption>Sorting process of Merge sort</figcaption></figure><p>Before going to the pseudocode of the merge sort , let’s implement a function responsible for merging two sorted arrays , so if we are having two arrays which are sorted , this helper function should create a new array which is also sorted , and consist of all of the elements in the two input arrays.</p><p>Let’s see the pseudocode to merge two sorted arrays:</p><p>1&gt; Create an empty array , take a look at the smallest values in each input array .</p><p>2&gt; While there are still values we have not looked at,so there we are having two cases , if the value in the first array is smaller than the value in the second array , push the value in the first array into our results and move on to the next value in first array , but if the value in the first array is larger than the value in the second array , push the value in the second array into our results and move on to the next value in the second array. Once we exhaust one array , push in all remaining values from the other array.</p><pre>function merge(arr1, arr2){<br>    let results = [];<br>    let i = 0;<br>    let j = 0;<br>    while(i &lt; arr1.length &amp;&amp; j &lt; arr2.length){<br>        if(arr2[j] &gt; arr1[i]){<br>            results.push(arr1[i]);<br>            i++;<br>        } else {<br>            results.push(arr2[j])<br>            j++;<br>        }<br>    }<br>    while(i &lt; arr1.length) {<br>        results.push(arr1[i])<br>        i++;<br>    }<br>    while(j &lt; arr2.length) {<br>        results.push(arr2[j])<br>        j++;<br>    }<br>    return results;<br>}<br>merge([100,200], [1,2,3,5,6])</pre><p>Let’s see the pseudocode for <strong>Merge Sort</strong> :</p><p>1&gt; Break up the array into halves until we have arrays that are empty or have one element.</p><p>2&gt; Once we have smaller sorted arrays, merge those arrays with other sorted arrays until you are back at the full length of the array.</p><p>3&gt; Once the array has been merged back together , return the merged array .</p><pre>// Merge function from earlier<br>function merge(arr1, arr2){<br>    let results = [];<br>    let i = 0;<br>    let j = 0;<br>    while(i &lt; arr1.length &amp;&amp; j &lt; arr2.length){<br>        if(arr2[j] &gt; arr1[i]){<br>            results.push(arr1[i]);<br>            i++;<br>        } else {<br>            results.push(arr2[j])<br>            j++;<br>        }<br>    }<br>    while(i &lt; arr1.length) {<br>        results.push(arr1[i])<br>        i++;<br>    }<br>    while(j &lt; arr2.length) {<br>        results.push(arr2[j])<br>        j++;<br>    }<br>    return results;<br>}<br><br>// Recrusive Merge Sort<br>function mergeSort(arr){<br>    if(arr.length &lt;= 1) return arr;<br>    let mid = Math.floor(arr.length/2);<br>    let left = mergeSort(arr.slice(0,mid));<br>    let right = mergeSort(arr.slice(mid));<br>    return merge(left, right);<br>}<br><br>mergeSort([10,24,76,73])</pre><p>So we have defined our sorted array merging function called merge , where we are merging two sorted array . merge function is taking two array arr1 and arr2 , here we are defined empty array results , and two integers i and j which are considered as iterator or pointer of first and second array . So we are checking while arr1.length is greater i and arr2.length is greater than j , we will be checking if arr2[j] is greater than arr1[i], we will be pushing arr1[i] on the results array and increment the value of i, else we will be pushing arr2[j] on the results array and increment value of j . If the arr1 is having more elements than arr2 , we will be pushing the the remaining elements of arr1 on the results array but if the arr2 is having more elements than arr1, we will be pushing the remaining elements of arr2 on the results array and lastly we will be returning results value . Now let’s see the function which will implement the sorting of the array , so in the function mergeSort we are first checking if arr.length ≤1 , means if arr is having one element we will just return the array , else we will be storing the value of the middle index of the array in variable called mid , then we are recursively calling the mergeSort function by the dividing the array into 2 halves arr[0] to arr[mid] and arr[mid] to arr[end], we are storing the return value (sorted array ) of those functions on left and right variables respectively . Finally we will be calling merge function to merge left and right array to get the final sorted array as output.</p><p>Now let’s see the big O of mergeSort , So the time complexity of the best case scenario , average case and worst case is <strong>O (n log n)</strong> , and space complexity of the mergeSort is <strong>O(n) </strong>.</p><p>So now our second sorting algorithm is <strong>Quick Sort</strong> :</p><p>Like merge sort, Quick sort exploits the fact that arrays of 0 or 1 elements are always sorted . Quick sort works by selecting one element( called the pivot ) and finding the index where the pivot should end up in the sorted array . Once the pivot is positioned appropriately , quick sort can be applied on either side of the pivot .</p><p>So our first step is to define a pivot helper function , in order to implement quick sort , it’s very useful to first implement a function responsible for arranging elements in an array on either sode of a pivot . Given an array , this helper function should designate an element as the pivot , it should then rearrange elements in the array so that all values less than the pivot are moved to left of the pivot , and all values greater than the pivot are move to the right of the pivot and the order of elements on either side of the pivot doesn’t matter. The helper should do this in place and it should not create a new array and when completed , the helper return the index of the pivot .</p><p>Let’s see how we can pick a pivot , the runtime of quick sort depends in part on how one select the pivot , ideally , the pivot should be chosen so that it’s roughly the median value in the data set you are sorting . For simplicity , we will always choose the pivot to be the first element .</p><p>Pivot Pseudocode:</p><p>It will accept three arguments: an array , a start index and an end index (these can default to 0 and the array length minus 1 respectively). We will taking the pivot element from the start of the array . We will be storing the current pivot index in a variable ( this will keep track of where the pivot should end up ) . We can loop through the array from the start until the end.</p><p>If the pivot is greater than the current element , increment the pivot index variable and then swap the current element with the element at the pivot index. Swap the starting element with the pivot index , return the pivot index.</p><pre>function pivot(arr, start=0, end=arr.length+1){<br>  function swap(array, i, j) {<br>    var temp = array[i];<br>    array[i] = array[j];<br>    array[j] = temp;<br>  }<br><br>  var pivot = arr[start];<br>  var swapIdx = start;<br><br>  for(var i = start + 1; i &lt; arr.length; i++){<br>    if(pivot &gt; arr[i]){<br>      swapIdx++;<br>      swap(arr,swapIdx,i);<br>    }<br>  }<br>  swap(arr,start,swapIdx);<br>  return swapIdx;<br>}<br><br><br>pivot([4,8,2,1,5,7,6,3])<br><br></pre><p>Now let’s work through the code , so our final goal is to select a pivot element , iterate through it and make sure at the end of the iteration , the elements on the left side of the pivot element will be smaller than pivot and elements on the right side of the pivot elements will be greater than pivot element. So we are pushing the array [4,8,2,1,5,7,6,3] in the pivot function.</p><p>In pivot function , we have defined swap function to swap the array elements . then we selected the first element of the array as the pivot element , swapIdx variable will store the pivot index of the array . Now we will be iterating the array from second index till the end of the array using the pointer i . we will checking if pivot element is greater than arr[i] we will be incrementing swapIdx by one and we will swap arr[swapIdx] with arr[i]. Once the iteration is over we will swap arr[start] and arr [swapIdx] and will return the final value of swapIdx. The iteration of the array will go like this :</p><p>[4, 8, 2, 1,5, 7, 6, 3] →[4, 2, 8, 1,5, 7, 6, 3] →[4, 2, 1, 8,5, 7, 6, 3] →[4, 2, 1, 8,5, 7, 6, 3] →[4, 2, 1, 8,5, 7, 6, 3] →[4, 2, 1, 8,5, 7, 6, 3] →[4, 2, 1, 3,5, 7, 6, 8] →[<br> 3, 2, 1, 4,5, 7, 6, 8]. And the return value of the function will be 3.</p><p>Now let’s see the pseudocode of <strong>Quicksort</strong> :</p><p>Call the pivot helper on the array , when the helper returns to us the updated pivot index , recursively call the pivot helper on the subarray to the left of that index , and the subarray to the right of that index . Our base case occurs when you consider a subarray with less than 2 elements .</p><pre><br>function pivot(arr, start = 0, end = arr.length - 1) {<br>  const swap = (arr, idx1, idx2) =&gt; {<br>    [arr[idx1], arr[idx2]] = [arr[idx2], arr[idx1]];<br>  };<br><br>  // We are assuming the pivot is always the first element<br>  let pivot = arr[start];<br>  let swapIdx = start;<br><br>  for (let i = start + 1; i &lt;= end; i++) {<br>    if (pivot &gt; arr[i]) {<br>      swapIdx++;<br>      swap(arr, swapIdx, i);<br>    }<br>  }<br><br>  // Swap the pivot from the start the swapPoint<br>  swap(arr, start, swapIdx);<br>  return swapIdx;<br>}<br><br><br>function quickSort(arr, left = 0, right = arr.length -1){<br>    if(left &lt; right){<br>        let pivotIndex = pivot(arr, left, right)<br>        //left<br>        quickSort(arr,left,pivotIndex-1);<br>        //right<br>        quickSort(arr,pivotIndex+1,right);<br>      }<br>     return arr;<br>} <br>           <br>quickSort([3,2,4,6,9,1,2,5,3,23])<br></pre><p>The array iteration will happen in this way :</p><p>[2, 2, 1, 3, 9,4, 6, 5, 3, 23] →[1, 2, 2, 3, 9,4, 6, 5, 3, 23] →[1, 2, 2, 3, 3,4, 6, 5, 9, 23] →[1, 2, 2, 3, 3,4, 6, 5, 9, 23] →[1, 2, 2, 3, 3,4, 6, 5, 9, 23] →[1, 2, 2, 3, 3,4, 5, 6, 9, 23]</p><p>Now let’s see the big O of QuickSort , So the time complexity of the best case scenario and average case scenario is <strong>O (n log n)</strong> , the worst case is <strong>O (n²)</strong> and space complexity of the mergeSort is <strong>O( log n) </strong>.</p><p>Now let compare the average time complexity of the sorting algorithms :</p><p>Bubble Sort — O(n²)</p><p>Insertion Sort — O(n²)</p><p>Selection Sort — O(n²)</p><p>Quick Sort — O(n log n)</p><p>Merge Sort — O(n log n)</p><p>So can we make a better sorting algorithm ? Answer is yes so now we will be discussing about Radix Sort .</p><p><strong>Radix Sort :</strong></p><p>Radix sort is a special sorting algorithm that works on lists of numbers. It never makes comparisons between elements , it exploits the fact that information about the size of a number is encoded in the number of digits, which means more digits means a bigger number . Let see try to understand this with an example .</p><p>Let’s say we are having an array:</p><p>[1556,4,3556,593,408,4386,902,7,8157,86,9637,29]</p><p>So we will be segregating the numbers based on digit in ones place.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nYQB6qMJEWvYZl0wRdUL2g.png" /></figure><p>Then we will popping out the numbers and push in the array back .</p><p>[902,593,4,1556,3556,4386,86,7,8157,9637,408,29],</p><p>then we will be segregating the numbers based on digit in tens place.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rr9q2JPYcnIYp_rRrRiegA.png" /></figure><p>So now array looks like this :</p><p>[ 902,4,7,408,29,9637,1556,3556,8157,4386,86,593],</p><p>then we will be segregating the numbers based on digits in hundred place .</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RcJQO5nTbuo8OWbdcq91nA.png" /></figure><p>So now array will look like this :</p><p>[ 4,7,29,86,8157,4386,408,1556,3556,593,9637,902],</p><p>then we will be segregating the numbers based on digits in thousand place .</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*N8KUxLz90w2QM8-8pGeMow.png" /></figure><p>So final array will look like this :</p><p>[4,7,29,86,408,593,902,1556,3556,4386,8157,9637]</p><p>So in order to implement radix sort, it’s helpful to build a few helper functions first:</p><p>getDigit(num,place)- which returns the digit in num at the given place value .</p><pre>function getDigit(num, i) {<br>  return Math.floor(Math.abs(num) / Math.pow(10, i)) % 10;<br>}</pre><p>digitCount(num)- which returns the number of digits in num .</p><pre>function digitCount(num) {<br>  if (num === 0) return 1;<br>  return Math.floor(Math.log10(Math.abs(num))) + 1;<br>}</pre><p>mostDigits(nums) — Given an array of numbers, returns the number of digits in the largest numbers in the list .</p><pre>function mostDigits(nums) {<br>  let maxDigits = 0;<br>  for (let i = 0; i &lt; nums.length; i++) {<br>    maxDigits = Math.max(maxDigits, digitCount(nums[i]));<br>  }<br>  return maxDigits;<br>}</pre><p>Now let’s see the pseudocode of <strong>Radixsort</strong> :</p><p>Define a function that accepts list of numbers . Figure out how many digits the largest number has. Loop from k=0 up to this largest number of digits . For each iteration of the loop we will create buckets for each digit (0 to 9) then place each number in the corresponding bucket based on its kth digit. Then replace existing array with values in our buckets starting with 0 and going up to 9.Finally return list at the end .</p><pre>function getDigit(num, i) {<br>  return Math.floor(Math.abs(num) / Math.pow(10, i)) % 10;<br>}<br><br>function digitCount(num) {<br>  if (num === 0) return 1;<br>  return Math.floor(Math.log10(Math.abs(num))) + 1;<br>}<br><br>function mostDigits(nums) {<br>  let maxDigits = 0;<br>  for (let i = 0; i &lt; nums.length; i++) {<br>    maxDigits = Math.max(maxDigits, digitCount(nums[i]));<br>  }<br>  return maxDigits;<br>}<br><br>function radixSort(nums){<br>    let maxDigitCount = mostDigits(nums);<br>    for(let k = 0; k &lt; maxDigitCount; k++){<br>        let digitBuckets = Array.from({length: 10}, () =&gt; []);<br>        for(let i = 0; i &lt; nums.length; i++){<br>            let digit = getDigit(nums[i],k);<br>            digitBuckets[digit].push(nums[i]);<br>        }<br>        nums = [].concat(...digitBuckets);<br>    }<br>    return nums;<br>}<br><br>radixSort([23,345,5467,12,2345,9852])</pre><p>We are using radixSort function for performing radix sort in the array , so first we are trying to get the number of digits in the largest numbers in the list by calling mostDigits function , In mostDigits function we are iterating through the list of numbers, for each number we are calculating the number of digits and assigning it to maxDigits, then we are using Math.max() function to compare and get the maximum number . Once we get the largest number of digits present in the array we are storing that in maxDigitCount . Then we are iterating from 0 to maxDigitCount (k) , then we are creating buckets for each digit (0 to 9) (i) . Then we are iterating through array of number and trying to get digit present in kth place of numbers and storing it and then we are placing each number in the corresponding bucket based on its kth digit.</p><p>Now let’s see the big O of radixSort , So the time complexity of the best case scenario , average case and worst case is <strong>O(nk) </strong>, where n is the number of elements present in the array and k is the number of digits (average).</p><p>The space complexity of the radixSort is <strong>O(n+k)</strong>.</p><p><strong>Conclusion :</strong></p><p>So we can conclude that merge sort and quick sort are standard efficient sorting algorithms . Quick sort can be slow in the worst case , but is comparable to merge sort on average. Merge sort takes up more memory because it creates a new array . And Radix sort is a fast sorting algorithm for numbers.</p><p>And please checkout my GitHub repo as the reference for the coding discussed in this blog :</p><p><a href="https://github.com/Yudhajitadhikary/Intermediate-Sort-Algorithm">GitHub - Yudhajitadhikary/Intermediate-Sort-Algorithm</a></p><p>HAPPY CODING :)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3133957c2d26" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Elementary Sorting in JavaScript]]></title>
            <link>https://yudhajitadhikary.medium.com/elementary-sorting-in-javascript-015cf2a036ff?source=rss-f54a1f93756b------2</link>
            <guid isPermaLink="false">https://medium.com/p/015cf2a036ff</guid>
            <category><![CDATA[sorting-algorithms]]></category>
            <category><![CDATA[page-speed]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[time-complexity]]></category>
            <category><![CDATA[big-o-notation]]></category>
            <dc:creator><![CDATA[Yudhajit Adhikary]]></dc:creator>
            <pubDate>Sun, 26 Nov 2023 17:58:49 GMT</pubDate>
            <atom:updated>2024-12-14T16:20:51.099Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ej3XVEITXbQxyGTfhSn_Zw.jpeg" /></figure><p>Hi guys, in this blog we will discuss in details on several elementary sorting algorithm in JavaScript .</p><p>So we are having many sorting algorithms but in this blog we will discuss on the very basic and simple sorting algorithm which are :</p><p><strong>1 &gt; Bubble Sort</strong></p><p><strong>2&gt; Insertion Sort</strong></p><p><strong>3&gt; Selection Sort</strong></p><p>So let’s start the discussion :</p><p><strong>What is Sorting ?</strong></p><p>Sorting is the process of rearranging the items in a collection (e.g. an array) so that the items are in some kind of order, for example :</p><ul><li>Sorting numbers from smallest to largest</li><li>Sorting names alphabetically</li><li>Sorting movies based on release year</li><li>Sorting movies based on revenue, etc</li></ul><p><strong>Why we need to learn this sorting ?</strong></p><p>In the current scenario of online website and shopping , user want to get everything sorted on their finger tip , Like if we take an example of any shopping website , almost all the website are competing on making their websites more and more user friendly, sorting plays an important role to achieve it , like offering more and more sorting options to the user on their product listing page . Sorting is an incredibly common task, so it’s good to know how it works. There are many different ways to sort things, and different techniques have their own advantages and disadvantages. Sorting sometimes has quirks, so it’s good to understand how to navigate through them and determine which sorting algorithm is suitable for which scenario .</p><p>Javascript has a sort method , Yes it does !!, but it doesn’t work the way we expect it to work .</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xUDo64nTdQy8d4DBX2Tj8g.png" /></figure><p>So if we see the above function , it returns the sorted result , but if we see the next function</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HE7A3HoyKGooPTf5hm_tlA.png" /></figure><p>It’s not returning sorted array . This is happening because by default, the sort() function sorts values as strings. This works well for strings but numbers are sorted as strings which is not correct.</p><p>So let’s see how JavaScript sorts :</p><p>The built-in sort method accepts an optional <em>comparator</em> function, we can use this comparator function to tell JavaScript how you want it to sort, the comparator looks at pairs of elements (<em>a</em> and <em>b</em>), determines their sort order based on the return value. If it returns a negative number, <em>a</em> should come before <em>b, </em>If it returns a positive number, <em>a</em> should come after <em>b</em>, and If it returns 0, <em>a</em> and <em>b</em> are the same as far as the sort is concerned. Let’s try to understand it with an example :</p><pre>function numberCompare(num1, num2) {<br>  return num1 - num2;<br>}<br><br>[ 6, 4, 15, 10 ].sort(numberCompare);<br>// [ 4, 6, 10, 15 ]</pre><p>So here the comparator function is numberCompare function , if we want to arrange the number in ascending order we returning the value of a - b . If a is greater than b , it will give positive value , which means a will come after b, and the array will get sorted in ascending order.</p><p>Now let see a string example:</p><pre>function compareByLen(str1, str2) {<br>  return str1.length - str2.length;<br>}<br><br>[ &quot;Steele&quot;, &quot;Colt&quot;, &quot;Data Structures&quot;, &quot;Algorithms&quot; ]<br>  .sort(compareByLen);<br>// [ &quot;Colt&quot;, &quot;Steele&quot;, &quot;Algorithms&quot;, &quot;Data Structures&quot; ]</pre><p>So here comparator function is compareByLen function , here we want to arrange strings in ascending order of string length , so in compareByLen function we are returning the difference of str1 and str2 , if str length is greater than str2 , then the str1 will be placed after str2.</p><p>Before going to sorting part we should have understanding of swapping . Because sorting involves many swapping .</p><pre>// ES5<br>function swap(arr, idx1, idx2) {<br>  var temp = arr[idx1];<br>  arr[idx1] = arr[idx2];<br>  arr[idx2] = temp;<br>}<br><br>// ES2015<br>const swap = (arr, idx1, idx2) =&gt; {<br>  [arr[idx1],arr[idx2]] = [arr[idx2],arr[idx1]];<br>}</pre><p>So these are the two ways by which we can perform swapping first one is by using a third parameter temp , and second one is ES2015 way of implementing the same logic.</p><p><strong>Bubble Sort :</strong></p><p>A sorting algorithm where the largest values bubble up to the top!</p><p>So let’s take an example [5 , 3 , 4, 1 , 2] , we will first check first two numbers 5 , 3 and compare if 5 is greater than 3 , then we are swapping the position of each other, it will become [3 , 5 , 4 , 1 , 2] , then we will again compare 5 and 4 , since 5 is greater than 4 , we will again swap them so now array will be [3 , 4 , 5, 1 , 2] , then we will compare 5 and 1 , since 5 is greater than 1 , we will again swap 5 and 1 so array will become [3 , 4 , 1 , 5 , 2 ] , similarly we will compare 5 and 2 , since 5 is greater than 2 , we will swap 5 and 2 , so array will become [3 ,4, 1, 2 ,5 ] similarly we will iterate through the array again from the beginning and place the next highest value before 5. And once these whole cycle completes we will get the array sorted in ascending order .</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/819/1*68Cv2T891Rk1GaYBAtzbBQ.png" /></figure><p>Now let’s see the <strong>pseudocode for Bubble Sort:</strong></p><ul><li>Start looping from with a variable called i the end of the array towards the beginning</li><li>Start an inner loop with a variable called j from the beginning until i - 1</li><li>If arr[j] is greater than arr[j+1], swap those two values!</li><li>Return the sorted array</li></ul><p>Now let’s see two approach one is unoptimised and another is optimised :</p><pre>// UNOPTIMIZED VERSION OF BUBBLE SORT<br>function bubbleSort(arr){<br>  for(var i = arr.length; i &gt; 0; i--){<br>    for(var j = 0; j &lt; i - 1; j++){<br>      console.log(arr, arr[j], arr[j+1]);<br>      if(arr[j] &gt; arr[j+1]){<br>        var temp = arr[j];<br>        arr[j] = arr[j+1];<br>        arr[j+1] = temp;         <br>      }<br>    }<br>  }<br>  return arr;<br>}<br><br>// ES2015 Version<br>function bubbleSort(arr) {<br>  const swap = (arr, idx1, idx2) =&gt; {<br>    [arr[idx1], arr[idx2]] = [arr[idx2], arr[idx1]];<br>  };<br><br>  for (let i = arr.length; i &gt; 0; i--) {<br>    for (let j = 0; j &lt; i - 1; j++) {<br>      if (arr[j] &gt; arr[j + 1]) {<br>        swap(arr, j, j + 1);<br>      }<br>    }<br>  }<br>  return arr;<br>}<br><br>bubbleSort([8,1,2,3,4,5,6,7]);</pre><p>In this function bubbleSort we are accepting an array , so we are running a loop from end to beginning that is from array length to 0 , and inside that we are running a loop from starting to end until i -1, so we are checking if array[j] is greater than array[j+1], if it’s true we are swapping both the values. So we have shown both normal and ES2015 way of swapping variables. And by this we will get the array sorted in ascending order . But there is a issue if you have noticed we are doing some unnecessary comparing which are actually not required , like let’s see an example we are having array [ 5 , 3 , 4 , 1 , 2 ] and we have almost sorted the array by following this algorithm, let’s assume we are in this stage where array looks like [ 2 , 1 , 3 , 4 , 5 ] , now if we take 2 and start comparing it with other elements like first with 1 , since 2 is greater than 1 , we will swap position of 2 and 1 , and it will look like [ 1, 2 , 3 , 4 , 5 ] now if we compare 2 and 3 , since 2 is smaller than 3 , we will skip the swapping then we will again compare between 3 and 4 then 5 , since the array is almost sorted so we would have easily skip those comparison. So we can say the above is not totally optimised , let see more optimised solution.</p><pre>// Optimized BubbleSort with noSwaps<br>function bubbleSort(arr){<br>  var noSwaps;<br>  for(var i = arr.length; i &gt; 0; i--){<br>    noSwaps = true;<br>    for(var j = 0; j &lt; i - 1; j++){<br>      if(arr[j] &gt; arr[j+1]){<br>        var temp = arr[j];<br>        arr[j] = arr[j+1];<br>        arr[j+1] = temp;<br>        noSwaps = false;         <br>      }<br>    }<br>    if(noSwaps) break;<br>  }<br>  return arr;<br>}<br><br>bubbleSort([8,1,2,3,4,5,6,7]);</pre><p>Let’s see more optimized approach of bubbleSort , where we are setting a new variable noSwaps which will consider whether any further comparison is required for the current iteration, so for each iteration we are setting noSwaps to true at beginning . Then we are starting the iteration , we are setting it to false if and only if the arr[j] &gt; arr[j+1] else we will break out from that iteration , by this we will be avoiding any further comparison , if we find any number which is greater than the selected number while iterating , we will omit further comparison for current iteration .</p><p><strong>Time and Space Complexity for Bubble Sort :</strong></p><p>In best case scenario , the time complexity of bubble sort will be O(n) , and in both average and worst case , the time complexity of bubble sort will be O(n²). Space complexity of bubble sort will be O(1). Now let’s come on to our next sorting algorithm selection sort.</p><p><strong>Selection Sort :</strong></p><p>Similar to bubble sort, but instead of first placing large values into sorted position, it places small values into sorted position. Let see this by an example : we are having an array [5 , 3 , 4 , 1 , 2] , so we will start finding the smallest element in each iteration , first we will consider the first element as the smallest element , 5 is the smallest element , now we will move forward and check whether 3 is lesser than 5 , since it’s true we will set 3 as smallest element and will continue comparing 3 with other numbers as well , at the end of the iteration we will find 1 as the smallest element , and we will swap the position of smallest element (1) and first element (5) so the array will look like this- [ 1 , 3 , 4 , 5 , 2 ] , next iteration we will start from 1 index for searching for next smallest element since 0 index is already sorted , so at the end of whole cycle of iteration the array will be sorted in ascending order.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/793/1*ajuJSdKYDW8tipcQU9gtXA.png" /></figure><p>Now let’s see <strong>pseudocode for Selection sort:</strong></p><ul><li>Store the first element as the smallest value you’ve seen so far.</li><li>Compare this item to the next item in the array until you find a smaller number.</li><li>If a smaller number is found, designate that smaller number to be the new “minimum” and continue until the end of the array.</li><li>If the “minimum” is not the value (index) you initially began with, swap the two values.</li><li>Repeat this with the next element until the array is sorted.</li></ul><p>Now let’s see the coding part of the same :</p><pre>// LEGACY VERSION (non ES2015 syntax)<br>function selectionSort(arr){<br>    for(var i = 0; i &lt; arr.length; i++){<br>        var lowest = i;<br>        for(var j = i+1; j &lt; arr.length; j++){<br>            if(arr[j] &lt; arr[lowest]){<br>                lowest = j;<br>            }<br>        }<br>        if(i !== lowest){<br>            //SWAP!<br>            var temp = arr[i];<br>            arr[i] = arr[lowest];<br>            arr[lowest] = temp;<br>        }<br>    }<br>    return arr;<br>}<br><br>// ES2015 VERSION<br>function selectionSort(arr) {<br>  const swap = (arr, idx1, idx2) =&gt;<br>    ([arr[idx1], arr[idx2]] = [arr[idx2], arr[idx1]]);<br><br>  for (let i = 0; i &lt; arr.length; i++) {<br>    let lowest = i;<br>    for (let j = i + 1; j &lt; arr.length; j++) {<br>      if (arr[lowest] &gt; arr[j]) {<br>        lowest = j;<br>      }<br>    }<br>    if (i !== lowest) swap(arr, i, lowest);<br>  }<br><br>  return arr;<br>}<br><br>selectionSort([0,2,34,22,10,19,17]);</pre><p>SelectionSort function accepts array input , inside that function we are looping through the array , and we are considering the the first element as the smallest element , in first iteration i will be 0 , we are running a loop j from i+1 to arr.length , there we are simply finding the smallest element in the array , once the we get the smallest element we are swapping the position of smallest number and Ith element in first iteration which is nothing but 0th element , again we will be doing the same to 1st element in second iteration and swap the position between smallest element and ith element and at the end of the whole iteration we will have the array sorted in ascending order.</p><p><strong>Time and Space Complexity for Selection Sort :</strong></p><p>In best case scenario , the time complexity of selection sort will be O(n) , and in both average and worst case , the time complexity of bubble sort will be O(n²). Space complexity of selection sort will be O(1). Now let’s come on to our next sorting algorithm insertion sort.</p><p><strong>Insertion Sort:</strong></p><p>In insertion sort we are building up the sorted array by gradually creating a larger left half which is always sorted . Let see an example :</p><p>Let see we are having array [ 5 , 3 , 4 , 1 , 2 ] , so we will pick up second element 3 in the array , then we will compare the second element with the one before it (5) and swap it to make it sorted , it will look like this now [3 , 5 , 4 , 1 , 2] , then we will take next element 4 , compare it with 5 , swap both since 4 is less than 5 , then we will not swap since 4 is not less than 3 , so now the array will look like this [ 3 , 4 , 5 , 1 , 2 ] , then we will take 1 and compare it with 5 and swap , since 1 is less than 5 , similarly it will be compared with 4 and 3 and placed in the 0th position , now the array will look like this [1 ,3 , 4 , 5 , 2] and finally in similar way we will take 2 and place it in the right position and will get a sorted array [1 , 2 , 3 , 4 , 5].</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/784/1*ozcToAh7zeVUe0UjUM5ZjA.png" /></figure><p>Let’s see <strong>pseudocode for Insertion Sort :</strong></p><ul><li>Start by picking the second element in the array</li><li>Now compare the second element with the one before it and swap if necessary.</li><li>Continue to the next element and if it is in the incorrect order, iterate through the sorted portion (i.e. the left side) to place the element in the correct place.</li><li>Repeat until the array is sorted.</li></ul><p>Now let’s see the coding part of the same :</p><pre>function insertionSort(arr){<br> var currentVal;<br>    for(var i = 1; i &lt; arr.length; i++){<br>        currentVal = arr[i];<br>        for(var j = i - 1; j &gt;= 0 &amp;&amp; arr[j] &gt; currentVal; j--) {<br>            arr[j+1] = arr[j]<br>        }<br>        arr[j+1] = currentVal;<br>    }<br>    return arr;<br>}<br><br>insertionSort([2,1,9,76,4])</pre><p>In this code we are defining a function insertionSort which accepts an array, we have declared a variable currentVal where we will store the value of the element which we will pick to make it sorted , so we are running a loop from 1 to end , where we are first storing the 1th element in currentVal , then we are running another loop from i-1, and checking adding if j≥0 and arr [j] &gt;currentVal , we will replace arr[j+1] with arr[j] else we will make arr[j+1]= currentVal , and finally we will return sorted array .</p><p><strong>Time and Space Complexity for Insertion Sort :</strong></p><p>In best case scenario , the time complexity of insertion sort will be O(n²) , and in both average and worst case , the time complexity of insertion sort will be O(n²). Space complexity of insertion sort will be O(1).</p><p><strong>Conclusion:</strong></p><p>In this blog we have discussed very basic and fundamental sorting algorithm and we got the significants of sorting . But for industrial fulfillments Bubble sort, selection sort, and insertion sort are all roughly equivalent because all of the algorithm are having average time complexities which are quadratic. So we can do better…but we need more complex algorithms! which we will discuss in our upcoming blogs :)</p><p>Please refer to this link to get a visual representation of all sorting algorithms:</p><p><a href="https://www.toptal.com/developers/sorting-algorithms">Sorting Algorithms Animations</a></p><p>And please checkout my GitHub repo as the reference for the coding discussed in this blog :</p><p><a href="https://github.com/Yudhajitadhikary/Searching-and-Elementary-Sorting">GitHub - Yudhajitadhikary/Searching-and-Elementary-Sorting: It&#39;s a reference of code discussed in my Searching and Sorting Blog</a></p><p>HAPPY CODING :)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=015cf2a036ff" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Searching in JavaScript…]]></title>
            <link>https://yudhajitadhikary.medium.com/searching-in-javascript-cef681b60df4?source=rss-f54a1f93756b------2</link>
            <guid isPermaLink="false">https://medium.com/p/cef681b60df4</guid>
            <category><![CDATA[search]]></category>
            <category><![CDATA[big-o-notation]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[page-speed]]></category>
            <dc:creator><![CDATA[Yudhajit Adhikary]]></dc:creator>
            <pubDate>Sat, 04 Nov 2023 17:40:10 GMT</pubDate>
            <atom:updated>2023-11-04T17:44:55.165Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/612/1*t7sYlIl-bOZ_JaSoUwH5nA.jpeg" /></figure><p>Hi guys , in this blog we will be discussing in details different searching algorithms , what are their time complexity, pros and cons and logic . So let’s get started …</p><p><strong>Searching :</strong></p><p><strong>Searching</strong> , the most deepest word in this world , people spend their entire life searching for peace , love and what not , but wait wait wait !! let’s not get into those deep philosophical norms :) ….. For us as a geek let see how do we search ?</p><p>In an array the simplest way to search for an value is to look at every element in the array and check if it’s the value we want .</p><p>The biggest example of significance of search is<strong> Google</strong>, it’s nothing but a search engine , and I think you all will agree with me that google is having the world most complexed searching algorithms. So we will explore how we can do searching using Javascript .</p><p>Javascript is also having it’s own search function , there are many different search methods on arrays like :</p><p><strong>1&gt; indexOf :</strong> The indexOf() method of <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array">Array</a> instances returns the first index at which a given element can be found in the array, or -1 if it is not present.</p><p><strong>2&gt; includes:</strong> The includes() method of <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array">Array</a> instances determines whether an array includes a certain value among its entries, returning true or false as appropriate.</p><p><strong>3&gt; find : </strong>The find() method of <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array">Array</a> instances returns the first element in the provided array that satisfies the provided testing function. If no values satisfy the testing function, <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/undefined">undefined</a> is returned.</p><p><strong>4&gt;findIndex: </strong>The findIndex() method of <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array">Array</a> instances returns the index of the first element in an array that satisfies the provided testing function. If no elements satisfy the testing function, -1 is returned.</p><p><strong>But how do these functions work ?</strong></p><p>And the answer is our very first and simple searching algorithm :</p><p><strong>Linear search :</strong></p><p><strong>Linear search</strong> is nothing but normal search algorithm where we will check every element in an array , and compare whether it’s the value we are looking for . Let’s see one example :</p><p>We are having one array <strong>[5 , 8 , 1 , 100 , 12 , 3 , 12 ]</strong> so let’s search for <strong>12 </strong>. We will start checking from the first element , first element is 5 , not 12 , so we will check second , it’s 8, not 12 , we will check third , it’s 1 , not 12 , then we will move on the 4th , it’s 100 , not 12 , then on 5th , now it’s 12! . Simple right . So before jumping into the coding part let see the<strong> pseudocode for Linear search :</strong></p><p>We will have one function which accepts an array and a value. We will loop through the array and check if the current array element is equal to the value , if it is we will return the index at which the element is found , else if the value is never found we will return -1.</p><p>Now let see the code :</p><pre>function linearSearch(arr, val){<br>    for(var i = 0; i &lt; arr.length; i++){<br>        if(arr[i] === val) return i;<br>    }<br>    return -1;<br>}<br><br>linearSearch([34,51,1,2,3,45,56,100], 100)</pre><p><strong>Code Walkthrough:</strong></p><p>So here we have defined a function linearSearch which are having two parameters arr and val , arr is the array in which we will be searching the element, and val is the element to be search , then we are iterating through the array using for loop and checking if arr[i] == val, means if there are any array element which is matching with val , if we encounter such element we will return i means the index of a element , else if the whole array is iterated but the element is not found we will return -1 means array is not having the element.</p><p>Now let see the <strong>time complexity of linear search:</strong> In this algorithm the best case scenario will be if the element we are searching is in the first index , <strong>O(1)</strong> ,and and worst case scenario will be if the element which we are searching is in the last index , <strong>O(n)</strong> . So the time complexity will be O<strong>(n)</strong>.</p><p>Now we will see a much faster form of search which is :</p><p><strong>Binary Search:</strong></p><p><strong>Binary search</strong> is a much faster form of search , Binary search only works on the sorted arrays! so rather than eliminating one element at a time like linear search , we can eliminate half of the remaining elements at a time . Let’s discuss in details, so binary search follows <strong>Divide and Conquer</strong> approach , let say we are having a sorted array <strong>[1,3,4,6,8,9,11,12,15,16,17,18,19] </strong>and let search for <strong>15</strong> , so first we will determine the element which is in the middle of the array , since the array is having 13 element so 7th element will be the mid element of the array which is 11 , we will check whether the mid element is greater or less than the element we want to search . Since 11&lt; 15 we will be ignoring the left side of the array , and will only search on the right side of the mid element , now the array will be <strong>[12,15,16,17,18,19]</strong> so now mid element will be 17 , since 15&lt;17 , we will ignore the right side of the mid element , so now the array will be <strong>[12,15,16]</strong> , now 15 will be the mid element and it’s the same element we are searching for ! So this is how binary search works. Now let’s see the <strong>pseudocode of Binary search:</strong></p><p>We will be having a function that accepts a sorted array and a value . We will create a left pointer at the start of the array , and a right pointer at the end of the array . While the left pointer comes before the right pointer , we will create another pointer in the middle , if you find the value you want , return the index , if the value is too small , move the left pointer up , if the value is too large , move the right pointer down , and lastly if you never find the value return -1.</p><p>Now let’s see the code :</p><pre>// Original Solution<br>function binarySearch(arr, elem) {<br>    var start = 0;<br>    var end = arr.length - 1;<br>    var middle = Math.floor((start + end) / 2);<br>    while(arr[middle] !== elem &amp;&amp; start &lt;= end) {<br>        if(elem &lt; arr[middle]){<br>            end = middle - 1;<br>        } else {<br>            start = middle + 1;<br>        }<br>        middle = Math.floor((start + end) / 2);<br>    }<br>    if(arr[middle] === elem){<br>        return middle;<br>    }<br>    return -1;<br>}<br><br>// Refactored Version<br>function binarySearch(arr, elem) {<br>    var start = 0;<br>    var end = arr.length - 1;<br>    var middle = Math.floor((start + end) / 2);<br>    while(arr[middle] !== elem &amp;&amp; start &lt;= end) {<br>        if(elem &lt; arr[middle]) end = middle - 1;<br>        else start = middle + 1;<br>        middle = Math.floor((start + end) / 2);<br>    }<br>    return arr[middle] === elem ? middle : -1;<br>}<br><br>binarySearch([2,5,6,9,13,15,28,23], 103)</pre><p><strong>Code Walkthrough:</strong></p><p>We are having binarySearch function which is having two parameters <strong>arr</strong> and <strong>elem</strong> , <strong>arr</strong> is the array is which we will be searching , <strong>elem</strong> is the element we will be searching . So we have declared two pointer <strong>start </strong>pointing to the first element and <strong>end</strong> pointing to the last element of the array. Then we are declaring the middle pointer of the array <strong>middle</strong> which points to the middle of the array . Now we are will writing the actual logic , we have defined a while loop , while middle element is not equal to search element and start pointer is less than or equal to end pointer means array iteration is not completed , we are checking if the search element is less than middle element we will set end pointer to previous element of middle element , else we will set start pointer to next element of the middle element , and again we will define the middle pointer according to the start and end pointer defined . Then if the while condition gets failed we will check whether the element which is getting pointer by middle pointer is equal to search element, if it is true it means element is found so we will reach the index of the element . if it is false it means the element is not there in the array and we will return -1.</p><p>Now let’s see the time complexity of the Binary Search , in the best case scenario , the time complexity will be <strong>O(1)</strong> and worst and average case the time complexity will be <strong>O(log n)</strong> . Let justify the statement , so we will see two example , let’s say we are having an array <strong>[2,4,5,9,11,14,15,19,21,25,28,30,50,52,60,63]</strong> and we are searching 13, so the iteration will be <strong>[2,4,5,9,11,14,15] →[11,14,15] →[11]</strong>, the array is having <strong>16</strong> elements and we are having <strong>4 </strong>iteration , so log 16 is 4 . Now let’s see the next example , now we are having an array <strong>[1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,32,35] </strong>so total <strong>32</strong> elements in array , and we will search 32 , so the iteration will be <strong>[17,18,19,20,21,22,23,24,25,26,27,28,29,30,32,35] →[25,26,27,28,29,30,32,35] →[29,30,32,35] →[32,35] →[35]</strong> , finally we are able to find the element with <strong>5</strong> iteration, so log 32 is 5. So we can say the time complexity of binary search is <strong>O(log N).</strong></p><p>Now let’s see own last concept of search algorithm which is <strong>Naive String search</strong></p><p><strong>Naive String Search:</strong></p><p>Suppose we want to count the number of times a smaller string appears in a longer string . So a straightforward approach involves checking pairs of characters individually . Let’s try to understand this through an example, so we are having a long string <strong>wowomgzomg</strong> and short string <strong>omg</strong> , we will start comparing the large string with short string , w of large string is not matching with o of short string , so we will move on for large string , now o of large string is matching with o of short string , so we will check the next character for both the string , but since w of large string is not matching with m of short string , for short string the iteration will again start from o , now again w of large string is not matching with o of short string , so only the pointer of larger string with move , now since the three consecutive text omg for large string is matching with omg of short string , we will increment the count by 1 , and same process will be followed and once large string is iterated completely , the count value will be returned .</p><p>Now let’s see the <strong>pseudocode :</strong></p><p>We have to loop over to longer string , then we have to loop over to shorter string , if the character don’t match , break out of the inner loop , if the character do match , keep going . If you complete the inner loop and find a match , increment the count of matches , return the count .</p><p>Now let’s see the code :</p><pre>function naiveSearch(long, short){<br>    var count = 0;<br>    for(var i = 0; i &lt; long.length; i++){<br>        for(var j = 0; j &lt; short.length; j++){<br>           if(short[j] !== long[i+j]) break;<br>           if(j === short.length - 1) count++;<br>        }<br>    }<br>    return count;<br>}<br><br>naiveSearch(&quot;lorie loled&quot;, &quot;lol&quot;)</pre><p><strong>Code Walkthrough:</strong></p><p>So we are having <strong>naiveSearch</strong> function which is having two parameters long and short string . Now we have defined a variable called count which used to store the count of occurrence of short string inside the large string . Now we are running a loop over long string and short string , and then we are checking if (short[j]!==long[i+j]) means if the characters of short string don’t match with large string , we will break out of the inner loop. and if the character matches we will keep going and if (j==short.length-1) means if we complete the inner loop and find a match, increment the count of matches, and finally will return match count .</p><p>Now what will be the<strong> time complexity of Naive String Search</strong> , so let assume the length of element in large string is n and that of short string is m , so since we are iterating through both the string the time complexity of naive string search will <strong>O(n*m)</strong>.</p><p><strong>Conclusion:</strong></p><p>Okay so we did it ! , we have touched almost all the corners of search algorithm in JavaScript . <strong>But please don’t stop searching :) </strong>. Do checkout my github repo for the reference of the code snippets discussed in this blog …</p><p><a href="https://github.com/Yudhajitadhikary/Searching-and-Elementary-Sorting">GitHub - Yudhajitadhikary/Searching-and-Elementary-Sorting: It&#39;s a reference of code discussed in my Searching and Sorting Blog</a></p><p><strong>HAPPY CODING :)</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cef681b60df4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Recursion in Js ….]]></title>
            <link>https://yudhajitadhikary.medium.com/recursion-in-js-39540ad623cd?source=rss-f54a1f93756b------2</link>
            <guid isPermaLink="false">https://medium.com/p/39540ad623cd</guid>
            <dc:creator><![CDATA[Yudhajit Adhikary]]></dc:creator>
            <pubDate>Sun, 24 Sep 2023 10:50:23 GMT</pubDate>
            <atom:updated>2023-09-28T14:20:41.040Z</atom:updated>
            <content:encoded><![CDATA[<h3>Recursion in Js ….</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/1*2Kdz84xWYZvk_wX4lcunIg.jpeg" /></figure><p>Hi Guys in this Blog we will discuss about Recursion in JavaScript. So let’s get started .</p><p><strong>What is Recursion?</strong></p><p>So in layman language we can say recursion is A <strong>process</strong> (a function in our case) that <strong>calls itself.</strong></p><p><strong>Why do we need to know this ?</strong></p><p>The easy and simple answer to this question is it’s everywhere , If we take up any Javascript built in function like <strong>JSON.parse / JSON.stringify </strong>, we will see these functions are internally written in Java using recursion concept. Recursion is also used internally in document.getElementById , and it’s very much useful on DOM traversal algorithm . Recursion concept is also useful for Object traversal , it’s very common in more complex algorithm , and it can be used as a cleaner alternative of iteration.</p><p>Now let’s see <strong>How recursive functions work ?</strong></p><p>Now before going to the concept of how recursive function works let’s see how a function works first .</p><p>In almost all program language there is a built-in data structure that manages what happen when function are invoked , it is called the <strong>Call Stack</strong> , It’s s a stack data structure .</p><p>Anytime a function is invoked, it is placed <strong>(push)</strong> on the top of the call stack.</p><p>When JavaScript sees the return keyword or when the function ends, the compiler will remove <strong>(pop)</strong> the function from the top of the call stack.</p><p>Let see following code:</p><pre>function takeShower(){<br>    return &quot;Showering!&quot;<br>}<br><br>function eatBreakfast(){<br>    let meal = cookFood()<br>    return `Eating ${meal}`<br>}<br><br>function cookFood(){<br>    let items = [&quot;Oatmeal&quot;, &quot;Eggs&quot;, &quot;Protein Shake&quot;]<br>    return items[Math.floor(Math.random()*items.length)];<br>}<br>function wakeUp() {<br>    takeShower()<br>    eatBreakfast()<br>    console.log(&quot;Ok ready to go to work!&quot;)<br>}<br><br>wakeUp()</pre><p>So we are having a chain of function calls here, first we are calling <strong>wakeUp() </strong>function, which are having two functions into it <strong>takeShower()</strong> and e<strong>atBreakfast()</strong> , then we are having console.log to indicate the end of the whole function chain. <strong>takeShower()</strong> function is just returning a string value, whereas <strong>eatBreakfast()</strong> function is having another function called <strong>cookFood() </strong>function and it returning the value which is getting returned from <strong>cookFood() </strong>. In <strong>cookFood()</strong> function we are having one array which is having the array of food names what can be cooked , we are picking any food randomly from the array and returning it to <strong>eatBreakfast()</strong> function, So to understand the flow of the execution of these function chain let see the chrome dev tool :</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fplayer.vimeo.com%2Fvideo%2F867621640%3Fapp_id%3D122963&amp;dntp=1&amp;display_name=Vimeo&amp;url=https%3A%2F%2Fvimeo.com%2F867621640&amp;image=https%3A%2F%2Fi.vimeocdn.com%2Fvideo%2F1728408841-22042c86348a6a27ca79fc24846d8e3b4030e9b243db09764de18a8c8de50871-d_1280&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=vimeo" width="1920" height="1200" frameborder="0" scrolling="no"><a href="https://medium.com/media/d3f5a33e0e6ada7188ba9b0ecd845818/href">https://medium.com/media/d3f5a33e0e6ada7188ba9b0ecd845818/href</a></iframe><p>To check the flow in the dev tool we can open our Javascript code in live server , and open the host link in google chrome , then right click on the browser window you will see a option inspect, then the dev tool will get opened , initially the Elements tab will be open , click to source tab where you will see your js file present in the source code , once you click on that you will see your js code , then we have to add debugger to the code , for that we first we have to consider what are breakpoints we will be adding on our code , since we will be checking the flow of the function chain we will set our breakpoints on the point where <strong>wakeUp()</strong> function is called . To set the debugger we just have to click on the line number where we want to add it , like in our case , line number 25 where <strong>wakeUp()</strong> function is called. By debugging a piece of code we can check each and every stage of a function execution. So in right side dev tool you will see there is a dropdown called Call Stack , now let’s follow that tab while we execute the our function , if we reload the page we will see anonymous function is getting added in call stack first , these anonymous function is the main execution thread of the page. If you notice in the right hand top in dev tool we are having a button like right pointing arrow with a dot in front , if we click on the it will show us the line by line execution of the function, so let see how the flow works. After anonymous function , <strong>wakeUp() </strong>function will be pushed at the top of the call stack , then since <strong>wakeUp()</strong> is calling <strong>takeShower()</strong> function, <strong>takeShower()</strong> function will be pushed to the top of the stack , in <strong>takeShower()</strong> function since browser have encountered a return statement it means the <strong>takeShower()</strong> function execution is completed, <strong>takeShower()</strong> function will be popped out from the call stack , again the control will go back to <strong>wakeUp() </strong>function, now <strong>eatBreakfast()</strong> function will be pushed in the call stack , <strong>eatBreakfast()</strong> is having a function <strong>cookFood()</strong>, so <strong>cookFood()</strong> will get pushed into the call stack , <strong>cookFood()</strong> function will take a random food item from items array and will return it to <strong>eatBreakfast() </strong>function , since browser encounters return statement on <strong>cookFood() </strong>function it will pop out <strong>cookFood() </strong>from call stack, then the control will go on <strong>eatFood()</strong> and since it encounters a return statement , it will pop out <strong>eatFood()</strong> function from the call stack and finally the call stack will go to <strong>wakeUp()</strong> function and will encounter end of function with console.log so browser will pop out <strong>wakeUp()</strong> function from call stack , and call stack will be empty , So this is how call stack works on executing a javascript code.</p><p>So in normal function , we have seen the function is being pushed on the call stack and popped off when they are done , for recursion function we will keep pushing same function on the call stack with different parameters.</p><p>So let’s see the execution flow of a recursive function:</p><pre>function collectOddValues(arr){<br>    let newArr = [];<br>    <br>    if(arr.length === 0) {<br>        return newArr;<br>    }<br>        <br>    if(arr[0] % 2 !== 0){<br>        newArr.push(arr[0]);<br>    }<br>        <br>    newArr = newArr.concat(collectOddValues(arr.slice(1)));<br>    return newArr;<br>}<br><br>collectOddValues([1,2,3,4,5])</pre><p>Here we are collecting the odd values from the array using recursion. So we are having<strong> collectOddValues</strong> function where we have created an arr <strong>newArr</strong> , then we are checking whether the first element of arr is even or odd , if it’s odd we are pushing the element in <strong>newArr</strong> , then we are recursively calling the <strong>collectOddValues</strong> function and updating it in <strong>newArr</strong>. All the recursion function should have a base condition , where the function should stop and return some values , for this we are checking if arr is having 0 element we will return the value of <strong>newArr</strong> . Now let’s see the execution of the function in dev tool, So first function that will be pushed to the call stack is <strong>collectOddValues([1,2,3,4,5])</strong> , on that function we are checking whether the parameter arr is having any element or not if it’s not having any element it will return <strong>newArr</strong> , else it will check if the first element is odd , if it’s odd the element will be pushed to <strong>newArr</strong> arr , then we will concatenate returned value of <strong>collectOddValues([2,3,4,5]) </strong>so <strong>collectOddValues([2,3,4,5]</strong>) will be pushed in callstack , then similarly <strong>collectOddValues([3,4,5])</strong> ,<strong> collectOddValues([4,5])</strong>, <strong>collectOddValues([5])</strong> and <strong>collectOddValues([])</strong> will be pushed on the callstack . So when <strong>collectOddValues([])</strong> will be called , it will check the whether there is any element in the arr , since arr is empty it will meet base case and will return <strong>newArr </strong>which is [], then control will return to <strong>collectOddValues([5])</strong> ,where <strong>newArr </strong>will become [5] so it will return [5], then control will return to <strong>collectOddValues([4,5])</strong> ,where <strong>newArr</strong> will remain [5] so it will return [5], then control will return to <strong>collectOddValues[3,4,5])</strong>, <strong>newArr</strong> will become [3,5] so it will return [3,5] , then control will return to <strong>collectOddValues([2,3,4,5])</strong> , <strong>newArr </strong>will remain [3,5] so it will return [3,5] , finally control will return to <strong>collectOddValues([1,2,3,4,5])</strong> where <strong>newArr</strong> will be become [1,3,5] and finally it will return the array [1,3,5]</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fplayer.vimeo.com%2Fvideo%2F867630304%3Fapp_id%3D122963&amp;dntp=1&amp;display_name=Vimeo&amp;url=https%3A%2F%2Fvimeo.com%2F867630304&amp;image=https%3A%2F%2Fi.vimeocdn.com%2Fvideo%2F1728423863-76f2c6f4858094e04ee28dcd44ad63545cc87b3b8f95058bf7d92fe30fb025c4-d_1280&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=vimeo" width="1920" height="1200" frameborder="0" scrolling="no"><a href="https://medium.com/media/d8bca4162e28e49681174634a1343551/href">https://medium.com/media/d8bca4162e28e49681174634a1343551/href</a></iframe><p>Now let’s explore few key features we should always consider while writing a recursion function:</p><p><strong>A&gt; Adding Base Cases :</strong> While defining recursion function we should define a base case that will lead to the end of the recursion call , otherwise recursion call will happen in infinite loop. Which will lead to Maximum call stack size exceeded error , because the recursion function will start executing in a infinite loop , and will get pushed in call stack infinite times which will exceed the maximum size of the call stack. Please check the below execution of the code where we have not kept any base case.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fplayer.vimeo.com%2Fvideo%2F867633861%3Fapp_id%3D122963&amp;dntp=1&amp;display_name=Vimeo&amp;url=https%3A%2F%2Fvimeo.com%2F867633861&amp;image=https%3A%2F%2Fi.vimeocdn.com%2Fvideo%2F1728428726-2c28cff1f7882acb4efe0286c01e0cb45b7c843792055754b56aa75dea504252-d_1280&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=vimeo" width="1920" height="1200" frameborder="0" scrolling="no"><a href="https://medium.com/media/6866b7482c7558ca032c28f7445fb0cd/href">https://medium.com/media/6866b7482c7558ca032c28f7445fb0cd/href</a></iframe><p><strong>B&gt; Adding return statement or you can say adding correct return statement: </strong>While defining recursion function we should always have a return statement , otherwise none of the recursion function will stop executing . Which will again lead to maximum call stack size exceeded error ,Please check the below execution of the code where we have replaced the return statement with console.log .</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fplayer.vimeo.com%2Fvideo%2F867661962%3Fapp_id%3D122963&amp;dntp=1&amp;display_name=Vimeo&amp;url=https%3A%2F%2Fvimeo.com%2F867661962&amp;image=https%3A%2F%2Fi.vimeocdn.com%2Fvideo%2F1728470230-620e5e063ccc86a2ed6bd996e7e885f74f75c736fe3ff2f8fdbe49b64b0f60b2-d_1280&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=vimeo" width="1920" height="1200" frameborder="0" scrolling="no"><a href="https://medium.com/media/8768ec3699962460493865429d8d0fa6/href">https://medium.com/media/8768ec3699962460493865429d8d0fa6/href</a></iframe><p><strong>C&gt; Adding different parameter to recursion function in each iterative call: </strong>While declaring recursive function we should always call function with different parameter in each iterative call, otherwise always recursive function will be pushed into call stack with same parameter, which will never meet the base condition means none of the function will get returned, which will again lead to maximum call stack size exceeded error, or Stack overflow error , Please check the below execution of the code where we are always passing same parameter while calling recursion function .</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fplayer.vimeo.com%2Fvideo%2F867686958%3Fapp_id%3D122963&amp;dntp=1&amp;display_name=Vimeo&amp;url=https%3A%2F%2Fvimeo.com%2F867686958&amp;image=https%3A%2F%2Fi.vimeocdn.com%2Fvideo%2F1728507163-d52d0251f1de02ee61314706dd54ebc0146ea6367ea1914765d2d806e4b3e014-d_1280&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=vimeo" width="1920" height="1200" frameborder="0" scrolling="no"><a href="https://medium.com/media/d389b789ed589af1ae17d9a9995a4b91/href">https://medium.com/media/d389b789ed589af1ae17d9a9995a4b91/href</a></iframe><p>Next topic we will be discussing is:</p><p><strong>Helper Method Recursion</strong></p><p>So far all the recursion function we have written are single stand alone functions , we have called <strong>factorial</strong> outside the function , and <strong>factorial</strong> itself calls <strong>factorial .</strong></p><pre>function factorial(num){<br>    if(num === 1) return 1;<br>    return num * factorial(num);<br>}<br>factorial(4)</pre><p>With <strong>Helper Method Recursion</strong> we will have outer method here, then inside that we have our recursion function, and this recursive function calls itself.</p><pre>function outer(input){<br>    <br>    var outerScopedVariable = []<br><br>    function helper(helperInput){<br>        // modify the outerScopedVariable<br>        helper(helperInput--)<br>    }<br>    <br>    helper(input)<br><br>    return outerScopedVariable;<br><br>}</pre><p>So why we need this <strong>helper method recursion</strong> , let’s say we are declaring variable result = [ ] which we will be using to store all odd elements from a given array . If we are doing it through recursive way, no matter what we put after this everytime the result will get reset to [ ] array. So How we are going to collect the data , the most easy solution is to put the result array outside the function , so rather than putting the result array nowhere globally we will be using <strong>helper method function</strong> , what will wrap the recursion function.</p><pre>function collectOddValues(arr){<br>    <br>    let result = []<br><br>    function helper(helperInput){<br>        if(helperInput.length === 0) {<br>            return;<br>        }<br>        <br>        if(helperInput[0] % 2 !== 0){<br>            result.push(helperInput[0])<br>        }<br>        <br>        helper(helperInput.slice(1))<br>    }<br>    <br>    helper(arr)<br><br>    return result;<br><br>}<br>collectOddValues([1,2,3,4,5])</pre><p>Now let’s see <strong>Pure Recursion Approach :</strong></p><p>Let’s see the pure recursion approach of the same piece of code:</p><pre>function collectOddValues(arr){<br>    let newArr = [];<br>    <br>    if(arr.length === 0) {<br>        return newArr;<br>    }<br>        <br>    if(arr[0] % 2 !== 0){<br>        newArr.push(arr[0]);<br>    }<br>        <br>    newArr = newArr.concat(collectOddValues(arr.slice(1)));<br>    return newArr;<br>}</pre><p>So this piece of code is the <strong>pure recursion</strong> version , where we replacing the <strong>helper method recursion</strong> logic with <strong>pure recursive</strong> logic , Here are few tips for writing pure recursion :</p><p>For arrays, use methods like <strong>slice, the spread operator,</strong> and <strong>concat</strong> that make copies of arrays so you do not mutate them.</p><p>We have to keep in mind that strings are immutable so you will need to use methods like <strong>slice, substr, or substring</strong> to make copies of strings.</p><p>To make copies of objects we can use <strong>Object.assign, or the spread operator.</strong></p><p>Now<strong> what about calculating Big O in case recursion ?</strong></p><p>Measuring <strong>time complexity </strong>is relatively simple. You can measure the time complexity of a recursive function as then number of recursive calls you need to make relative to the input.</p><p>Measuring <strong>space complexity</strong> is a bit more challenging. You can measure the space complexity of a recursive function as the <strong>maximum</strong> number of functions on the call stack at a given time, since the call stack requires memory.</p><p><strong>Tail Call Optimisation:</strong></p><p><strong>Tail Call Optimisation</strong> is a concept where we can optimise a recursive function. Compilers usually execute recursive procedures by using a <strong>stack</strong>. This stack consists of all the pertinent information, including the parameter values, for each recursive call. When a procedure is called, its information is <strong>pushed </strong>onto a stack, and when the function terminates the information is <strong>popped </strong>out of the stack. Thus for the non-tail-recursive functions, the <strong>stack depth</strong> (maximum amount of stack space used at any time during compilation) is more. The idea used by compilers to optimize tail-recursive functions is simple, since the recursive call is the last statement, there is nothing left to do in the current function, so saving the current function’s stack frame is of no use. So ES2015 allows for <strong>tail call optimisation</strong>, where you can make some function calls without growing the call stack. By using the <strong>return </strong>keyword in a specific fashion we can extract output from a function without keeping it on the call stack. Unfortunately this has not been implemented across multiple browsers so it is not reasonable to implement in production code.</p><p><strong>Conclusion:</strong></p><p>So let’s recap what we have learned in this blog :</p><ul><li>A recursive function is a function that invokes itself</li><li>Your recursive functions should <strong>always</strong> have a base case and be invoked with different input each time</li><li>When using recursion, it’s often essential to return values from one function to another to extract data from each function call</li><li>Helper method recursion is an alternative that allows us to use an external scope in our recursive functions</li><li>Pure recursion eliminates the need for helper method recursion, but can be trickier to understand at first.</li></ul><p>So we have covered almost all the topics which are related to recursive concept, Hope this will be helpful for you !! Please check out my Github repo for the reference of the codes discussed in this blog :</p><p><a href="https://github.com/Yudhajitadhikary/Big-O-Notation-Blog">GitHub - Yudhajitadhikary/Big-O-Notation-Blog: It&#39;s a reference repo for my Big O Notation Blog.</a></p><p>HAPPY CODING :)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=39540ad623cd" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Big O Notation in JS….]]></title>
            <link>https://yudhajitadhikary.medium.com/big-o-notation-in-js-e04b076dced1?source=rss-f54a1f93756b------2</link>
            <guid isPermaLink="false">https://medium.com/p/e04b076dced1</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[big-o-notation]]></category>
            <category><![CDATA[time-complexity]]></category>
            <category><![CDATA[performance]]></category>
            <category><![CDATA[pagespeed-insights]]></category>
            <dc:creator><![CDATA[Yudhajit Adhikary]]></dc:creator>
            <pubDate>Mon, 18 Sep 2023 12:35:38 GMT</pubDate>
            <atom:updated>2023-09-18T13:26:15.950Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ckFZ3PWssoWrWrRFU3fZQg.jpeg" /></figure><p>Hi Guys in this blog we will discuss on Big O Notation in JS , here we will cover very basic concepts on Big O Notation:</p><p><strong>1&gt; Motivate the need for something like Big O Notation</strong></p><p><strong>2&gt; Describe what Big O Notation is</strong></p><p><strong>3&gt; Simplify Big O Expressions.</strong></p><p><strong>4&gt; Define “time complexity” and “space complexity”.</strong></p><p><strong>5&gt; Evaluate the time complexity and space complexity of different algorithms using Big O Notation.</strong></p><p><strong>6&gt; Built in data structures through the lens of Big O.</strong></p><p>So let’s get started …</p><p><strong>1&gt; Motivate the need for something like Big O Notation :</strong></p><p>Let’s get motivated first :) , like <strong>why we need Big O Notation ?</strong> So let’s start with a question, <strong>Imagine we have multiple implementations of the same function. How can we determine which one is the “best?”</strong>.</p><p>So let’s see an example , we are having one problem statement like</p><p><strong>Write a function that accepts a string input and returns a reversed copy</strong></p><p>There will be multiple way to solve this problem , Whenever we are measuring a performance of a code we will classify those in a richter scale like earthQuake :) like :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*M2FL05SD79wMpv1qhiDoaw.png" /><figcaption><strong>Scale of Measuring Performance</strong></figcaption></figure><p>But it’s very informal/non technical way of defining the performance of our code , It’s important to have a precise vocabulary to talk about how our code performs for that we will be having <strong>Big O Notation</strong> to measure and determine the performance of our code.</p><p>But you may think <strong>who cares for Performance or Big O Notation?.</strong> If the code is working we should not be worry ,but that’s not the case, literally every developer cares about performance , it’s the key thing that differentiate your application from other application specially if a website is with high traffics , so with <strong>Big O Notation</strong> it’s helpful for developer on discussing trade-offs between different approaches, also When your code slows down or crashes <strong>Big O Notation</strong> actually help us identifying parts of the code that are inefficient that can help us find pain points in our applications.</p><p>Suppose we want to <strong>write a function that calculates the sum of all numbers from 1 up to (and including) some number <em>n</em></strong>. There are two ways to solve the problem :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AfVE5j9r1yZqbMW38vnARw.png" /><figcaption><strong>write a function that calculates the sum of all numbers from 1 up to (and including) some number <em>n</em></strong></figcaption></figure><p>So which one is better , before that we have to consider like what does better means, is it :</p><p><strong>a&gt; Faster ?</strong></p><p><strong>b&gt; Less memory intensive ?</strong></p><p><strong>c&gt; More Readable ?</strong></p><p>So here faster and less memory intensive will always take the fast priority for considering the performance of a piece of code.</p><p>Let’s try to see how we can measure the speed of a piece of code, first approach we can follow is by using timer by this way :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6WYDOeh7QYtKomoUpNvb9A.png" /><figcaption><strong>Measuring Performance by using timer</strong></figcaption></figure><p>Let see what we have done here , we have defined our function <strong>addUpto ()</strong> where we are passing <strong>n </strong>as parameter. we are initialising a variable <strong>total</strong> that will store the sum of n numbers . Then we are running a for loop from 1 to n-1 and adding the value of n to total in each iteration , once iteration is done we are returning the value of total . This is about definition , now for measuring the performance of function we are using performance.now function . The performance.now() method returns a high resolution timestamp in milliseconds. It represents the time elapsed since <a href="https://developer.mozilla.org/en-US/docs/Web/API/Performance/timeOrigin">Performance.timeOrigin</a> (the time when navigation has started in window contexts, or the time when the worker is run in <a href="https://developer.mozilla.org/en-US/docs/Web/API/Worker">Worker</a> and <a href="https://developer.mozilla.org/en-US/docs/Web/API/ServiceWorker">ServiceWorker</a> contexts). So what we are doing here first we are defining <strong>t1 </strong>which is storing the time when navigation has started in window contexts , then we are calling the function with 1000000000 as value of n <strong>(Note : one thing we should always consider , we should always use larger value as parameter to test the performance of a function )</strong> , then we we are defining another variable <strong>t2</strong> which is storing the time when the worker is run in <a href="https://developer.mozilla.org/en-US/docs/Web/API/Worker">Worker</a> and <a href="https://developer.mozilla.org/en-US/docs/Web/API/ServiceWorker">ServiceWorker</a> contexts . Now if we deduct <strong>t1</strong> from <strong>t2</strong> and divide it with <strong>1000 </strong>(since it will be in microsecond) we will get the function’s execution time in second , but there is a catch here , what if you are running the code in other’s machine will the result will be consistent? no right !! So there are few drawbacks on this approach of calculating performance which are as follows:</p><ul><li>Different machines will record different times</li><li>The <em>same</em> machine will record different times!</li><li>For fast algorithms, speed measurements may not be precise enough?</li></ul><p>So our next query is<strong> if not time , then what ?</strong></p><p>Rather than counting <em>seconds</em>, which are so variable…</p><p>Let’s count the <em>number</em> of simple operations the computer has to perform!</p><p>Let analyse this piece of Code :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pX6rXE-uK3RMxy-3TO7FvQ.png" /><figcaption><strong>Sum upto n 1st approach</strong></figcaption></figure><p>Let’s count the number of operation we are having in this code , one is multiplication, addition and division , so 3 simple operations, regardless of the size of <em>n.</em></p><p>Now let’s see another approach of same problem:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HuuezdGRLxWaQ7VU53h4KA.png" /><figcaption><strong>Sum upto n 2nd approach</strong></figcaption></figure><p>so += will have n additions and n assignments , i++ will have n additions and n assignments let total= 0 will be 1 assignment , let i=1 will have i assignment, i ≤n will have n comparisons. So depending on what we count, the number of operations can be as low as 2<em>n</em> or as high as 5<em>n</em> + 2. But regardless of the exact number, the number of operations grows roughly <em>proportionally</em> <em>with n. </em>If <em>n</em> doubles, the number of operations will also roughly double. So we can say this function is totally dependent on the value of n. If we take n=100 , 5n+2 will be 502 but when n=100000 5n+2 will be 500002. So we can see value of 5n+2 is total dependent on value of n .</p><p><strong>2&gt; Describe what Big O Notation is:</strong></p><p>Okay Now it’s time to Introduce ….. <strong>Big O Notation</strong></p><p>Big O Notation is a way to formalize fuzzy counting , It allows us to talk formally about how the runtime of an algorithm grows as the inputs grow.</p><p><strong>Big O Notation Definition</strong></p><p>We say that an algorithm is <strong>O(f(n))</strong> if the number of simple operations the computer has to do is eventually less than a constant times <strong>f(n)</strong>, as <strong>n</strong> increases</p><ul><li>f(n) could be linear (f(n) = n)</li><li>f(n) could be quadratic (f(n) = n )</li><li>f(n) could be constant (f(n) = 1)</li><li>f(n) could be something entirely different!</li></ul><p>Let’s go through few examples on the same :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/932/1*1YktiP43u67gzeVL2dcy-w.png" /><figcaption><strong>Sum upto n 1st approach</strong></figcaption></figure><p>Here irrespective of any value of n , the number of operation will be 3 , so <strong>f(n)</strong> is not dependent on n , so time complexity will be <strong>O(1)</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/787/1*JT4DJ3MGA3tdi8kRIqCRXA.png" /><figcaption><strong>Sum upto n 2nd approach</strong></figcaption></figure><p>Here number of operations is (eventually) bounded by a multiple of <em>n. </em>So<em> </em>time complexity will be <strong>O(n)</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KtaqlN2BCBvcWDrQv1BpRQ.png" /><figcaption><strong>Printing elements from 0 to n and then from n to 0</strong></figcaption></figure><p>Here also number of operations is (eventually) bounded by a multiple of <em>n , </em>so time complexity will be <strong>O(n)</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FsiwPWs7n66xs5cZK1K54w.png" /><figcaption><strong>Printing all Pairs</strong></figcaption></figure><p>Here O(n) operation is inside of an O(n) operation. so time complexity will be<strong> O(n²)</strong>.</p><p><strong>3&gt; Simplify Big O Expressions</strong></p><p>When determining the time complexity of an algorithm, there are some helpful rule of thumbs for big O expressions.</p><p>These rules of thumb are consequences of the definition of big O notation.</p><p><strong>a&gt; Constant does not matter</strong></p><p>If we have a time complexity like <strong>O(2n)</strong> we can ignore the constant part 2 and consider it as <strong>O(n)</strong>. <strong>O(500)</strong> will become <strong>O(1) </strong>constant time complexity , <strong>O(13n²)</strong> will become <strong>O(n²)</strong> .</p><p><strong>b&gt; Smaller terms does not matter</strong></p><p>If we have a time complexity like <strong>O(n+10)</strong> we can ignore the smaller terms 10 and can consider it as <strong>O(n)</strong>. <strong>O(1000n+50 )</strong> will become <strong>O(n)</strong> and <strong>O(n²+5n+8)</strong> will become <strong>O(n²)</strong>.</p><p>Analysing complexity with big O can get complicated , so there are several rules of thumb that can help us on that , These rules won’t always work, but are a helpful starting point. So let see the <strong>Big O Shorthands</strong>….</p><p><strong>a&gt; Arithmetic operation are constant :</strong> Let’s try to understand in details , computer used to take same amount of time for running 2+2 and 10000+10000. So whatever there is arithmetic operation execution it will have constant time, it’s not dependent on the values of the parameters associated in the operation.</p><p><strong>b&gt; Variable assignment is constant : </strong>Which actually means the time complexity of assigning x=2 and x=10000 is same.</p><p><strong>c&gt; Accessing elements in an array (by index) or object (by key) is constant:</strong></p><p>For array we used to access the elements by index and for object we used to access elements by key , so time complexity of the accessing elements of both array and object will be same .</p><p><strong>d&gt; In a loop, the complexity is the length of the loop times the complexity of whatever happens inside of the loop:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FsiwPWs7n66xs5cZK1K54w.png" /><figcaption><strong>Printing all Pairs</strong></figcaption></figure><p>In this example , the complexity will be n (length of the loop ) times n ( since it’s having another loop inside) that is O(n²).</p><p>Let’s see two scenarios to improve our understanding on time complexity :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/981/1*vb5ETcYfWp5sIKBB2Ts7vg.png" /><figcaption><strong>Print logarithmic value at least 5 times</strong></figcaption></figure><p>In this function execution will happen at least 5 times to at most n times, So we can say the time complexity of this code is <strong>O(n)</strong> , because it’s totally proportional to value of n , it will run 5 times if n=1,2,3,4,5 and it will run n times if n &gt;5. Let’s see another example:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/945/1*FWFtCYq7a7TnyT7aP3K5FA.png" /><figcaption><strong>Print logarithmic value at most 5 times</strong></figcaption></figure><p>In this function execution will happen maximum 5 times , regardless of any value of n , because it will run n times if n=1,2,3,4,5 and it will run 5 times if n &gt;5. So If we ignore the smaller terms , the complexity of this code will be<strong> O(5)</strong> eventually that will be <strong>O(1)</strong> constant time.</p><p>Now let’s see the graph of time complexity :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Cgc-ramsYIIShjNwY0wtoQ.png" /><figcaption><strong>Time Complexity Graph</strong></figcaption></figure><p>The Big O chart above shows that <strong>O(1)</strong>, which stands for constant time complexity, is the best. This implies that your algorithm processes only one statement without any iteration. Then there’s <strong>O(log n)</strong>, which is good, and others like it, as shown below:</p><ul><li><strong>O(1)</strong> — Excellent/Best</li><li><strong>O(log n)</strong> — Good</li><li><strong>O(n)</strong> — Fair</li><li><strong>O(n log n)</strong> — Bad</li></ul><p>You now understand the various time complexities, and you can recognise the best, good, and fair ones, as well as the bad and worst ones (always avoid the bad and worst time complexity).</p><p>The next question that comes to mind is how you know which algorithm has which time complexity.</p><ul><li>When your calculation is not dependent on the input size, it is a constant time complexity (<strong>O(1)</strong>).</li><li>When the input size is reduced by half, maybe when iterating, handling <a href="https://joelolawanle.com/posts/recursion-in-javascript-explained-for-beginners">recursion</a>, or whatsoever, it is a logarithmic time complexity (<strong>O(log n)</strong>).</li><li>When you have a single loop within your algorithm, it is linear time complexity (<strong>O(n)</strong>).</li><li>When you have nested loops within your algorithm, meaning a loop in a loop, it is quadratic time complexity (<strong>O(n²)</strong>).</li></ul><p><strong>4&gt; Define “time complexity” and “space complexity”</strong></p><p>So far, we’ve been focusing on <strong>time complexity </strong>that means<strong> </strong>how can we analyse the <em>runtime</em> of an algorithm as the size of the inputs increases?</p><p>We can also use big O notation to analyse <strong>space</strong> <strong>complexity</strong>: how much additional memory do we need to allocate in order to run the code in our algorithm?</p><p>Sometimes you’ll hear the term <strong>auxiliary space complexity</strong> to refer to space required by the algorithm, not including space taken up by the inputs. Unless otherwise noted, when we talk about space complexity, technically we’ll be talking about auxiliary space complexity.</p><p>Let’s see the<strong> rules of Thumb </strong>when it comes for space complexity :</p><p>a&gt; Most primitives (booleans, numbers, undefined, null) are constant space.</p><p>b&gt; Strings require O(<em>n</em>) space (where <em>n</em> is the string length).</p><p>c&gt; Reference types are generally O( <em>n</em>), where n is the length (for arrays) or the number of keys (for objects).</p><p><strong>5&gt; Evaluate the space complexity of different algorithms using Big O Notation</strong></p><p>Let’s see some examples:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*K-LUIaTh_FrmDJLhgFLTIw.png" /><figcaption><strong>Sum of elements of array</strong></figcaption></figure><p>In this piece of code total is one number and i is another number , so space complexity of this piece of code will be O(1) space.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*d7vtFU9YtRL6RBgFlPQ0ig.png" /><figcaption><strong>Creating a new array by doubling the value of elements of array</strong></figcaption></figure><p>Here the space complexity of the piece of code will be O(n) space where n is number of elements in arr (arr.length) .</p><p><strong>6&gt; Built in data structures through the lens of Big O.</strong></p><p>Now that we’ve covered BIG O , Let’s spend a couple minutes analysing the things we do all the time in JS: working with Arrays, Objects, and built-in methods.We spend a lot of this course talking about data structures.</p><p>Let’s start by discussing the ones we get for free, so we will discuss:</p><ul><li>How objects and arrays work, through the lens of Big O</li><li>Why adding elements to the beginning of an array is costly</li><li>Compare and contrast the runtime for arrays and objects, as well as built-in methods.</li></ul><p><strong>Big O of Objects :</strong></p><p>Objects are unordered collection of key value pairs .</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rVqwxYQgTyFhVGkBNeC2EA.png" /><figcaption><strong>Sample Object</strong></figcaption></figure><p><strong>When to use objects:</strong></p><ul><li>When you don’t need order.</li><li>When you need fast access / insertion and removal.</li></ul><p>When you don’t need any ordering, objects are an excellent choice!</p><p>Let’s see what is the time complexity of several operation we can perform on Object:</p><p><strong>a&gt;Insertion </strong>— Insertion of any element in object will always be constant time complexity <strong>O(1).</strong></p><p><strong>b&gt;Removal</strong> — Removal of any element in object will always be constant time complexity <strong>O(1).</strong></p><p><strong>c&gt;Searching</strong> — Searching any element in object will be<strong> O(n)</strong> where n is number of key value pairs present in the object.</p><p><strong>d&gt; Access</strong> — Like insertion and deletion, accessing an element in object will be <strong>O(1).</strong></p><p><strong>Big O of Object Method:</strong></p><p><strong>a&gt; Object.keys </strong>— The Object.keys() static method returns an array of a given object&#39;s own enumerable string-keyed property names. So time complexity of Object. keys function will be <strong>O(N)</strong></p><p><strong>b&gt; Object.values</strong> —The Object.values() static method returns an array of a given object’s own enumerable string-keyed property values. So time complexity of Object.values function will be <strong>O(N)</strong></p><p><strong>c&gt; Object.entries</strong> — The Object.entries() static method returns an array of a given object&#39;s own enumerable string-keyed property key-value pairs. So time complexity of Object.entries function will be <strong>O(N)</strong></p><p><strong>d&gt; hasOwnProperty</strong> — The hasOwnProperty() method of <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object">Object</a> instances returns a boolean indicating whether this object has the specified property as its own property. So time complexity of <strong>hasOwnProperty </strong>function will be <strong>O(1)</strong></p><p><strong>Big O of Array:</strong></p><p>Array is ordered list of elements:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7elZgIjjhIMZleBt1Ca3lQ.png" /><figcaption><strong>Sample Array</strong></figcaption></figure><p><strong>When to use arrays:</strong></p><ul><li>When you need order</li><li>When you need fast access / insertion and removal (sort of….)</li></ul><p>Let’s see what is the time complexity of several operation we can perform on Array:</p><p><strong>a&gt;Insertion</strong> — Insertion of any element in array depends on where the element will be inserted . Adding element in the first position will have more time complexity than adding element at the last position, because adding element from first position will include reindexing of all elements in array.</p><p><strong>b&gt;Removal </strong>— Like insertion, removal of any element in array depends on where the element will be removed. Removing element from the first position will have more time complexity than removing element from the last position, because removing element from first position will include reindexing of all elements in array.</p><p><strong>c&gt;Searching</strong> — Searching any element in array will be<strong> O(n)</strong> where n is number of elements present in the array.</p><p><strong>d&gt;Access </strong>— Accessing an element in array will be <strong>O(1).</strong></p><p><strong>Big O of Array Operations:</strong></p><ul><li><strong>push</strong> — The push() method of <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array">Array</a> instances adds the specified elements to the end of an array and returns the new length of the array. So time complexity of Array.push function will be <strong>O(1)</strong></li><li><strong>pop</strong> — The pop() method of <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array">Array</a> instances removes the last element from an array and returns that element. This method changes the length of the array. So time complexity of Array.pop function will be <strong>O(1)</strong></li><li><strong>shift</strong> — The shift() method of <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array">Array</a> instances removes the first element from an array and returns that removed element. This method changes the length of the array. So time complexity of Array.shift function will be <strong>O(N)</strong></li><li><strong>unshift</strong> — The unshift() method of <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array">Array</a> instances adds the specified elements to the beginning of an array and returns the new length of the array. So time complexity of Array.unshift function will be <strong>O(N)</strong></li><li><strong>concat</strong> — The concat() method of <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array">Array</a> instances is used to merge two or more arrays. This method does not change the existing arrays, but instead returns a new array. So time complexity of Array.concat function will be <strong>O(N).</strong></li><li><strong>slice </strong>— The slice() method of <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array">Array</a> instances returns a <a href="https://developer.mozilla.org/en-US/docs/Glossary/Shallow_copy">shallow copy</a> of a portion of an array into a new array object selected from start to end (end not included) where start and end represent the index of items in that array. The original array will not be modified. So time complexity of Array.slice function will be <strong>O(N)</strong></li><li><strong>splice</strong> — The splice() method of <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array">Array</a> instances changes the contents of an array by removing or replacing existing elements and/or adding new elements in place . So time complexity of Array.splice function will be <strong>O(N)</strong></li><li><strong>sort </strong>—The sort() method of <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array">Array</a> instances sorts the elements of an array <em>in place</em> and returns the reference to the same array, now sorted. The default sort order is ascending, built upon converting the elements into strings, then comparing their sequences of UTF-16 code units values. So time complexity of Array.sort function will be <strong>O(N * log N).</strong></li><li><strong>forEach/map/filter/reduce/etc</strong>. — For all mapping functions of array the time complexity will be <strong>O(N).</strong></li></ul><p><strong>Summary :</strong></p><ul><li>To analyse the performance of an algorithm, we use Big O Notation</li><li>Big O Notation can give us a high level understanding of the time or space complexity of an algorithm</li><li>Big O Notation doesn’t care about precision, only about general trends (linear? quadratic? constant?)</li><li>The time or space complexity (as measured by Big O) depends only on the algorithm, not the hardware used to run the algorithm</li></ul><p><strong>Conclusion:</strong></p><p>That is really long one , But congrats!! finally we did it . So now I think we will have a better understanding on big O Notation . But this is not enough, we have mostly covered the theoretical part of <strong>Big O Notation </strong>, writing a performance efficient code keeping Big O Notation in mind really needs practice and hands on Experience. Please check the link below its really helpful for analysing time complexity graphically for different functions:</p><p><a href="https://rithmschool.github.io/function-timer-demo/">Big O Introduction</a></p><p>I am attaching my GitHub repo down below for the codes discussed in the blog :</p><p><a href="https://github.com/Yudhajitadhikary/Big-O-Notation-Blog">GitHub - Yudhajitadhikary/Big-O-Notation-Blog: It&#39;s a reference repo for my Big O Notation Blog.</a></p><p>HAPPY CODING !!!! :)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e04b076dced1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Let’s get started with Algolia…]]></title>
            <link>https://yudhajitadhikary.medium.com/lets-get-started-with-algolia-517b9c6984c3?source=rss-f54a1f93756b------2</link>
            <guid isPermaLink="false">https://medium.com/p/517b9c6984c3</guid>
            <category><![CDATA[algolia]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[search]]></category>
            <category><![CDATA[algolia-search]]></category>
            <dc:creator><![CDATA[Yudhajit Adhikary]]></dc:creator>
            <pubDate>Sun, 01 May 2022 12:37:28 GMT</pubDate>
            <atom:updated>2022-05-01T13:00:59.170Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/670/1*PIcs9uQuDg5twaOeVmDidw.jpeg" /></figure><p>Hi Guys, today we will be discussing about a wonderful search and recommendation service, <strong>Algolia</strong>. Algolia empowers Builders with the Search and Recommendation services they need to build world-class experiences.</p><p>So we will divide your discussion into seven parts:</p><p><strong>1. What is Algolia ?</strong></p><p><strong>2. How to push data in Algolia using API ?</strong></p><p><strong>3. How to implement Searching in Algolia ?</strong></p><p><strong>4. How to implement Filtering in Algolia ?</strong></p><p><strong>5. How to implement Sorting in Algolia ?</strong></p><p><strong>6. Demo</strong></p><p><strong>7. Conclusion</strong></p><p>So let Begin…..</p><h3><strong>1. What is Algolia ?</strong></h3><p>Algolia is a hosted search engine that offers full-text, numerical, and faceted search. Algolia’s powerful API lets us quickly and seamlessly implement search within our websites and mobile applications. Algolia also have analytical capable of delivering real-time results from the first keystroke.</p><h3><strong>2. How to push data in Algolia using API ?</strong></h3><p>Algolia provides several ways to push data in their portal dashboard . The data can be pushed manually or using api. We will see in our demo how it is done through api. Algolia used to store data in a collection called <strong>index</strong>. We can also replicate an index , these replicated index are mostly used for sorting. Algolia is having a built-in function <strong>replaceAllObjects()</strong> which used to push all the data from json or from any other api to algolia. We will be seeing how this function works in our demo.</p><pre>index.replaceAllObjects(array <a href="https://www.algolia.com/doc/api-reference/api-methods/replace-all-objects/#method-param-objects">objects</a>)<br><br>index.replaceAllObjects(array <a href="https://www.algolia.com/doc/api-reference/api-methods/replace-all-objects/#method-param-objects">objects</a>, {<br>    // All the following parameters are optional<br>    <a href="https://www.algolia.com/doc/api-reference/api-methods/replace-all-objects/#method-param-safe">safe</a>: bool,<br>    // + any <a href="https://www.algolia.com/doc/api-reference/api-methods/replace-all-objects/#method-param-requestoptions">requestOptions</a><br>})</pre><h3>3. How to implement Searching in Algolia ?</h3><p>In order to implement search in Algolia, we have to define searchable attributes in our Algolia portal , like whenever user type something in the search bar , the search result should come according to searchable attributes value . We can also give preference if we want to add multiple searchable attributes in the portal. There are two ways to define searchable attributes in Algolia , one is by added searchable attributes manually in the portal, or using <strong>setSettings() </strong>function to do the same through API.</p><pre>index.setSettings({ &#39;customRanking&#39;: [&#39;desc(followers)&#39;] }, {<br>  forwardToReplicas: <strong>true</strong><br>}).then(() <strong>=&gt;</strong> {<br>  <em>// done</em><br>});</pre><h3>4. How to implement Filtering in Algolia ?</h3><p>In Algolia Filtering is handled by facets. In order to allow Algolia to perform facetting we have to define Attributes for faceting on Algolia portal. We can also use <strong>setSettings()</strong> function just like this to define our Attributes for faceting.</p><pre>index.setSettings({<br>  attributesForFaceting: [&#39;genre&#39;, &#39;author&#39;]<br>});</pre><h3>5. How to implement Sorting in Algolia ?</h3><p>So for implementing sorting like sort by price , sort by name in Algolia, we have to create replica of the parent index, like let’s say we are having an index for product called productsIndices , we want to perform sorting by price and by name, So what we can do we can create two replica index from productIndices one for sort by price, and one for sort by name. And we can give custom ranking from <strong>Ranking and Sorting </strong>tab in <strong>Configuration </strong>from our dashboard, we will be seeing those later, Just we have to define which parameter let’s say price or name should come in which order (ascending or descending order). So what we have to do we will fetch data from that particular index , like when there is no sorting options selected we will take data from productIndices, if now user clicks on sort by price we will fetch data from that particular replica of productIndices which is specified to handle the price sorting.</p><p>Now enough theory , to make the things clearer we will be creating a small application that performs pushing, searching , sorting , filtering using Algolia.</p><p>So let’s get started …</p><h3>6. Demo</h3><p>Now it’s demo time , let’s start coding together , so open your vsts we will be first create our very basic react boilerplate. So we have to run</p><h4>npx create-react-app &lt;Project name&gt;</h4><p>once it’s done we will be having a simple react boilerplate , now we have to do <strong>cd &lt;tab&gt; enter </strong>then run <strong>npm run start</strong> to run our application to localhost 3000.</p><p>So in order to start with algolia we have to install algolia , so to do that run :</p><p><strong>npm i algolia</strong></p><p>So now our basic boilerplate is up and running , now let see the folder structure of our code base:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Xi3Pn5IPIvr0IqHWzIrmmQ.png" /></figure><p>Mostly this codebase is same as react boilerplate, only change we have done is we have added adapter folder which is having the adapter files. <strong>algolia.adapter.js</strong> is having functions to fetch data from algolia. <strong>algoliaIndexManager.js </strong>is having algolia class object where we have defined few variables and methods . <strong>algoliaClient.js</strong> is defining the algolia client we will be using to fetch the data , where as <strong>pushingdata.js</strong> is having function to push data to algolia. Let’s first do the setup for Algolia in our algolia portal:</p><p>So we will first go to this url:</p><p><a href="https://www.algolia.com/">Site Search &amp; Discovery powered by AI</a></p><p>Here we have to login , we can take the free trial version for learning purpose .</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tMOubyBDUwq6cNfy4f5s7w.png" /></figure><p>When we are done with login there will be a default space already created for use.We can use the same .</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Z_Rxbd51E1VgySmHWOFMYA.png" /></figure><p>So Now if we scroll down we will see there in <strong>Settings</strong> in left side bottom. If we click on that we will get an option <strong>API Keys</strong> where we will get all the Api key required to make our application working.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*G65SQpwV_nkcUje02Ofqlw.png" /></figure><p>We need two Api Keys Admin API Key and Application Id. Now let’s put those in our codebase and start creating our client, <strong>AlgoliaClient.js</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/33aa6c24bd95190e0e7e24e320d749a1/href">https://medium.com/media/33aa6c24bd95190e0e7e24e320d749a1/href</a></iframe><p>In <strong>AlgoliaClient.js </strong>, we have defined a function <strong>getWriteClient()</strong> where we are declaring our Algolia client, then we are returning the client. Finally we are export getWriteClient that will return the algolia client.</p><p>Now let see the <strong>datapushing.js</strong> the file which is having scripts to push data to algolia from our <strong>data.js</strong>.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/07f0dfd2e6105d608012aca5ae885309/href">https://medium.com/media/07f0dfd2e6105d608012aca5ae885309/href</a></iframe><p>Now let’s see the <strong>datapushing.js</strong> :</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/915d84a4a6b7e548f0af3801126fdb7f/href">https://medium.com/media/915d84a4a6b7e548f0af3801126fdb7f/href</a></iframe><p>In <strong>datapushing.js</strong>, we are pushing data to our algolia dashboard, in <strong>getFieldObject()</strong> we are creating key , value pair that we are pushing in algolia. <strong>push()</strong> is pushing data into algolia, in this push function we are checking if data.length &gt;0 ,we are declaring variable <strong>pushedData</strong> that will store the pushed data. Then we are importing <strong>replaceAll</strong>, <strong>setSettings</strong> and <strong>createReplica</strong> methods from <strong>IndexManager.js </strong>which defines the algolia class object. Then we are mapping through the data and for each node we are pushing node in pushedData array, we are calling the <strong>replaceAll</strong> function with pushedData as argument. Similarly we are calling <strong>setSettings</strong> function with an array having ‘name’ as argument, finally we are calling <strong>createReplica</strong> function with an array having values <strong>‘Demo-Index-desc(name)’</strong> and <strong>‘Demo-Index-desc(price)’</strong>. We will be looking into those functions in <strong>algoliaIndexManager.js.</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8d5d15d078204c4f7d0f32d0305f5a21/href">https://medium.com/media/8d5d15d078204c4f7d0f32d0305f5a21/href</a></iframe><p>In <strong>algoliaIndexManager.js</strong> , we have defining our algolia class object ,we defining variables and methods like <strong>name</strong>, <strong>index</strong>, <strong>replaceAll()</strong>, <strong>setSettings()</strong> and <strong>createReplica (). </strong>Inside our IndexManger class we are<strong> </strong>setting name as the name that is coming as argument , then we are setting the index by calling <strong>getWriteClient()</strong> with this.name, <strong>this name</strong> will be the name of the index we want to create. We are defining <strong>replaceAll()</strong>, this function will actually store the records in our Index ,this.index is having the current index so there we are calling algolia’s built-in function <strong>replaceAllObjects</strong> with data and configuration settings coming as argument of the method.</p><p>In <strong>setSettings()</strong> we are actually setting the searchable attributes of our index using algolia’s built-in <strong>setSettings</strong> function.</p><p>Similarly <strong>createReplica()</strong> is used to create replica of our Index (these replicas are used for Sorting). So we having created two replicas from our Index <strong>(Demo-Index)</strong> ,<strong>‘Demo-Index-desc(name)’</strong> and <strong>‘Demo-Index-desc(price)’</strong>.</p><p>Please note to push data into algolia we have to go to the respective path ,where the file is present and run <strong>node datapushing.js </strong>from our terminal, Once you run that and everything went well , you will see records coming on Algolia portal dashboard.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SfJO7kZBRTEUeew7kTlNqg.png" /></figure><p>Now if you can see there are two replicas of our <strong>Demo-Index</strong> index, <strong>Demo-Index-desc(name)</strong> and <strong>Demo-Index-desc(price)</strong>. <strong>Demo-Index-desc(name)</strong> will be having the data sorted name wise , where as <strong>Demo-Index-desc(price) </strong>will be having the data sorted price wise. So to do that we have to go to the <strong>Configuration → Ranking and Sorting</strong> , and will have to add custom ranking like this :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_Tjve2OdCNbH9mGr2dO9-w.png" /></figure><p>Now let’s see App.js:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4035ae668e4fb24d331a571a74658389/href">https://medium.com/media/4035ae668e4fb24d331a571a74658389/href</a></iframe><p>In <strong>App.js</strong> we are defining our dom structure of our application , we will be keeping your application simple. Our application will be having a product listing page having all products listed . We can search a product by it’s name, we can also filter products based on the category of the products ,also we can sort products by price and by name. So we have imported <strong>getAlgoliaResults() </strong>and <strong>getAlgoliaSearchResults()</strong> from <strong>algolia.adapter.js </strong>, these two functions are actually fetching data from Algolia. Inside our App function we are defining three states <strong>data</strong> ,<strong>loading</strong> , <strong>inputQuery</strong>. <strong>data</strong> represents the product data we will be rendering in the listing page ,<strong>loading</strong> represents the boolean data which indicates when the page is loading or fetching data from algolia and <strong>inputQuery</strong> represents the query we are searching on our search box . Inside <strong>useEffect()</strong> we can calling <strong>loadData()</strong> function , where we fetching the initial data from algolia that we will be rendering on first load. So first we setting loading as true , then we are fetching data from algolia by calling <strong>getAlgoliaResults()</strong> function, once we get the data we using setData to set the state data ,then we are setting loading as false. Now let go down to the return section to see the dom structure ,we have added a title , then we have placed an input field which will be our search box. So whenever user is typing something in the input field onChange of it we are calling <strong>handleInputChange()</strong> function. In <strong>handleInputChange()</strong> we are setting the value of inputQuery with the query. On clicking the Search button we are calling <strong>searchResult()</strong>. In <strong>searchResult()</strong> we are getting the data according to query (inputQuery) we are passing in search box. Then we are having few filtering options Like Shirt, Sneaker, Bag, Watch, Kefiah and All (For all products) ,we have kept buttons for each product category to perform filtering, onClick of those buttons we are calling <strong>SelectProduct1()</strong> by passing the particular category name as an argument. In <strong>SelectProduct1()</strong> we are doing faceting for filtration , So we are passing two parameters to perform the faceting, one is <strong>facets </strong>array that contains the parameters which will be considered as facets and <strong>facetFilters </strong>another array which contains the facet category according to which filtering should happen ,for example <strong>facetFilters:[facetCollection:watch]</strong> means show those products which are having <strong>watch</strong> in the array <strong>facetCollection</strong>. We have also implemented the sorting functionality where we are sorting the data according to product’s name and price. <strong>handleSort()</strong> function is handling the sorting functionality , inside <strong>handleSort()</strong> function we are calling <strong>getAlgoliaResults</strong> function to get the data accordingly to the name we are passing as argument , like if the name is price, we will be fetching data from that specific Index that is containing product data sorted according to their price .</p><p>So lastly we are just mapping through our data and rendering our product cards having product image, name and price. The functions for fetching data from algolia is defined in <strong>algolia.adapter.js</strong> let ‘s have a look on that .</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/660abd2f1457a1f86e8c1c237f6facb9/href">https://medium.com/media/660abd2f1457a1f86e8c1c237f6facb9/href</a></iframe><p>So in <strong>algolia.adapter.js</strong> we are having two functions,<strong> getAlgoliaResults()</strong> and <strong>getAlgoliaSearchResults()</strong>. <strong>getAlgoliaResults()</strong> is used to fetch data according to the request-object (facetting) and name (sorting) passed as argument, so we are first determining the name of the index we will be using according to the sorting option user have selected (sorting) ,then we are initiating our Index with that name , and calling algolia built-in<strong> search</strong> function with the request-body coming as an argument (facetting) to get filtered data. <strong>getAlgoliaSearchResults()</strong> is used to handle the search functionality of our application , so we are just calling the same built-in <strong>search</strong> function with the query string instead of keeping the string empty. So we have done the whole code base walk-though , Now let’s see the output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RXSVD5XU2z3z1P_BG-d2wg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*meaVSg7OVOhXCBUAB0XB9Q.png" /></figure><h4>7. Conclusion</h4><p>Ohh Okay that’s was a lengthy one , So in this article we have discussed the basic concepts of how to perform searching , sorting and filtering functionality using Algolia. But I will suggest please go through the documentation of algolia first before getting started with it ,it is very nice, helpful and descriptive :</p><p><a href="https://www.algolia.com/doc/">Algolia Documentation</a></p><p>I am attaching the GitHub code link as a reference of this article:</p><p><a href="https://github.com/Yudhajitadhikary/Algolia-Blog">GitHub - Yudhajitadhikary/Algolia-Blog: It&#39;s the basic implementation of algolia having searching , filtering and sorting functionality.</a></p><p>HAPPY CODING….:)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=517b9c6984c3" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to create routes using Express and Postman..]]></title>
            <link>https://yudhajitadhikary.medium.com/how-to-create-routes-using-express-and-postman-5f200b3b85b6?source=rss-f54a1f93756b------2</link>
            <guid isPermaLink="false">https://medium.com/p/5f200b3b85b6</guid>
            <category><![CDATA[restful-api]]></category>
            <category><![CDATA[postman]]></category>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[expressjs]]></category>
            <category><![CDATA[mongodb]]></category>
            <dc:creator><![CDATA[Yudhajit Adhikary]]></dc:creator>
            <pubDate>Sat, 11 Sep 2021 16:08:39 GMT</pubDate>
            <atom:updated>2021-09-11T16:08:39.714Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KY8GcnRglBI9P1-ku6GFgw.png" /></figure><p>In this article we will see how to develop api endpoint using <strong>NodeJS</strong> and <strong>Postman</strong>. We will divide this article into several parts so that it’s easy for us to understand.</p><p>1. Brief definition of NodeJs.</p><p>2. Brief definition of Postman</p><p>3. Setting up Express and Basic routes</p><p>4. API and Restful API Design</p><p>5. Middleware and the Request Response Cycle</p><p>6. Implementing Post,Patch, Get and Delete request in Api</p><p>7. Conclusion</p><ol><li><strong>Brief definition of Express:</strong></li></ol><p>“ <strong>Express is a fast, unopinionated minimalist web framework for Node.js</strong> ” — official web site: <a href="https://expressjs.com/">Expressjs.com</a></p><p><strong>Express.js</strong> is a web application framework for Node.js. It provides various features that make web application development fast and easy which otherwise takes more time using only Node.js.</p><p><strong>Express.js </strong>is based on the Node.js middleware module called <strong><em>connect</em></strong> which in turn uses http module. So, any middleware which is based on connect will also work with Express.js. For more details please go through the official website .</p><p><a href="https://expressjs.com/">Express.js · Node.js web application framework</a></p><p><strong>2. Brief definition of Postman:</strong></p><p><strong>Postman</strong> is an API client that makes it easy for developers to create, share, test and document APIs. This is done by allowing users to create and save simple and complex HTTP/s requests, as well as read their responses. The result — more efficient and less tedious work. For more details please go through the documentation .</p><p>3. <strong>Setting up Express and Basic routes:</strong></p><p>After a brief description of what are Postman and NodeJs, Let’s see how our final codebase will actually look like:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/432/1*fbHRxT6dCZtxs4s9cJCe-w.png" /><figcaption>Folder structure</figcaption></figure><p>So before we start with explanation of our codebase folder , let first understand what is our aim ,what we are going to create ? We will actually create a tour management api , where we will perform all the <strong>CRUD</strong> (Create,Read,Update,Delete ) operations like creating a new tour , updating an existing tour, deleting a tour etc using Express js and we will test our api ends on Postman. So our codebase will be having a <strong>controller </strong>folder which will have the controller functions like creating , updating , deleting tours, we are having two files inside, <strong>tourController.js</strong> will contain the controller functions of tours, where as <strong>userController.js</strong> will contain the controller functions of users. <strong>dev-data</strong> is a folder where we are having some dummy tour data that we will populating in our api as the sample tour dataset, <strong>tours-simple.json</strong> is having those sample data . <strong>node-modules </strong>will be created when we will run <strong>npm i</strong> on our integrated terminal of vscode, we will come on that part later . <strong>Public</strong> folder is having two html files these are not required for now , I have added that just to show you some add-on feature of express like how we can show html page in our api endpoint , about this we will discuss in the last section of this article. Next <strong>routes</strong> folder is having the endpoints means the router which we will create and will test in Postman. <strong>tourRoutes.js</strong> will contain the routes for tours , whereas <strong>userRoutes.js </strong>will contain the routes for users. <strong>.eslintrc.json</strong> is the file where we can config the eslint rules of our application, we will not be discussing about eslint in this article our main focus will be on creating restful api. Similarly <strong>.prettierrc</strong> is the file to define prettier which are helpful to resolve lint issue of our application. <strong>app.js</strong> is the file which will be responsible for setting up our express js , <strong>config.env</strong> is the environment config file where we used to keep all the constant values which will be same throughout the application , <strong>config.env</strong> also contains constants that changes depending on which environment our application is running like development or production. <strong>package.json </strong>is used to store the metadata associated with the project as well as to store the list of dependency packages. In order to add dependency packages to your projects, you need to create <strong>package.json</strong> file. The file makes it easy for others to manage and install the packages associated with the project.While <strong>app.js </strong>is responsible to setup express in our application , <strong>server.js</strong> is responsible to run our express application in the server .</p><p>So first we will create our package.json file , so we will open our integrated terminal of vscode and run <strong>npm init</strong> , this command will ask some questions to create our package.json file, you can answer those or can skip by pressing enter. Finally you will see a <strong>package.json</strong> file will get created.So now we have to install our main package <strong>express</strong>, to install that we will run <strong>npm i express</strong> in our terminal.</p><p>Now we will create our <strong>app.js</strong> file:</p><pre>const express = require(&#39;express&#39;);<br>const morgan = require(&#39;morgan&#39;);</pre><pre>const tourRouter = require(&#39;./routes/tourRoutes&#39;);<br>const userRouter = require(&#39;./routes/userRoutes&#39;);</pre><pre>const app = express();<br>console.log(app.get(&#39;env&#39;))</pre><pre>// 1) MIDDLEWARES<br>if (process.env.NODE_ENV === &#39;development&#39;) {<br>  app.use(morgan(&#39;dev&#39;));<br>}</pre><pre>app.use(express.json());<br>app.use(express.static(`${__dirname}/public`));</pre><pre>app.use((req, res, next) =&gt; {<br>  console.log(&#39;Hello from the middleware 👋&#39;);<br>  next();<br>});</pre><pre>app.use((req, res, next) =&gt; {<br>  req.requestTime = new Date().toISOString();<br>  next();<br>});</pre><pre>// 3) ROUTES<br>app.use(&#39;/api/v1/tours&#39;, tourRouter);<br>app.use(&#39;/api/v1/users&#39;, userRouter);</pre><pre>module.exports = app;</pre><p>In <strong>app.js, </strong>we are first importing <strong>express</strong> and <strong>morgan</strong> ,morgan is HTTP request logger middleware for node.js, this package is used to see req data right in console.Then we are importing the routes of our application. We are creating variable called app<strong> </strong>which represent the result of calling express. <strong>app.get(‘env’)</strong> is the variable which determines in which environment we are running our code.</p><pre>if (process.env.NODE_ENV === &#39;development&#39;) {<br>  app.use(morgan(&#39;dev&#39;));<br>}</pre><p>We are checking if the node environment is development , we are using morgan middleware.</p><pre>app.use(express.json());</pre><p>it a method inbuilt in express to recognise the incoming Request Object as a <strong>JSON</strong> Object . This function is the first middleware which we are using in our application.</p><pre>app.use(express.static(`${__dirname}/public`));</pre><p>by this we are telling express to take all static files from public folder of our codebase.</p><pre>app.use((req, res, next) =&gt; {<br>  console.log(&#39;Hello from the middleware 👋&#39;);<br>  next();<br>});</pre><pre>app.use((req, res, next) =&gt; {<br>  req.requestTime = new Date().toISOString();<br>  next();<br>});</pre><p>We are creating a middleware function we will discuss about what is middleware later.</p><pre>app.use(&#39;/api/v1/tours&#39;, tourRouter);<br>app.use(&#39;/api/v1/users&#39;, userRouter);</pre><p>Then we are define the base routes of our application separately for tours and users , we will look into tours routes in this article .We are adding router from the respective route file . Like let’s assume we are having a route like <strong>/api/v1/tours/viewTours</strong> to show all tours ,then the base route of the url is <strong>/api/v1/tours</strong> which will be same for all routes related to tours and the remaining part is <strong>/viewTours</strong> which will depend based on our requirement and how we want our routes to look like , those will be defined in files inside routes folder.</p><pre>module.exports = app;</pre><p>Lastly we are exporting our express object. Now let’s see server.js:</p><pre>const dotenv = require(&#39;dotenv&#39;);<br>const app = require(&#39;./app&#39;); <br>dotenv.config({ path: &#39;./config.env&#39; }); <br>const port = process.env.PORT || 3000;<br>app.listen(port, () =&gt; <br>{  console.log(`App running on port ${port}...`);});</pre><p>In <strong>server.js </strong>we will ask express to listen to port 3000 to startup in server, express is 100% NodeJs under the hud. So here we are importing dotenv. <strong>Dotenv</strong> is a zero-dependency module that loads environment variables from a .env file into <a href="https://nodejs.org/docs/latest/api/process.html#process_process_env">process.env</a>, to install it we have to run <strong>npm i dotenv</strong> in our integrated terminal ,then we are importing our express object from app.js .</p><pre>dotenv.config({ path: &#39;./config.env&#39; });</pre><p>Here we are asking dotenv to take the env variables from config.env.</p><pre>const port = process.env.PORT || 3000;</pre><p>We are defining the port in which we want to run our application, if we are not having PORT defined in config.env , we will define it as 3000.</p><pre>app.listen(port, () =&gt; <br>{  console.log(`App running on port ${port}...`);});</pre><p>Express is 100% NodeJs under hud, we are passing port and calling the callback function where we have added a console.log message just to tell our user that our application is running successfully. Let’s now see our <strong>config.env</strong> file:</p><pre>NODE_ENV=development</pre><pre>PORT=3000</pre><pre>USERNAME=Yudha</pre><pre>PASSWORD=123456</pre><p>In <strong>config.env </strong>we used to define all the variable which are constant throughout our application or frequently used constant , the main benefit of this is that we can update the values of those variables which are used in many places of our codebase just by changing it in this one file.</p><p>So before going to our other files let’s understand few concepts of express, api , restful api , middleware and request response cycle. So let’s begin ..</p><p>4. <strong>API and Restful API Design</strong></p><p>So what is Api ? Api stands for application programming interface , a piece of software that can be used by another piece of software, in order to allow application to talk to each other. It’s not necessary for Api to always be a webapi, but Api can be used with , <strong>Nodejs for http API( Node API)</strong>,<strong> Browser DOMJS Api</strong>, or with <strong>object-oriented programming </strong>when exporting method to the public .</p><p>There are some specific characteristics which makes an api ,a restful api those are:</p><p><strong>a. Separate Api into logical resource</strong> :</p><p>All data we are using should be divided into logical resource. Resource object is a representation of something , which has data associated to it , any information that can be named like user, tours etc.</p><p><strong>b. Expressing structured resource band URLs:</strong></p><p>We should define urls with proper structured resource format:</p><p><strong>https://www.tours.com/addNewTour</strong></p><p>https://www.tours.com-&gt;<strong>urls</strong></p><p>addNewTour-&gt;<strong>Endpoint</strong></p><p>c. <strong>using HTTPS methods(verbs):</strong></p><p>We have to perform <strong>C</strong>reate, <strong>R</strong>ead,<strong>U</strong>pdate,<strong>D</strong>elete methods .</p><p><strong>C</strong>reate -&gt; <strong>POST </strong>/tour</p><p><strong>R</strong>ead-&gt; <strong>GET</strong>/tours/7</p><p><strong>U</strong>pdate-&gt;[<strong>PUT</strong>-&gt;Client is suppose to put entire update object]</p><p>,[<strong>PATCH</strong>-&gt;Client send only the part of object that have been changed]</p><p><strong>D</strong>elete-&gt;<strong>DELETE</strong>/tour/7</p><p><strong>d. Send data as JSON:</strong></p><p>We have to send data in Json format :</p><p>If there is a data coming from api looks like this:</p><p>{</p><p>“id”:5,</p><p>“tourName”: “Manali”</p><p>“rating”: “4.5”</p><p>}</p><p>in express we will actually convert the data into a proper format of response like this:</p><p>{</p><p>“status”: “success”,</p><p>“data”:{</p><p>“id”:5,</p><p>“tourName”: “Manali”,</p><p>“rating”: “4.5”</p><p>}</p><p>}</p><p>This formatting is called enveloping the response from Api.</p><p><strong>e. Be stateless:</strong></p><p>All state should be on the client, this means that each request must contain all the information necessary to process a certain request, the server should not have to remember previous request. Let’s try to understand it with an example. Let say there is a api tour/next where we are performing GET method to get the next page, so to go to the next page index we have to have two variables currentpage:contains currentpage index and nextpage:contains nextpage index, so to handle such situation we have to add code something like this:</p><p>GET/ tour/next →<strong>WEB SERVER</strong></p><p>currentPage=5</p><p>nextPage=currentPage+1</p><p>send(nextPage)</p><p>In this case the state is actually on server</p><p>But in restful api the next page will come from the client so server do not have to remember previous request.</p><p>GET/tour/6 →<strong>WEB SERVER</strong></p><p>5. <strong>Middleware and the Request Response Cycle:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/820/1*DY54ObAx1cxCk2ZTPQ7IyQ.png" /><figcaption>Middleware Stack</figcaption></figure><p>The essence of express is <strong>Request Response Cycle</strong>, <strong>Express</strong> Application receives a request when someone hit the server , then a request and response object that means data is used and processed in order to generate and set back a meaningful response to the client . And to process the data we used something called <strong>Middleware</strong>, which can manipulate the request or response object, it’s called <strong>middleware</strong> because it’s a function which executes between the receiving the request and sending the response. Actually we can say that in express everything is a middleware. Order of middleware stack is actually executed in the order those are defined in the code.Each and every request, response coming from incoming request use to move and processed through each middleware. At the end of middleware we used to call next() function, this next() function actually calls the next middleware function that is defined in the chain of middleware.</p><p>6. <strong>Implementing Post,Patch,Get and Delete request in Api:</strong></p><p>So let see how to implement https methods , let’s see our<strong> TourRoutes.js</strong>:</p><pre>const express = require(&#39;express&#39;);</pre><pre>const tourController = require(&#39;./../controllers/tourController&#39;);</pre><pre>const router = express.Router();</pre><pre>router.param(&#39;id&#39;, tourController.checkID);</pre><pre>router</pre><pre>.route(&#39;/&#39;)</pre><pre>.get(tourController.getAllTours)</pre><pre>.post(tourController.checkBody, tourController.createTour);</pre><pre>router<br>.route(&#39;/:id&#39;)</pre><pre>.get(tourController.getTour)</pre><pre>.patch(tourController.updateTour)</pre><pre>.delete(tourController.deleteTour);</pre><pre>module.exports = router;</pre><p>In <strong>TourRoutes.js</strong>, we are first importing express, then we are importing tourController which contains all the logical function of implementing the http functional of tour routes. Then we are defining the routes , routing means basically to determine how an application respond to a certain client request.</p><pre>router</pre><pre>.route(&#39;/&#39;)</pre><pre>.get(tourController.getAllTours)</pre><pre>.post(tourController.checkBody, tourController.createTour);</pre><p>So we are actually using two routes ,first one is <strong>/api/v1/tours</strong> , you may remember this is the base route we have defined in app.js , so ‘<strong>/</strong>’ actually means the base route , so in this route we will be showing all the tours.The functionality of doing so is actually defined in tourController.js. To get all tours we have to implement get request on that api, so we are calling a callback function or middleware <strong>getAllTours</strong> which is defined in <strong>tourController.js</strong>. On the same route we will also implement post operation to add new tours, for that we are implementing a chain of middleware. Here the first middleware is <strong>checkbody</strong> which actually validating whether the user is entering valid entries and mandatory data to create a new tour and then <strong>createTour</strong> which is creating the new tour.</p><pre>router<br>.route(&#39;/:id&#39;)</pre><pre>.get(tourController.getTour)</pre><pre>.patch(tourController.updateTour)</pre><pre>.delete(tourController.deleteTour);</pre><p>Second is <strong>/api/v1/tours/:id</strong>, where we are performing three http operations, first one is get operation to get the details of specific tour which will be having the specific id , id will actually come from client side means if client hits /api/v1/tours/56 then it’s actually refers that user wants to operate http operation on the tour which is having the id 56.</p><pre>router.param(&#39;id&#39;, tourController.checkID);</pre><p>router.param is actually used to define how route will reacts when user hits some url which is having id in the end of the url, so when user hits such url, this <strong>checkID</strong> middleware function will first get triggered to check whether the user have entered valid id , or if there is any tours having the same id , if not it will throw error message . We have discussed previously that middleware functions used to get triggered in the order they are called , so once this id validation is done then the other http functions are called. So in <strong>/api/v1/tours/:id </strong>route<strong> </strong>we are performing three http operations, first one is <strong>get </strong>operation to get the tour details having specific id .The callback function or middleware <strong>getTour</strong> function will do that job, second is <strong>patch</strong> function to update tour details of the tour having the specific id , the <strong>updateTour</strong> function will handle the functionality , similarly third one is <strong>delete </strong>operation to delete tour having the specific id, to implement deletion of the tour we are calling <strong>deleteTour</strong> function. Lastly we are exporting the routes. Now let’s see tourController.js:</p><pre>const fs = require(&#39;fs&#39;);</pre><pre>const tours = JSON.parse(</pre><pre>fs.readFileSync(`${__dirname}/../dev-data/data/tours-simple.json`)</pre><pre>);</pre><pre>exports.checkID = (req, res, next, val) =&gt; {</pre><pre>// console.log(`Tour id is: ${val}`);</pre><pre>if (req.params.id * 1 &gt; tours.length) {</pre><pre>return res.status(404).json({</pre><pre>status: &#39;fail&#39;,</pre><pre>message: &#39;Invalid ID&#39;</pre><pre>});</pre><pre>}</pre><pre>next();</pre><pre>};</pre><pre>exports.checkBody = (req, res, next) =&gt; {</pre><pre>if (!req.body.name || !req.body.price) {</pre><pre>return res.status(400).json({</pre><pre>status: &#39;fail&#39;,</pre><pre>message: &#39;Missing name or price&#39;</pre><pre>});</pre><pre>}</pre><pre>next();</pre><pre>};</pre><pre>exports.getAllTours = (req, res) =&gt; {</pre><pre>// console.log(req.requestTime);</pre><pre>res.status(200).json({</pre><pre>status: &#39;success&#39;,</pre><pre>requestedAt: req.requestTime,</pre><pre>results: tours.length,</pre><pre>data: {</pre><pre>tours</pre><pre>}</pre><pre>});</pre><pre>};</pre><pre>exports.getTour = (req, res) =&gt; {</pre><pre>// console.log(req.params);</pre><pre>const id = req.params.id * 1;</pre><pre>const tour = tours.find(el =&gt; el.id === id);</pre><pre>res.status(200).json({</pre><pre>status: &#39;success&#39;,</pre><pre>data: {</pre><pre>tour</pre><pre>}</pre><pre>});</pre><pre>};</pre><pre>exports.createTour = (req, res) =&gt; {</pre><pre>// console.log(req.body);</pre><pre>const newId = tours[tours.length - 1].id + 1;</pre><pre>const newTour = Object.assign({ id: newId }, req.body);</pre><pre>tours.push(newTour);</pre><pre>fs.writeFile(</pre><pre>`${__dirname}/dev-data/data/tours-simple.json`,</pre><pre>JSON.stringify(tours),</pre><pre>err =&gt; {</pre><pre>res.status(201).json({</pre><pre>status: &#39;success&#39;,</pre><pre>data: {</pre><pre>tour: newTour</pre><pre>}</pre><pre>});</pre><pre>}</pre><pre>);</pre><pre>};</pre><pre>exports.updateTour = (req, res) =&gt; {</pre><pre>res.status(200).json({</pre><pre>status: &#39;success&#39;,</pre><pre>data: {</pre><pre>tour: &#39;&lt;Updated tour here...&gt;&#39;</pre><pre>}</pre><pre>});</pre><pre>};</pre><pre>exports.deleteTour = (req, res) =&gt; {</pre><pre>res.status(204).json({</pre><pre>status: &#39;success&#39;,</pre><pre>data: null</pre><pre>});</pre><pre>};</pre><p>In <strong>TourController.js </strong>we are defining all function which are associated with tour routes. So first we are importing fs package , this package is used to read or write data from a static file. To install this package we have to run <strong>npm i fs</strong> in our integrated terminal.</p><pre>const tours = JSON.parse(</pre><pre>fs.readFileSync(`${__dirname}/../dev-data/data/tours-simple.json`)</pre><pre>);</pre><p>We will actually read data from the static file named <strong>tours-simple.json</strong> which is inside <strong>dev-data</strong> folder. So we are reading data from <strong>tours-simple.json</strong> and storing it in variable called <strong>tours</strong> .</p><pre>exports.checkID = (req, res, next, val) =&gt; {</pre><pre>// console.log(`Tour id is: ${val}`);</pre><pre>if (req.params.id * 1 &gt; tours.length) {</pre><pre>return res.status(404).json({</pre><pre>status: &#39;fail&#39;,</pre><pre>message: &#39;Invalid ID&#39;</pre><pre>});</pre><pre>}</pre><pre>next();</pre><pre>};</pre><p>So the middleware usually used to have req, res , let’s take a get operation , if client requests for get operation on <strong>‘/’</strong> routes , the function to handle such request actually looks like this :</p><p><strong>app.get(‘/’,(req, res)=&gt;{</strong></p><p><strong>call back function we want to perform</strong></p><p><strong>}</strong></p><p><strong>req</strong> represents the request body which client is sending, <strong>res</strong> represent the response we will be sending back to client,</p><p>In <strong>checkID</strong> function, we are checking whether user is entering valid id before dealing with the routes having id at it’s end , we are checking whether request param id is larger than tours length, if it’s true it means user has entered invalid id, we will send response with status code 404 and return json response having params, status: ‘fail’ , message: ‘Invalid id’ , then we are calling <strong>next()</strong> function, <strong>next()</strong> function calls the next middleware function defined in the middleware stack if any.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9zm_HEIbiv56ouLK5fvgeg.png" /></figure><pre>exports.checkBody = (req, res, next) =&gt; {</pre><pre>if (!req.body.name || !req.body.price) {</pre><pre>return res.status(400).json({</pre><pre>status: &#39;fail&#39;,</pre><pre>message: &#39;Missing name or price&#39;</pre><pre>});</pre><pre>}</pre><pre>next();</pre><pre>};</pre><p>In <strong>checkBody</strong> function, we are actually checking whether the user is giving all the mandatory fields while creating a new tour. Name and price are the mandatory fields for creating new tours.So we are checking whether request body is having name and price fields, if those are not there we will return error message ‘Missing name or price’ with status code 400, then we are calling next() function which will call the next middleware function define in the middleware stack if any.</p><pre>exports.getAllTours = (req, res) =&gt; {</pre><pre>// console.log(req.requestTime);</pre><pre>res.status(200).json({</pre><pre>status: &#39;success&#39;,</pre><pre>requestedAt: req.requestTime,</pre><pre>results: tours.length,</pre><pre>data: {</pre><pre>tours</pre><pre>}</pre><pre>});</pre><pre>};</pre><p>In <strong>getAllTours</strong> function, we are getting all the tours present in our application, so we are setting response status as 200, and we are sending response json which is having params like status: ‘success’, <strong>requestAt</strong> will have time at which request was made, <strong>results</strong> will have the number of tours present in our application, and lastly in data we are passing our <strong>tours</strong> variable which we defined above.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nkqyxfw7Z91WiM1x4WgXWw.png" /><figcaption>GET OPERATION IN POSTMAN</figcaption></figure><pre>exports.getTour = (req, res) =&gt; {</pre><pre>// console.log(req.params);</pre><pre>const id = req.params.id * 1;</pre><pre>const tour = tours.find(el =&gt; el.id === id);</pre><pre>res.status(200).json({</pre><pre>status: &#39;success&#39;,</pre><pre>data: {</pre><pre>tour</pre><pre>}</pre><pre>});</pre><pre>};</pre><p>In <strong>getTour</strong> function, we are getting the tour having the id we are specifying in the url(/service/ex: /api/v1/tours/2) where id is 2.So in this function we are using find function and checking if there is any tour which is having id equal to param id.If there is a match we are storing that in our <strong>tour</strong> variable. then we are sending our res status code 200 and sending response data having status= ‘success’ and data having our <strong>tour</strong> object.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6eonWRcNOuWuYHT8upGR2A.png" /><figcaption>GET OPERATION ON POSTMAN</figcaption></figure><pre>exports.createTour = (req, res) =&gt; {</pre><pre>// console.log(req.body);</pre><pre>const newId = tours[tours.length - 1].id + 1;</pre><pre>const newTour = Object.assign({ id: newId }, req.body);</pre><pre>tours.push(newTour);</pre><pre>fs.writeFile(</pre><pre>`${__dirname}/dev-data/data/tours-simple.json`,</pre><pre>JSON.stringify(tours),</pre><pre>err =&gt; {</pre><pre>res.status(201).json({</pre><pre>status: &#39;success&#39;,</pre><pre>data: {</pre><pre>tour: newTour</pre><pre>}</pre><pre>});</pre><pre>}</pre><pre>);</pre><pre>};</pre><p>In <strong>createTour</strong> function, we are creating new tour by taking data from req body. So we are creating <strong>newId</strong> by adding last tour id with one , then we are creating our <strong>newTour</strong> , so we are creating an object with id as <strong>newId</strong> and other <strong>req.data</strong>, then we are pushing our newTour into our <strong>tours</strong> variable, then we are replacing data of our tours-simple.json with our latest tours value. Finally we are sending res status code 201 and sending response data having status= ‘success’ and data having our <strong>newTour</strong> object.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-N1UopMl9lCNKoInXgcEiQ.png" /><figcaption>POST OPERATION IN POSTMAN</figcaption></figure><pre>exports.updateTour = (req, res) =&gt; {</pre><pre>res.status(200).json({</pre><pre>status: &#39;success&#39;,</pre><pre>data: {</pre><pre>tour: &#39;&lt;Updated tour here...&gt;&#39;</pre><pre>}</pre><pre>});</pre><pre>};</pre><p>In <strong>updateTour</strong> function, we are updating the existing tour having the id similar to <strong>req.param.id</strong>, and passing response status 200.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uveG9JwRDUeqMpPhXkELjQ.png" /><figcaption>PATCH OPERATION IN POSTMAN</figcaption></figure><pre>exports.deleteTour = (req, res) =&gt; {</pre><pre>res.status(204).json({</pre><pre>status: &#39;success&#39;,</pre><pre>data: null</pre><pre>});</pre><pre>};</pre><p>In <strong>deleteTour</strong> function, we are deleting the tour having the id similar to req.param.id, and passing response status 200.</p><p><strong>7. Conclusion:</strong></p><p>So in this article we discuss how to create restful api and perform CRUD operation using express and postman. We will be continuing our discussion in next article , in next article we will be discussing how to setup , integrate <strong>MongoDb</strong> and how to define schema in <strong>MongoDb</strong> using <strong>Mongoose</strong>.I am attaching the GitHub code link as a reference of this article:</p><p><a href="https://github.com/Yudhajitadhikary/NodeJs_Api_Creation_Blog">GitHub - Yudhajitadhikary/NodeJs_Api_Creation_Blog: It&#39;s a reference demo of how to create Api using NodeJS and Postman</a></p><p><strong>HAPPY CODING !!</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5f200b3b85b6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How Node Js and Web works together..]]></title>
            <link>https://yudhajitadhikary.medium.com/how-node-js-and-web-works-together-d107331fe0c8?source=rss-f54a1f93756b------2</link>
            <guid isPermaLink="false">https://medium.com/p/d107331fe0c8</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[expressjs]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[nodejs]]></category>
            <dc:creator><![CDATA[Yudhajit Adhikary]]></dc:creator>
            <pubDate>Sun, 17 Jan 2021 13:54:42 GMT</pubDate>
            <atom:updated>2021-01-17T14:13:08.100Z</atom:updated>
            <content:encoded><![CDATA[<h3>Basic Architecture of NodeJS and Web Creation..</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*lvRrB0IeZCMfR7La" /><figcaption>Photo by <a href="https://unsplash.com/@pankajpatel?utm_source=medium&amp;utm_medium=referral">Pankaj Patel</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>In this article we will go through the basic concept and architecture of NodeJS. We will go through how web works, and how NodeJS executes the code under the hood. So we will segregate our discussion into several segment.</p><ol><li><strong>What is Node Js ?</strong></li><li><strong>How to Web works ?</strong></li><li><strong>Architecture behind NodeJS ?</strong></li></ol><p><strong>1. What is Node Js ?</strong></p><p>Node Js is a JavaScript runtime built on Google open source V8 js engine. Node Js is just a JavaScript outside of the browser. JavaScript is run in V8 engine provided by Google.</p><p><strong>What is the perfect condition for using Node Js as a web server ?</strong></p><p>We can use JavaScript on the server side of web development , in order to build fast , highly scalable network applications (Backend)</p><p><strong>Why and when to use NodeJS ?</strong></p><blockquote><strong>Node Js Pros:</strong></blockquote><ol><li>For single threaded based on event driven , non blocking I/O model.</li><li>Perfect for building fast and scalable data- intensive apps.</li></ol><blockquote><strong>Use Node Js:</strong></blockquote><ol><li>API with databases behind it.</li><li>Data streaming real time chat application.</li><li>Server side web application.</li></ol><blockquote><strong>Don’t use NodeJS :</strong></blockquote><p>Application with heavy server side processing (CPU-intensive).</p><blockquote><strong>Features of NodeJS:</strong></blockquote><p>Companies like Netflix, Uber, PayPal, eBay have started using NodeJS in production.</p><p>Since NodeJS is having JS across the entire stack it makes faster and more efficient development.</p><p><strong>NPM</strong>:- Node package Manager is a huge library of open source packages available for everyone for free.</p><p>NodeJS is having very active developer community.</p><p>So to proceed with our discussion , we should know what are different approach by which NodeJS works:</p><blockquote><strong>Synchronous Approach:</strong></blockquote><p><strong>const fs=require (‘fs’)</strong></p><p><strong>const input =fs.readFileSync(‘input.txt’, ‘utf-8’);</strong></p><p><strong>console.log(input)</strong></p><blockquote><strong>Asynchronous Approach:</strong></blockquote><p><strong>const fs=require(‘fs’)</strong></p><p><strong>fs.requireFile(‘input.txt’ ‘utf-8’ ,(err, data)=&gt;{</strong></p><p><strong>console.log(data)</strong></p><p><strong>});</strong></p><p><strong>console.log(‘Reading file’);</strong></p><p>So these are two approach we can apply NodeJS. So NodeJS Process is the place where our application runs. If one user got access to the single thread in synchronous way others have to wait for it to get complete. This scenario is called callback Hell which is a disadvantage of synchronous approach. But in asynchronous approach , the more time consuming tasks should be executed in background, so that other processes need not to wait for that process to get complete.</p><p><strong>2. How the Web works ?</strong></p><p>So what happens when we access a webpage.</p><p><strong>DNS &lt;=&gt;DNS Lookup&lt;=&gt;Client (browser)&lt;=&gt;TCP/IP Socket&lt;=&gt;Server</strong></p><p><a href="https://www.google.com/maps">https://www.google.com/maps</a></p><p>Now we let analysis Google map url as example. Here ‘<strong>https</strong>’ is the protocol, ‘<a href="http://www.google.com/"><strong>www.google.com</strong></a>’ is the domain name and ‘<strong>maps</strong>’ is the resource.</p><p>We need to have something to convert domain name to real name of the server. <strong>DNS</strong> (Domain Name Server), is special server which are basically like a phone book of the internet. Browser makes request to DNS , this DNS then simply match the web address that we type into the browser to the server with real ip address .This happens with ISP( Internet Server Provider) .Domain is not the real address , DNS will convert it to the real ip address which your browser can then call after it been send back to our browser.</p><p><a href="http://216.58.21.206:443/"><strong>https://216.58.211.206:443</strong></a></p><p>‘http’ is the protocol, 216.58.211.206 is the IP address, 443 is the port number , by default 443 is the port number for https and 80 is for http.</p><p>Once we have the real web address , a TCP/IP socket connection gets established between client and server, this connection is typically kept alive for entire time for transferring all the files on website.</p><blockquote><strong>What are TCP/IP ?</strong></blockquote><p>TCP is the transmission controlling protocol, and IP is the internet protocol, and together they are connection protocol that define exactly how data travel across the web. They are basically the internet fundamental control system, they are the one who set the rules about how data moves.</p><p><strong>Client==&gt; Http Request==&gt;Server</strong></p><p>Communication protocol is simply a system of rules of two or more parties to communicate. In case of http it’s just a protocol that allow client and web server to communicate by sending request and response message from client to server back.</p><blockquote><strong>Request message looks like this:</strong></blockquote><p>Start Line (Http method+request target+HTTP version)→ <strong>GET/maps/HTTP/1.1</strong></p><p><strong>Host:www.google.com</strong></p><p><strong>User-Agent: Mozilla/5.0</strong></p><p><strong>Accept-Language: en-us</strong></p><p><strong>&lt;Body&gt; → Request Body</strong></p><p><strong>GET</strong> is used to get data, <strong>POST</strong> is used send data, <strong>PUT</strong> and <strong>PATCH </strong>is used to basically modify data.</p><blockquote>then <strong>Http response header looks like this:</strong></blockquote><p>Start Line (HTTP version+ Status code+ Status message)→<strong>HTTP/1.1 200 OK</strong></p><p><strong>Date: Fri, 18 Jan 2021</strong></p><p><strong>Content-Type: Text/html</strong></p><p><strong>Transfer-Encoding: checked</strong></p><p><strong>&lt;Body&gt; →</strong></p><p><strong>Response Body</strong></p><p>Then index.html is the first to be loaded , then it scan for assets like JS, CSS and images. Then the process is repeated for each file. TCP actually breakup the response into thousand of small chunks, before they are set. Once they get their destination it will reassemble those into the original required response, which will be automatically seen in the browser. IP is used to send routes for all of the packets to the internet which are nothing but the ip address of each packets.</p><blockquote><strong>Frontend VS Backend Web Development</strong></blockquote><p>Server: A base server is real component that is connected to internet, which stores full HTML, CS, JS and runs http server, which is capable of performing request and response.</p><blockquote><strong>Static VS Dynamic VS Api:</strong></blockquote><p>Static application will be having html , css and JavaScript files in the web server. There will be no backend code for static websites.</p><p><strong>Html, Css , JavaScript →browser →Ui</strong></p><p>Dynamic application is actually server side rendering.</p><p><strong>Database →get data →build Web using Template →Html, Css, JavaScript →browser →Ui</strong></p><p><strong>Web Application =Dynamic website + Functionality.</strong></p><p><strong>API →Database →Get Data →JSON →Browser →Build Website using Template →Ui</strong></p><p><strong>3.</strong> <strong>Architecture behind NodeJS ?</strong></p><p><strong>|V8 JS →Machine Engine| →|Libuv →free source library with strong focus JS and synchronous output + C++ + event loop |</strong></p><p>V8 is the machine engine for NodeJS, and it uses library called Libuv which free source library with strong focus on JS , NodeJs is the combination of JavaScript and C++. It having a feature called event loop which manages the threads and event execution.</p><p>Using node on a computer means there will be a NodeJS process(instance of a program in execution on a computer).</p><blockquote><strong>Single Thread(Sequence of instruction)</strong></blockquote><p>If you run node application , we will run on a single thread.</p><p><strong>Initialize program →execute ‘top-level’ code →require modules →register event callbacks →start event loop</strong></p><p>So when event are hard they could not be done in start event , those are handled by thread pool.</p><blockquote><strong>Thread Pool:</strong></blockquote><p>Thread pool can have additional 4 or more Thread or tasks running parallelly , It also takes offload works from the event loop, it is also capable to handle heavy tasks such as File System APIS, Cryptography, Compression and DNS Lookups.</p><blockquote><strong>Event Loops:</strong></blockquote><p>All the application code that is inside callback functions (non top / top level code) are handled by event loop . NodeJS is build around callback function.</p><blockquote><strong>Event Driven Architecture:</strong></blockquote><p><strong>Event Loop →start →Expired Timer Callback →I/O polly and callback →[Next Tick() Queue] →set Immediately callback →[Other Microtasks Queue] →close callbacks →Any pending timer or I/O tasks ? →(Yes) →Back to Expired Timer Callbacks/ else it will Exit.</strong></p><p>So first event are emitted, event loops picks them up and callbacks are called. Event loop does the orchestration , it receives events, calls there callback functions , and offers more expensive tasks to the Thread pull. Event loops make asynchronous possible in NodeJS. So It don’t block the tasks, don’t use synchronous version of function in fs.crypto and zlib modules in our callback function, don’t perform complex calculation, becomes careful with the JSON in large objects, don’t use too complex regular expressions. The event loop actually works for all these stuff to happen .The poll phase is the phase where I/O callbacks are handled, So when the queue of callbacks is empty, we have no I/O callbacks. Event loop will wait in this phase until there is an expired timer, But if we scheduled a callback using setImmediate, then that callback will actually be executed right away after the polling phase and even before expired timer. If there is one such tasks , in that case the timer expires right away after zero second, for that the event loop actually waits , so it pauses the polling phase, so that setImmediate callback is actually executed first. Next Ticks was a task of microtasks, and a queue that gets executed after each phase, not just after one entire tick .So to summarize ,setImmediate actually executes once per tick, while next Ticks gets executed immediately.</p><p>So in node, there are certain object called event emitters that emit events as soon as something important happens in the application. This events can then be picked up by event listener that we developers set up, which will fire off callback first that are attached to each listener.</p><p><strong>Event Emitter →emits event →Event listener →calls →Attached callback function</strong></p><p><strong>NEW REQUEST ON SERVER</strong></p><p><strong>127.0.0.1:8000 → Listener:</strong></p><p><strong>const server=http.createServer()</strong></p><p><strong>server.on(‘request’,(req,res)=&gt;{</strong></p><p><strong>console.log(‘Request received’);</strong></p><p><strong>res.end(‘Request received’);</strong></p><p><strong>})</strong></p><p>So here we are creating a listener .When a new request is made, the server acts as an emitter, and will automatically emit an event called ‘request’, each time that request hits the server. Then since we already have a listener setup for the exact event, the callback function that we attach to the listener will be called, it will simple send the same data back to the client, Now it works this way because behind the scene the server is actually an instance of the NodeJS, event Emitter class. So it inherits all the event listening logic from that Event Emitter class. [Event emitter logic is called observer Pattern in JS].So the idea is that we set there a observer, in our case the event listener will act as observer which keeps waiting ,keeps observing the subject that will eventually emit the event that the listener is waiting for. And the opposite of the pattern is simply function calling other function, so observer pattern is an actual design to react rather than call, there is a huge benefit of using this architecture, it is fast , everything is more de-coupled. We don’t have function from the file system module so we call functions from HTTP module, these modules are nicely de-coupled and self contained. This architecture make it way more straight forward to react multiple time to the same event.</p><blockquote><strong>Streaming:</strong></blockquote><p>Streaming is used to process(Read and write) data piece by piece (chunks) without completing the whole read and write operation, and therefore without keeping all data in memory. It is perfect for handling large volume of data like videos and is more efficient in data processing in terms of memory (no need to keep all data in memory one time. We don’t have to access all the data which are available).</p><p>In Node there are 4 fundamental type of stream:</p><p><strong>Readable Streams</strong>: Streams from which user can read container data , <strong>example:</strong> http request file read stream, stream are instance of the event emitter.</p><p><strong>Writable Streams:</strong> Stream from which user can write data, <strong>example: </strong>http response for file write stream.</p><p><strong>Duplex Streams:</strong> Stream that are both readable and writeable, <strong>example:</strong> net web socket.</p><p><strong>Transform Streams:</strong> Duplex stream that transform data as it is written or read, <strong>example: </strong>Zlib Grip creation.</p><blockquote><strong>Requiring Modules:</strong></blockquote><p>Each JS file is treated as a separate module. Node JS uses the common JS module system. There have been attempts to bring ES modules to node JS(.MJS)</p><p><strong>require (‘test-module’) →resolving &amp; Loading[require to receive the module name as input start with core module if it begins with ./axios to load developer modules, it means is no file found try to find folder with index.js in it. Else go to node-modules /axios and try to find the module there.] →wrapping →execution →returning exports →caching</strong></p><blockquote><strong>Wrapping:</strong></blockquote><p><strong>function(exports,require,module,_filename,_dirname){</strong></p><p><strong>//module code lives here</strong></p><p><strong>}</strong></p><p>node doesn’t actually execute the code that we write into a file but instead the wrapper that will contain our code in it’s body will execute the code.</p><p><strong>require</strong> →function to require module.</p><p><strong>module </strong>→reference to the current module.</p><p><strong>exports </strong>→reference to module exports, used to export object from a module.</p><p><strong>_filename </strong>→absolute path of the current modules file.</p><p><strong>_dirname </strong>→directory name of the current module.</p><blockquote><strong>Returning exports:</strong></blockquote><p>Require function returns exports of the required module. Module exports is the returned object, we can use module.export to export one single variable, for example one constant or one function, We can also use exports to export multiple variables as well.</p><p>So this is the big picture of how actually NodeJS works under the hood and how a website gets created. We have covered mainly the theoretical side of the NodeJs. We have not done anything practically for now. This is the basic architecture of NodeJs which we should know before we start implementing NodeJS in our application.</p><p><strong>HAPPY CODING :)</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d107331fe0c8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Creating Application using MongoDB Realm (Stitch)(Part-2)]]></title>
            <link>https://yudhajitadhikary.medium.com/creating-application-using-mongodb-realm-stitch-part-2-52d1b2ec6ba2?source=rss-f54a1f93756b------2</link>
            <guid isPermaLink="false">https://medium.com/p/52d1b2ec6ba2</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[realm]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[mongodb]]></category>
            <dc:creator><![CDATA[Yudhajit Adhikary]]></dc:creator>
            <pubDate>Mon, 11 Jan 2021 11:30:17 GMT</pubDate>
            <atom:updated>2021-01-11T11:30:17.770Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*QJWremrYuEiPouAG" /><figcaption>Photo by <a href="https://unsplash.com/@syinq?utm_source=medium&amp;utm_medium=referral">Susan Yin</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Hi Guys !, this article is the continuity of my previous article.</p><p><a href="https://yudhajitadhikary.medium.com/building-application-with-mongodb-and-stitch-realm-part-1-7712a1f9f42">Building Application with MongoDB and Stitch Realm( Part-1)…</a></p><p>In part-1 we have discussed about the basic concept of mongoDB , we have developed our Product Store Application using MongoDB and React . Actually in part-1 we have build the application with the basic approach of MongoDB, creating backend using MongoDB, defining api and all , then creating frontend using React , and finally connecting the frontend and backend. If you have not checked my first blog please check that one first then you will understand the basic concept and what’s the difference between the two approach, the one we have applied in part 1 and the one we will be applying in part 2.So In part 2 we will be using Stitch a server less Query Api for building the same application we have developed in part 1 So that we can relate the difference between the approach clearly.</p><p><strong>What is Stitch ?</strong></p><p>Stitch is a server less platform for building application , it’s a collection of service offered by MongoDB Company, that we can use for building web application. So that a developer or we can focus on user interface and our code logic.</p><p>Stitch gives us access to MongoDB Atlas database access will be then available inside our client side application. It does explore our database credentials, it’s like our user can login or signup through stitch server . A user will use their own credentials to get access to the database, or we can lockdown what a single user can do. User are allowed to insert documents to their collection. We will authorize rights to our user, because they will not be having full access to the DB with mongoDB credentials which are not explored through Stitch. Stitch also react to events, if something gets inserted into a database, or something gets updated, we can run some code that gets triggered.</p><p>So How stitch actually works, stitch execute code or functionality in the cloud using stitch function and stitch services, which makes stitch server less. database is stitch query anywhere mongoDB mobile, stitch also reacts to events using stitch triggers.</p><p>So we will first see the previous architecture of mongoDB we had used in part 1.</p><p><strong>Client (App) → (Node Api) → [MongoDB/Atlas]</strong></p><p>Client App is our application, Node Js acts as the server between our client app and mongoDB database. For stitch that Node Api will get replaced by Stitch Server.</p><p><strong>Client (App) → (Stitch Server) → [MongoDB/Atlas]</strong></p><p>So enough theory , Now let’s start coding.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e4f6845234119c46d32e1c6229be1065/href">https://medium.com/media/e4f6845234119c46d32e1c6229be1065/href</a></iframe><p>So App.js is the root component or the parent component of all other component for our application. Now , if you have gone through part-1 you will notice that we are not performing any api fetch or anything using axios. So we are using ‘mongodb-stitch-browser-sdk’ for including stitch server in our application, to install it we have to run : <strong>npm i mongodb-stitch-browser-sdk </strong>in our vscode terminal. We are importing Stitch, UserPasswordAuthProviderClient and UserPasswordCredential from mongodb-stitch-browser-sdk. These are client for interacting with username/password authentication provider in Stitch. So our App.js is having three parameter in state, isAuth to check whether the user is authenticated or not, authMode to determine whether user is logging in or signing up into our application and error to show error message. Now inside constructor we are configuring our client we are first initializing our default client id using Stitch.initializeDefaultAppClient. So from where we are getting this id ‘myshop-nareq’. To get the id we first have to add our project to MongoDB Realm. We have to first login to our MongoDB profile, there at the top we will be seeing Realm option. Click on that , then click on Create a New App button at top right . We will be seeing a form asking for Application name and Link for our Data Source. We can get a specific name, and add the cluster which we had created earlier for our application. Then we will click on Create button. Then a new app will be created in the MongoDB Realm , there on the top left we will see there will be App id , we will copy that id and will use that into our Stitch.initializeDefaultAppClient() function. We are calling callFunction , this callFunction() takes two parameters first one is function which will be defined into stitch function, and two parameter is the parameter we want to pass to that stitch function. To define the function we have to go to that realm dashboard, on the left side navigation tab there will be a function tab , click on that , then click on create a new function. On Function Editor tab , we will define our function.</p><p><strong>exports = function(arg){<br>console.log(‘Greet!’,arg)<br> return {arg: arg};<br>};</strong></p><p>We are just logging in console a message ‘Greet!’ .If we go to the logs tab in realm dashboard we will see that Greet! message whenever a user logs in. arg parameter gets the value which we pass on the client. callFunction() as second argument. logoutHandler() function is used to handle logging out from our application , there we are setting the isAuth state to false, we will be using those functions in other component or pages of our application. authHandler function is used to handle login. if user does not enter any details we will return our function. Else if the user have entered the details , we are creating user password authentication provider client using auth.getProviderClient() function. There we are passing UserPasswordAuthProviderClient.factory as parameter , UserPasswordAuthProviderClient is client for interacting with username/password authentication provider in Stitch. Now we are checking the authMode state , if it’s login we are creating the login credentials using the input fields data and calling UserPasswordCredential () function with the input field values. Then we are sending a request to make the user logged into our application using that credentials. Else if the user is signing up we are registering our user with the email id and password user has entered. So we are setting our request according to authMode state value, so our request will be a asynchronous function so if we are getting response that means user is authenticated ,we are setting the isAuth to true, But if there is any error we are setting isAuth to false. authModeChangedHandler() function is used to toggle the value of authMode between login and signup. errorHandler() function is used to set error message for our application. Now we will see the actual Dom structure of our application. Inside render we are first defining the routes of our application. We used to define all the routes and redirects (if any) inside Switch tag. So inside Switch tag we are first defining the redirects for base route ‘/’ user will be redirected to ‘/products’ routes, from ‘/auth’ and ‘signup’ also the user will be redirected to our products page. For path ‘/product/:mode’, mode value will be ‘add’ ,means for adding new products we will be using this route. So we are rendering our EditProductPage page and sending the response data and errorHandler function as props of the page. Similarly when the path is ‘/product/:id/:mode’ mode value will be ‘edit’ and id will be the object Id of the document (product) which we want to edit. Here also we are rendering EditProductPage page with the response data and errorHandler function as props of it. For route ‘products/:id’ id will be the object id of the particular product whose details will be shown into our product page, So there we are rendering our product page ProductPage with the response data and errorHandler function as props of it. ‘/products’ will be rendering our products page ( ProductPage ).But if our user is not authenticated means the isAuth state value is false, we will be defining a different route. We will redirecting our user from ‘/’ , ‘/product’ , ‘/products’ to ‘/auth’, we want our user to first login then continue with other pages. For the route ‘/confirm-account’ we are rendering our confirm account page. For the route ‘/auth’ we are rendering the our AuthPage , there we are passing our mode state , authHandler and authModeChangedHandler as props. Now we are finally rendering our Modal component which will appear whenever there is some error , there we are passing a custom title and errorHandler function as props and a paragraph as the child of it. Backdrop is used to make the background of our application blackish as the Modal opens. We have added our Header component , where we are passing isAuth state and logoutHandler function as props. And finally we are adding the routes variable which we have defined above. Now we create the rules means what our user can do in our application. To do that we have to go to the rules tab , then we have to click on Add Collection button, then we will be redirected to page where we will select the database and collection name for which we want to set the rules. For permission template we will keep it No template for now. This will create the rules of our application for the read/ write permission in product collection. Then we can see there will a tabular representation of rules which got applied to the product collection, we can check or uncheck the options of read and write to set rules for product collection. We can also specify the read write rules for specific field in product collection by clicking on Add Field button. Now we will specify how the user authentication or login will happen for our application. For that we have to go to Authentication tab , there we will select the authentication type we want, we will select Email/Password by clicking on edit button . Provider Enabled will be ON, we can also send a confirmation mail to that email id, for that select User Confirmation Method to Send a confirmation email. There should be one Email confirmation Url, which should point to a page that contains the email confirmation script. Realm will automatically append the user token and tokenId to that Url in the email. So we are passing account confirmation page url <a href="http://localhost:3000/confirm-account">http://localhost:3000/confirm-account</a> , so realm will automatically append the token and token Id to that url and user will automatically get redirected to our homepage. Now let’s see the pages of our application. We will start with Auth.js.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ebeb72877cb6cd2e44606f8299a5924e/href">https://medium.com/media/ebeb72877cb6cd2e44606f8299a5924e/href</a></iframe><p>In Auth.js we are defining our authentication page. So state will be having two parameters email and password. inputChangeHandler is the function which is used to set our state values according to the values we will be entering in our input fields. Now we are checking value of mode for setting value of our modeButtonText and submitButtonText variable accordingly. This page will be having a button for login or signup, onClick of this we are calling onAuthModeChange function from props. Now inside the form we are having input fields for email and password. onChange of each input fields we are calling inputChangeHandler function with the input field name and event object. We are also having the button for submitting the form. onSubmit of the form we are calling onAuth function from props, with the object having input field values of email and password as the parameter . Now we will be looking into the confirmAccount page.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d7323099a2063ff525bf443b64d5a7cc/href">https://medium.com/media/d7323099a2063ff525bf443b64d5a7cc/href</a></iframe><p>So confirm Account page will actually perform the confirmation of the email id. When user submits the email id and password for signup . A confirmation mail will be send to that email id. That mail will be having a url <a href="http://localhost:3000/confirm-account">http://localhost:3000/confirm-account</a>/:token/:tokenid, token and tokenId while be provided by realm, when user clicks on that link , user gets redirected to the homepage, which indicates the email confirmation is successful. So this functionality happens in this confirmAccount.js. In confirmAccount.js componentDidMount() we are storing the url of the page in a constant called queryUrl , then we are storing the params of the url in queryParams. then we are fetching the token and tokenId from the params, and storing those in token and tokenId constant respectively. Now are creating authentication client by using auth, getProviderClient function and named it emailPassClient. Our user email id is confirmed by passing the token and tokenId to emailPassClient.confirmUser function. If there is no error means user email confirmation is successful we are redirecting our user to our homepage ‘ / ’ . So in confirmation page we want to show our user the Loading message when the confirmation is running until the user gets redirected to the homepage of our application, for that we are just rendering main tag with the message Confirming Account….. ,Now we will be see our Products.js .</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d62fad5e63708ef034da26a9430edf2c/href">https://medium.com/media/d62fad5e63708ef034da26a9430edf2c/href</a></iframe><p>In Products.js we are defining our Products page. There are two parameter in our states , isLoading and products. when the page renders in componentDidMount() we are calling fetchData() function. fetchData() function actually fetches the data from our database, so in fetchData () we are first defining our service client called mongodb. Now we are accessing products collection in shop database , then we are fetching the data in array format, when we got the response we are setting our isLoading state to false and passing the response to our isLoading state. If there is any error we are setting isLoading state to false and calling the OnError function from props with the error message. We also have another function productDeleteHandler() to handle the delete functionality of our products. In productDeleteHandler( ) function we are creating service client for our database called mongodb. Then we are accessing products collection in shop database and deleting product having id same as productId. Once deletion is done we are calling fetchData() function. Now we are defining the content, initially we are defining the content as Loading products.. .When isLoading is false and products are available, we are setting content as Products component which is having products state and productDeleteHandler() function as props. If isLoading is false and there is no products we are setting content as paragraph having text ‘Found no products, Try again later’. Finally we are rendering the content inside main tag. Now let’s see the Product.js.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f5c3d70ef31e25dbd34f205229ad7d04/href">https://medium.com/media/f5c3d70ef31e25dbd34f205229ad7d04/href</a></iframe><p>In Product.js we are designing our product details page. We have two parameter in states isLoading and product. So when the page loads in componentDidMount() we are fetching the details of the particular product . We are creating service client for our database called mongodb. Then we are accessing products collection in shop database and fetching product having id same as id coming from params of the page url. Once we get the data of that particular product we are converting product id and price into string, then we are setting our isLoading state to false and passing the response data to our product state. If there is any error we will be setting isLoading state to false, and will be calling onError() function with error message. We are rendering content variable , so initially our page will show ‘Is loading…’. If isLoading is false , and product details is fetched , we are setting content to main tag having product name, price, product image and description. If isLoading is false and there is no product details , we will show paragraph having text ‘Found no product. Try again later’. Now we will be seeing the Edit Product page.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/40ff1eb60a6f5f649d4919ebeddddfb8/href">https://medium.com/media/40ff1eb60a6f5f649d4919ebeddddfb8/href</a></iframe><p>In EditProduct.js , we are creating add product and edit product page of our application. We are importing our Input and Button component. So our ProductEditPage is having 5 parameters in state , isLoading , title, price, imageUrl and description. When our page renders , in componentDidMount we will be checking whether the user is adding new product or editing existing product for that we are checking this.props.match.params.mode if it is equal to ‘edit’, We are creating service client for our database called mongodb. Then we are accessing products collection in shop database and fetching product having id same as id coming from params of the page url. Once we get all the details of our product we are setting our isLoading state to false, title to product name, price to product price , imageUrl to product.image and description to product description. If this.props.match.params.mode is not equal to ‘edit’ we will just set our isLoading to false. editProductHandler() function is used to edit or add products in our application. We will be first do error checking if the user have not entered any thing and clicks on the submit button we will just simply return the function we will not perform anything. If user enters all the details and submit the form we will first set the isLoading state to true, we will create an object productData with all the input fields values. Then we will be creating our request based on the value of mode present in our url (this.props.match.params.mode). If mode is equal to ‘edit’ we are calling updateOne function on products collection , updateOne have two arguments first argument is the condition for determining in which product the update should happen and second parameter is having the updated product data . But if it is not then it means the user is actually adding new products for that we are creating our service client and inserting the productData or newly added product details in our products collection. Once we get the response we will set isLoading state to false, and redirecting our page to products page. If there is any error , we are setting isLoading states to false and calling our onError() function with error message. inputChangeHandler() function is used to set our state value with the input field value. So inside render we will setting our content, So our content will be a form having input fields for product title, price, image, description. For each fields we are passing the config object, label, elType, and on onChange() function we are calling inputChangeHandler function with event object and label of each input field. Then we are having button to submit the edit /add product form , on submission of the form we are calling editProductHandler() function. If this.state.isLoading is true we will set content to paragraph having text ‘Is loading…’.And finally render our content inside main tag. So our application is up now let’s have a look.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fcodesandbox.io%2Fembed%2Fnervous-gauss-lqxtn&amp;display_name=CodeSandbox&amp;url=https%3A%2F%2Fcodesandbox.io%2Fs%2Fnervous-gauss-lqxtn&amp;image=https%3A%2F%2Fcodesandbox.io%2Fapi%2Fv1%2Fsandboxes%2Flqxtn%2Fscreenshot.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=codesandbox" width="1000" height="500" frameborder="0" scrolling="no"><a href="https://medium.com/media/12d56a60a26e4dd486796efa50c40db0/href">https://medium.com/media/12d56a60a26e4dd486796efa50c40db0/href</a></iframe><p>So we can see how easily we can create our application using MongoDB Stitch, We don’t have to config any backend or Api , Stitch takes care of it. This is just a basic implementation we can utilize many cool features which are provided by Stitch in our application. The main advantage of Stitch is that developer do not have to worry for the backend creation or connection , this will give them more time to think about user interface and coding logics. I am attaching my github repo and documentation of MongoDB as reference of this article.</p><p><strong>Code :</strong></p><p><a href="https://github.com/Yudhajitadhikary/MongoDB-with-Stitch">Yudhajitadhikary/MongoDB-with-Stitch</a></p><p><strong>Documentation:</strong></p><p><a href="https://docs.mongodb.com/">Welcome to the MongoDB Documentation</a></p><p><strong>HAPPY CODING….:)</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=52d1b2ec6ba2" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building Application with MongoDB and Stitch Realm( Part-1)…]]></title>
            <link>https://yudhajitadhikary.medium.com/building-application-with-mongodb-and-stitch-realm-part-1-7712a1f9f42?source=rss-f54a1f93756b------2</link>
            <guid isPermaLink="false">https://medium.com/p/7712a1f9f42</guid>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[realm]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[mongodb]]></category>
            <dc:creator><![CDATA[Yudhajit Adhikary]]></dc:creator>
            <pubDate>Thu, 31 Dec 2020 09:26:04 GMT</pubDate>
            <atom:updated>2020-12-31T09:26:04.465Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*jwvX3E1dA7Z6mm2L" /><figcaption>Photo by <a href="https://unsplash.com/@markusspiske?utm_source=medium&amp;utm_medium=referral">Markus Spiske</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Hi Guys ! in this article we will be creating a Product Store Application ,using MongoDB and React. On the second part we will be building the same application using Stitch(Realm) , a server less platform for building application.</p><p>So what is MongoDB , MongoDB is database, word MongoDB comes from the word Humongous , which means huge. So MongoDB will be having collections(table for schema full)and each collections are having document(data for schema full).So in MongoDB, data are stored in binary form of json format called BSON. It’s is very flexible since it is schema less we can store any type of data in collection. MongoDB is managed by a very strong community called MongoDB/Atlas (Cloud) which is self managed enterprise. It’s also having cloud management and ops management. It having mongoDB compass portal for data visualization, BI connector , MongoDB Charts used for data science and Stitch for server less backend solution, which is having features like server less query API, databases triggers and real time sync .</p><p>Before start coding , we will create our MongoDB cluster and will create project on that cluster. So we have to go to the website of MongoDB: <a href="https://cloud.mongodb.com/">https://cloud.mongodb.com</a>, here we have to login then have to create our own project. For creating project we have to click on New Project Button, Then a modal will popup there we have to give the name of our project and then have to add your teammate name whom we want to give access , incase if we are building any project in a group .Now if we click on the Create Project , new project will be created . Now we have to create cluster where our data will be stored. For that we have to click on Build a cluster button, We have to select AWS as our cloud provider. Then select the region which cover our country and choose cluster tier as M0 Sandbox which is totally free, then we have to provide a name to our cluster. Then if we click on Create Cluster button , a cluster will be created . So we have created project cluster for our application.</p><p>Now let’s start coding. So we will start with the backend setup from db.js.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5b37915961ffcccd06f57b7c3c74fc28/href">https://medium.com/media/5b37915961ffcccd06f57b7c3c74fc28/href</a></iframe><p>In db.js first we are importing mongoDB . We are creating the MongoDB client called MongoClient , Then we are defining the mongoDB connection url , so from where we will get that ? we have to go to our mongoDB portal there will be a button connect , if we click on that there will be three options we have to select the second one ‘connect your application’ and then a url will be generated ,we have to just add the password and database name which we want to use to that url . Now we have to keep in mind the password which we will be adding is not the login password , we have to add the database access password. To get that password we have to go to the mongoDB portal and have to select Database Access from left navigation bar, Now there we have to add user by clicking on add new database user button, we have to provide username and password, we can also categories our user Database role and user privilege, we can keep Read and Write to any database option there for now . Then click on Add user. The password we provided there is the password we have to add in place of password in url . Now for the database name if we click on the collections button we will be redirecting to the page for adding database, we can create a database by clicking create database button. The name which we provide to that database, is that name which we have to add on the url . Now we are replacing password and database name placeholder with those values in the url and adding that url into our mongoUrl variable. initDb function is the function to initiate the data , if the data is already initialized it will show the message ‘Database is already initialized’ and will return a callback function with the db passed in argument. Then we are using connect() function with mongoDB url ,connect() function creates a connection to a MongoDB instance and returns the reference to the database. Once it is connected we are sending _db as the reference of the database and passing it to the callback function, and if there is any error we are sending the error into the callback function. getDb() function is used to get the database. Lastly we are import those two functions initDb and getDb so that we can use those in other files. Now let’s see the app.js file.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/160973a10131e38a078a6e611565cb22/href">https://medium.com/media/160973a10131e38a078a6e611565cb22/href</a></iframe><p>In app.js we are doing the actual backend setup of our application. We are importing path, express and body-parser. We have defined the routes of our application on routes folder inside backend. We are importing those routes in our app.js file and also the those two functions from db.js. Then we are creating instance of express and named it app. Then we are using body-parser , body-parser is Node.js body parsing middleware. It actually parse incoming request bodies in a middleware before your handlers, and the results are available under the req.body property. To serve static files such as images, CSS files, and JavaScript files, we use express.static built-in middleware function in Express. The path.join() method joins all given path segments together using the platform-specific separator as a delimiter, then normalizes the resulting path. So in the backend we are actually storing all the images present inside our images folder , to the backend route /images. Then we are adding specific values to our header so there will be no CORS issue so that React SPA is able to communicate with our server. We have created a group of routes inside routes folder , we want our products routes should render when the base route is ‘/route’ and authentication routes when the base route is ‘/’. Then we are calling our initDb() function defined in db.js .We are passing the callback function as parameter of the initDb() function if there is any error on creating or connecting the db we will console.log the error, else if everything is fine we ask our express instance (app) to listen to port number 3100.Now lets see the routes folder. Our routes folder is having two files auth.js and products.js . We will first check the auth.js</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fdd20ea1988bab39dad63286e45e07d5/href">https://medium.com/media/fdd20ea1988bab39dad63286e45e07d5/href</a></iframe><p>In auth.js , we will be defining the user authentication of the application .We are importing express.router, json web token and bcryptjs. jsonwebtoken is used to create json web token for the user login , whenever a user login we will be creating the json web token , once the token expires the user have to again login. bcryptjs is used to encrypt our password before storing it into our database. We are importing the initDb() and getDb() function from db.js. Then we are creating an instance of our Router. createToken() function is used to create json web token , we are setting the expiry duration to 1 hour , means a user can logged into our application for one hour , after that he/she have to login again. Now we are performing post request to the endpoint /login , So router.post is having 3 parameters request, response and next. We are fetching the data of email and password from request body. We are getting database from getDb() function , once we get the database. we are calling the db().collection to get the collection with name ‘users’ . users is the collection into which will be storing our user details. So when a user will try to login first we will check if that email matches with any of our user data. If it matches we will compare the entered password with the password stored in database using bcrypt.compare() function. So if the password is same the bcrypt.compare() function will return true, else it will return false. bcrypt.compare is a asynchronous function so we are adding .then if the returned response is false we will throw a error or if it is true we will create a token using createToken function other than that we will set response status code to 200 and on response json we will send message : ‘Authentication succeeded’ and json web token created when our user logged in. Now .catch is used to catch whatever error is thrown , so remember when our password is not matching we are throwing an error , catch function will catch that error. So once the password is not matching we are setting the http request status to 401 and in response json we are sending the message ‘Authentication failed, invalid username or password’. So this is how we are handling the login endpoint.</p><p>Now we will be looking into the signup endpoint. So in /signup we will be performing post request. Like login we are fetching email and password from the request body and hashing the password before storing it in database with bcrypt.hash() function , so in hash function we are passing two values actual password and the length of the hashed code. bcrypt.hash() function is an asynchronous function so in the .then method we are defining that if the password is hashed we will be storing the hashed password to our database. For storing the user data we are calling our getDb() function and the then inside our users collection in database we are inserting an object having email and password. Email contains the user email id and password contains the hashed password of that user. Once the user data is inserted into our database then we are creating our json web token, setting the response status to 201 and setting response json with an object having json web token and user email id. If there is any error in storing the data , we will be setting the http response status to 500 and will be setting response json with object having message ‘Creating the user failed’. Now let’s see our product routes.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c407f0ae170b634270ea92df2b8d804a/href">https://medium.com/media/c407f0ae170b634270ea92df2b8d804a/href</a></iframe><p>In products.js we will be defining our products routes. We are first importing express router, mongoDB , and functions defined in db.js. Think back to when you were first introduced to the concept of decimals in numerical calculations. Doing math problems along the lines of 3.231 / 1.28 caused problems when starting out because 1.28 doesn’t go into 3.231 evenly. This causes a long string of numbers to be created to provide a more precise answer. In programming languages, we must choose which number format is correct depending on the amount of precision we need. When one needs high precision when working with BSON data type , the decimal128 is the one to use. As the name suggests, decimal128 provides 128 bits of decimal representation for storing really big (or really small) numbers when rounding decimals exactly is important. So for that we are importing mongodb.Decimal128 for string price value into our database. ObjectId is used to create id for each document of our collection database. We have created our router instance . In the base route / we will be showing products page, we will be doing get request .We have created an empty array products for storing the products. Now we are finding data from products collection of our database and sorting the products in ascending order, then for each product document in database we are converting the price parameter which is in integer into string , then we are pushing the product document into our empty products variable. Since it’s a asynchronous we are adding .then method , so once all the product document id pushed into products array , we are send the products array into the response json with http status of 200.But if there is any error we are setting the response status to 500 with message: ‘An error occurred’.</p><p>/:id route will be route to displaying particular product details, where id is the object id of that particular product. Now we are calling our getDb() function to get the database, then on our products collection we are performing get operation , we are finding product those ObjectId (_id) which matches with the id in the route(req.params.id), req.params.id actually contains the value of id in our route /:id. So when we get the product id matched we are converting the product price into string. Then we are setting the response status to 200 and in the json we are sending the product document. And if there are any error we are setting http status code 500 and in json we are sending message ‘An error occurred’.</p><p>Now we will be adding new product to our products list .So we are doing post request. So we will be creating our object newProduct which will be having all the details of the product which we want to add .Then we are calling getDb() function , we are insert newProduct object into our products collection , when insertion is complete we are setting http status to 201 and in the response we are sending message ‘Product added’ and product Id. If there is any error we are setting http request status 500 with json message ‘An error occurred’.</p><p>We can also edit existing products, for that we will be doing patch request on /:id , where id will be the id of the product which we will be editing. So we are doing post request. We are creating our object updatedProduct which will be having the editing parameter of the product. Then we are calling getDb() function , we are using updateOne function ,updateOne function will be having two parameter, first one contains the condition for the determining which product we want to edit on database, if we keep it blank object it will reflect those changes to all the documents inside the collection. So we are putting condition that we will modify that product those ObjectId (_id) is equal to request.params.id(id in the route/:id), then we are just replacing the entire document with the update data (updatedProduct) using set operator. Post and patch is almost same only it’s more relevant to use patch when we are modifying any pre-existing document. So once the modification is done we will be setting http status to 200 and in the response json we are passing message: ‘Product updated’ and product id , else we will be passing the error message : ‘An error occurred’ in response json.</p><p>We can also delete our products , for that we will be calling delete request on ‘/:id’ where id will be the object id of the product we want to delete. So we are calling getDb() function , then we are deleting the document those ObjectId (_id) matches with the request.params.id(id in the route/:id). Once deleting is done we are setting the http response status to 200 , and in response json we are sending the message: ‘Product deleted’. Else if there is any error we will be setting response status code to 500 and sending error message ‘Product deleted’. So our backend api is now ready . Now we will be looking into our frontend. So we will start with index.js.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/080cae19cb1263e9e07e4e15a1ef322f/href">https://medium.com/media/080cae19cb1263e9e07e4e15a1ef322f/href</a></iframe><p>So index.js is the main file of our frontend .We are importing react , react-dom and from react-router-dom we are destructing BrowserRouter. We are also importing the index.css file for styling and our App component. We will be wrapping our App component with BrowserRouter so that we can implement the routing in our application. App.js is the main file which will be having the child components, so inside the div having id root we are rendering our App component by wrapping in with BrowserRouter. Now let’s see the App.js.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/48a07731b1de83dedddffff53ad35beb/href">https://medium.com/media/48a07731b1de83dedddffff53ad35beb/href</a></iframe><p>So App.js is the root file of our application it will be having all the child components of our application. We are importing react, react-router dom for routing and axios for api calls. Also we are importing components like Header, Modal, Backdrop, pages like Products, Product, EditProduct and Auth. So Now inside App component first we are defining the states , we are having isAuth, authMode and error parameters in state . logoutHandler function handles the log out functionality of our application, isAuth state is required to determine whether the user is logged in or not. So on logoutHandler we are setting the isAuth value to false. authHandler is the function to handle the authentication of our application , So if user enter the email id and password, the state authMode is first checked if it is login then the authData or the details user have entered will be post to the backend route <a href="http://localhost:3100/login">http://localhost:3100/login</a>.but if the authMode value in signup the user details will be posted to <a href="http://localhost:3100/signup">http://localhost:3100/signup</a>. So this authData will be there in the api (backend) on the request body. Now once the request is successful, the api will be returning a response authResponse , if the status of the authResponse is 200 or 201 , we are just storing the token we got from the response and finally setting the isAuth to true just to indicate that the user is now loggedin. Else if there is any error , we will calling error Handler function with the response error message, and setting the isAuth to false. authModeChangedHandler is the function to just toggle the state of authMode between login and signup. errorHandler sets the value of the error state with the message passed into it as argument. Now we will see the actual Dom structure of our application. Inside render we are first define the routes of our application. We used to define all the routes and redirects (if any) inside Switch tag. So inside Switch tag we are first defining the redirects for base route ‘/’ user will be redirected to ‘/products’ routes, from ‘/auth’ and signup also the user will be redirected to our products page. For path ‘/product/:mode’, mode value will be ‘add’ ,means for adding new products we will be using this route. So we are rendering our EditProductPage page and sending the response data and errorHandler function as props of the page. Similarly when the path is ‘/product/:id/;mode’ mode value will be ‘edit’ and id will be the object Id of the document (product) which we want to edit. Here also we are rendering EditProductPage page with the response data and errorHandler function as props of it. For route ‘products/:id’ id will be the object id of the particular product whose details will be shown into our product page, So there we are rendering our product page ProductPage with the response data and errorHandler function as props of it. ‘/products’ will be rendering our products page ( ProductPage ).But if our user is not authenticated means the isAuth state value is false. we will be defining a different route. We will redirecting our user from ‘/’ , ‘/product’ , ‘/products’ to ‘/auth’, we want our user to first login then continue with other pages. For the route ‘/auth’ we are rendering the our AuthPage , there we are passing our mode state , authHandler and authModeChangedHandler as props. Now we are finally rendering our Modal component which will appear whenever there is some error , there we are passing a custom title and errorHandler function as props and a paragraph as the child of it. Backdrop is used to make the background of our application blackish as the Modal opens. We have added our Header component , where we are passing isAuth state and logoutHandler function as props. And finally we are adding the routes variable which we have defined above.</p><p>So Now we will first look into our components. We will start with Backdrop .</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3b3601c74a344779438fac5a8574a06c/href">https://medium.com/media/3b3601c74a344779438fac5a8574a06c/href</a></iframe><p>In Backdrop.js we are just adding a div having the css class to add the blackish effect to entire application whenever error occurred and Modal component pops up.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1fba60a146c197c1fe1b9f864389a240/href">https://medium.com/media/1fba60a146c197c1fe1b9f864389a240/href</a></iframe><p>In Button.js , we are creating the button of our application. We are just having a html button tag with some styles and props.children rendered inside it.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/40d9bea8653f8e38e04e954bf110aacd/href">https://medium.com/media/40d9bea8653f8e38e04e954bf110aacd/href</a></iframe><p>In Header.js we have imported react , destructured NavLink from react-router-dom. NavLink is used to implement navigation between the pages of our application. First we are defining the links variable, if user is authenticated , we are creating a unordered list having NavLink for our products page, addProduct page and a button for logout. But if user is not authenticated we have only one NavLink for Authentication in unordered list. Finally we are rendering our links variable inside header.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/81bc06188f80e86476235c70031a84cd/href">https://medium.com/media/81bc06188f80e86476235c70031a84cd/href</a></iframe><p>In input.js we are creating the input fields of our application. So we are defining inputElement variable based on the elType props value , if elType is equal to ‘textarea’ we are adding textarea with all the config as props and we are passing the props onChange function in our onChange props . If the value of elType is something else other than ‘textarea’ we will be adding input tag. Then we are returning the dom , so inside a div there will be a label and our inputElement.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/af57108e245dc5ef4763011318754b3a/href">https://medium.com/media/af57108e245dc5ef4763011318754b3a/href</a></iframe><p>In Modal.js , we are importing our Button component. So modal will be displayed when the props value of open is true. So we are appending the open class on modal whenever the open value is true. We are having header with title, and 2 sections inside first section we are rendering our children and inside second section we are rendering the button element onClick of the button we are calling onClose() function coming as props.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/214f044f9f1e03042be652c364c9dd56/href">https://medium.com/media/214f044f9f1e03042be652c364c9dd56/href</a></iframe><p>In Product.js, we are iterating through products props , and rendering the ProductItem component. In ProductItem we are passing product id as key , product name as title, product description as text , product price as price, product image as imageUrl , and onDeleteProduct function as onDelete props.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e7784790c9e1c45dedf3da5695e0d658/href">https://medium.com/media/e7784790c9e1c45dedf3da5695e0d658/href</a></iframe><p>In ProductItem.js , We will be using article tag of html, so inside it we will be adding props.imageUrl as background Image of the first div. Then we are rendering product title, price and text. We are having three buttons Details, Edit and Delete. Details button is used to show the details of product, Edit and Delete is used to edit and delete that particular product. So for Details button we are using link tag to link it with the ‘/products/:product.id’ url. For Edit button we are linking it to ‘products/:product.id/edit’ .In backend the ‘edit’ will be denoted as mode value. For deleting product we are passing onDelete function with the product id on the onClick event of the delete button. Now let’s see the pages folder.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/bdbbf2658b8b81826db31d7985f7768c/href">https://medium.com/media/bdbbf2658b8b81826db31d7985f7768c/href</a></iframe><p>In Auth.js we are defining our authentication page. So state will be having two parameters email and password. inputChangeHandler is the function which is used to set our state values according to the values we will be entering in our input fields. Now we are checking value of mode for setting value of our modeButtonText and submitButtonText variable accordingly. This page will be having a button for login or signup, onClick of this we are calling onAuthModeChange function from props. Now inside the form we are having input fields for email and password. onChange of each input fields we are calling inputChangeHandler function with the input field name and event object. We are also having the button for submitting the form. onSubmit of the form we are calling onAuth function from props, with the object having input field values of email and password as the parameter . Now we will be looking into the products page.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1518da2891e4dcfc0680cfe21058fcc3/href">https://medium.com/media/1518da2891e4dcfc0680cfe21058fcc3/href</a></iframe><p>In products.js we are importing the products component. Our page is having two parameters in state those are isLoading and products. Inside componentDidMount() we are calling the fetchData function. So we will first see the fetchData() function , this function is used to fetch data from our backend. In fetchData () function we are performing get operation on our products endpoint (http://localhost:3100/products) to get all the products . Once we get all the products we are setting the value of isLoading to false and we are passing the response data to our products state. If there is any error we will be setting isLoading to false and will call onError function from props with the error message .Inside render we are defining the content variable so initially our content will be a paragraph having ‘Loading products…’ once isLoading is false and there will be products is our products array , we will be setting the content as the our product component , on that product component we are sending our product state and productDeleteHandler function as props. If the state isLoading is false and there is no product into the products array we will be set our content to the paragraph having text ‘Found no products. Try again later’. productDeleteHandler() function is used to delete the product so whenever user click on the delete button , we will be calling this function. In productDeleteHandler() we are performing delete request on <a href="http://localhost:3100/products/&#39;">http://localhost:3100/products/&#39;</a> and passing the product id in the request body , once it is deleted we are calling the fetchData() function just to reflect the changes in our ui but if there is any error we will be calling onError function with the error message .Then we are returning our content inside main tag. Now we will be looking into the product details page.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3cf4a7463589bb7921bb05fe904fa329/href">https://medium.com/media/3cf4a7463589bb7921bb05fe904fa329/href</a></iframe><p>In product.js we are designing our product details page. We have two parameter in states isLoading and product. So when the page loads in componentDidMount() we are fetching the details of the particular products .We are performing get function on the products endpoint <a href="http://localhost:3100/products/+">http://localhost:3100/products/+</a> we are appending the id from the page url(https://medium.com/this%C2%A0.props.match.params.id).Once we get the data of that particular product we are setting our isLoading state to false and passing the response data to our product state. If there is any error we will be setting isLoading state to false, and calling onError() function with error message. So we are rendering content variable , so initially our page will show ‘Is loading…’. If isLoading is false , and product details is fetched , we are setting content to main tag having product name, price, product image and description. If isLoading is false and there is no product details , we will show paragraph having text ‘Found no product. Try again later’. Now we will be seeing the Edit Product page.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/812e87ec3512a2a18d25d016a84faf2d/href">https://medium.com/media/812e87ec3512a2a18d25d016a84faf2d/href</a></iframe><p>In EditProduct.js , we are creating add product and edit product page of our application. We are importing our Input and Button component. So our ProductEditPage is having 5 parameters in state , isLoading , title, price, imageUrl and description. When our page renders , in componentDidMount we will be checking whether the user is adding new product or editing existing product for that we are checking this.props.match.params.mode if it is equal to ‘edit’, we will be performing get request on <a href="http://localhost:3100/products/">http://localhost:3100/products/</a>+we are appending the product id of the product we are editing. Once we get all the details of our product we are setting our isLoading state to false, title to product name, price to product price , imageUrl to product.image and description to product description. If this.props.match.params.mode is not equal to ‘edit’ we will just set our isLoading to false. editProductHandler() function is used to edit or add products in our application. We will be first error checking if the user have not entered any thing and clicks on the submit button we will just simply return the function we will not perform anything. If user enters all the details and submit the form we will first set the isLoading state to true, we will create an object productData with all the input fields values. Then we will creating our request based on the value of mode present in our url (this.props.match.params.mode). If mode is equal to ‘edit’ we will be preforming patch request to the endpoint ‘http://localhost:3100/products/&#39; + this.props.match.params.id’ and will send the productData in the request body. But if it is not then it means the user is actually adding new products for that we are performing post request to the endpoint ‘<a href="http://localhost:3100/products">http://localhost:3100/products</a> ’ and will send the productData in the request body. Once we get the response we will set isLoading state to false, and redirecting our page to products page. If there is any error , we are setting isLoading states to false and calling our onError() function with error message. inputChangeHandler() function is used to set our state value with the input field value. So inside render we will setting our content, So our content will be a form having input fields for product title, price, image, description. For each fields we are passing the config object, label, elType, and on onChange() function we are calling inputChangeHandler function with event object and label of each input field. Then we are having button to submit the edit /add product form , on submission of the form we are calling editProductHandler() function. If this.state.isLoading is true we will set content to paragraph having text ‘Is loading…’.And finally render our content inside main tag.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/69bfc388380649497ad5778198c3873a/href">https://medium.com/media/69bfc388380649497ad5778198c3873a/href</a></iframe><p>So our application is now ready but how we will running our application for that we will add our package.json , we just have to run <strong>npm init</strong> in our terminal , it will ask few questions but free to skip those by pressing enter. Then we will see our package.json will be created in our root folder. There we can add npm package as dependencies by running <strong>npm i &lt;package name&gt;</strong>. We have added few packages like axios, bcryptjs, body-parser and many more. So we will run <strong>npm i </strong>just to install all the dependencies from package.json. We will see node_modules folder will be created. Then we will run <strong>npm run start</strong> for running frontend , for running backend we will again open a new terminal and will run <strong>npm run start:server . </strong>Now let’s see our application.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fcodesandbox.io%2Fembed%2Funruffled-darkness-fzz8r&amp;display_name=CodeSandbox&amp;url=https%3A%2F%2Fcodesandbox.io%2Fs%2Funruffled-darkness-fzz8r&amp;image=https%3A%2F%2Fcodesandbox.io%2Fapi%2Fv1%2Fsandboxes%2Ffzz8r%2Fscreenshot.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=codesandbox" width="1000" height="500" frameborder="0" scrolling="no"><a href="https://medium.com/media/22455c5dc996ecd0c70be96015d592e5/href">https://medium.com/media/22455c5dc996ecd0c70be96015d592e5/href</a></iframe><p>So this is one way of creating a simple application using mongoDB as database and react as frontend. But it’s little bit complex we have to create the backend and frontend separately then have to connect and perform CRUD operations. In part 2 we will be building the same application with Stitch which is server less backend solution, which is having features like server less query API, databases triggers and real time sync .This will actually reduce our effort of creating application . Stitch takes care of most of the backend staffs. Till then we can go through the document of the mongoDB , it’s really nice and will give a descriptive overview of mongoDB concepts. I am attaching my github repo and mongoDB documentation link as the reference of this article.</p><p><strong>MongoDB Documentation:</strong></p><p><a href="https://docs.mongodb.com/">Welcome to the MongoDB Documentation</a></p><p><strong>Code:</strong></p><p><a href="https://github.com/Yudhajitadhikary/MongoDB_With_RestAPI">Yudhajitadhikary/MongoDB_With_RestAPI</a></p><p><strong>HAPPY CODING..:)</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7712a1f9f42" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>