<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>DEV Community: Nitin Patel</title>
    <description>The latest articles on DEV Community by Nitin Patel (@niinpatel).</description>
    <link>https://dev.to/niinpatel</link>
    <image>
      <url>https://media2.dev.to/dynamic/image/width=90,height=90,fit=cover,gravity=auto,format=auto/https:%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F97741%2Fb31b9460-0b92-4b18-b0cd-7ccadcfdfff0.jpeg</url>
      <title>DEV Community: Nitin Patel</title>
      <link>https://dev.to/niinpatel</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://dev.to/feed/niinpatel"/>
    <language>en</language>
    <item>
      <title>What does the phrase Monadic Bind mean in Haskell?</title>
      <dc:creator>Nitin Patel</dc:creator>
      <pubDate>Fri, 07 Jun 2019 09:57:03 +0000</pubDate>
      <link>https://dev.to/niinpatel/what-does-the-phrase-monadic-bind-mean-in-haskell-ie7</link>
      <guid>https://dev.to/niinpatel/what-does-the-phrase-monadic-bind-mean-in-haskell-ie7</guid>
      <description>&lt;p&gt;I’ve been learning Haskell for a few months now and I think I have a good understanding of what monads are. I’m not an expert so I should warn you this answer might be completely wrong.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://www.quora.com/In-Haskell-what-does-the-phrase-monadic-bind-mean/answer/Nitin-Patel-46"&gt;I originally posted this as a Quora answer. Reposting it here:&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Monadic bind&lt;/strong&gt; is the name given to the (&amp;gt;&amp;gt;=) function or bind function, also known as chain, flatMap, or joinMap.&lt;/p&gt;

&lt;p&gt;I personally like to call it the “then” function borrowing the word from JavaScript Promises. It is much more intuitive that way if you read it as “then” instead of “bind”.&lt;/p&gt;

&lt;p&gt;Consider the following Haskell program which takes a number from stdin and prints its square root in stdout.&lt;/p&gt;


&lt;div class="ltag_gist-liquid-tag"&gt;
  
&lt;/div&gt;


&lt;p&gt;If you read the (&amp;gt;&amp;gt;=) as &lt;em&gt;then&lt;/em&gt;. The program basically read as:&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;main = getLine &lt;em&gt;then&lt;/em&gt; stringToNumber &lt;em&gt;then&lt;/em&gt; squareRoot *then *print.&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;If you have programmed in JavaScript and you’re familiar with Promises, you will find this approach quite intuitive.&lt;/p&gt;

&lt;p&gt;In Practice, most people use the “Do Notation” which is just syntactic sugar over the monadic bind syntax. Once, you understand this, do notation should be quite easy.&lt;/p&gt;

&lt;p&gt;For reference, here’s the same program converted to “Do notation”.&lt;/p&gt;


&lt;div class="ltag_gist-liquid-tag"&gt;
  
&lt;/div&gt;


&lt;h2&gt;
  
  
  &lt;strong&gt;But what does (&amp;gt;&amp;gt;=) function actually do?&lt;/strong&gt;
&lt;/h2&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--ZNeF5FDV--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://cdn-images-1.medium.com/max/2000/0%2AWXYsA_WrYTAaQMRH" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--ZNeF5FDV--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://cdn-images-1.medium.com/max/2000/0%2AWXYsA_WrYTAaQMRH" alt="It’s just a monoid in the category of endofunctors. What’s the problem?"&gt;&lt;/a&gt;&lt;em&gt;It’s just a monoid in the category of endofunctors. What’s the problem?&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;To know what this function actually does, we first need to know what a monad is. The definition of monad can be found on &lt;a href="https://en.wikipedia.org/wiki/Monad_(functional_programming)"&gt;Wikipedia Page on Monads&lt;/a&gt;:&lt;/p&gt;

&lt;blockquote&gt;
&lt;h1&gt;
  
  
  &lt;em&gt;a **monad&lt;/em&gt;* is a &lt;a href="https://en.wikipedia.org/wiki/Design_pattern"&gt;design pattern&lt;/a&gt; that allows structuring programs &lt;a href="https://en.wikipedia.org/wiki/Generic_programming"&gt;generically&lt;/a&gt; while automating away &lt;a href="https://en.wikipedia.org/wiki/Boilerplate_code"&gt;boilerplate code&lt;/a&gt; needed by the program logic.*
&lt;/h1&gt;
&lt;/blockquote&gt;

&lt;p&gt;Right now, this sentence doesn’t make sense, hopefully, it will make some sense after I give a few examples.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Example 1: Handling Null values (Maybe type).&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;I’ll use JavaScript syntax for convenience.&lt;/p&gt;

&lt;p&gt;Let’s say we have a value which may or may not exist (nullable), we want to perform some computations on the value. These computations could also fail and return null values. Our code will be:&lt;/p&gt;


&lt;div class="ltag_gist-liquid-tag"&gt;
  
&lt;/div&gt;
 

&lt;p&gt;This code violates the &lt;a href="https://en.wikipedia.org/wiki/Don't_repeat_yourself"&gt;DRY Principle&lt;/a&gt; and is quite ugly because of all the nesting. Let’s try to abstract out the repetitive code.&lt;/p&gt;

&lt;p&gt;We can design a maybe data type which holds either some value or Null. And we can define a function that does null checking for you.&lt;/p&gt;

&lt;p&gt;Now, instead of our functions returning null, it will return this Maybe data type. Here’s an example implementation with some functions returning Maybe type.&lt;/p&gt;


&lt;div class="ltag_gist-liquid-tag"&gt;
  
&lt;/div&gt;


&lt;p&gt;Then we can write our program into a flat pipeline instead of the nested hell we had earlier.&lt;/p&gt;


&lt;div class="ltag_gist-liquid-tag"&gt;
  
&lt;/div&gt;


&lt;p&gt;If at any point the function returns Null, all other computations will be skipped. (Like if we divide by zero or square root a negative number).&lt;/p&gt;

&lt;p&gt;Now, look again at the definition of the monad I gave above, and see if it makes a little bit more sense now:&lt;/p&gt;

&lt;blockquote&gt;
&lt;h1&gt;
  
  
  &lt;em&gt;a **monad **is a &lt;a href="https://en.wikipedia.org/wiki/Design_pattern"&gt;design pattern&lt;/a&gt; that allows structuring programs &lt;a href="https://en.wikipedia.org/wiki/Generic_programming"&gt;generically&lt;/a&gt; while automating away &lt;a href="https://en.wikipedia.org/wiki/Boilerplate_code"&gt;boilerplate code&lt;/a&gt; needed by the program logic.&lt;/em&gt;
&lt;/h1&gt;
&lt;/blockquote&gt;

&lt;p&gt;&lt;strong&gt;Example 2:&lt;/strong&gt; &lt;strong&gt;Handling Async Values (Promises)&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Let’s say that instead of returning Null values, our functions returned *Async *values, meaning that values that don’t exist yet but will be available in future. (For example, it’s an API request or Database call).&lt;/p&gt;

&lt;p&gt;Here, instead of checking for null values, we need to *wait *for the value of the previous result to be available because we execute any function.&lt;/p&gt;

&lt;p&gt;JavaScript had a solution to this called &lt;strong&gt;The&lt;/strong&gt; **Callback Pattern. **Callback pattern solved this problem but it resulted in the same kind of nested callback hell we saw earlier. &lt;a href="http://callbackhell.com/"&gt;more about callbacks&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;This is why the popular approach to handling async values in JavaScript is to use Promises.&lt;/p&gt;

&lt;p&gt;We have seen that the &lt;em&gt;then&lt;/em&gt; function in Maybe type performs an “if check” for us between every function execution. The &lt;em&gt;then *function in Promises waits for the previous result and executes the given function when it is available.&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;This allows us to convert a nested callback code into a flat pipeline of functions.&lt;/p&gt;


&lt;div class="ltag_gist-liquid-tag"&gt;
  
&lt;/div&gt;


&lt;p&gt;Hopefully, you can see a pattern here and somewhat grasp the abstract concept of monads.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;But what about the IO Monad in Haskell?&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;The IO Monad works on the same principle. As we have seen before, monadic bind performs some intermediate computation in between functions, removing the need for us to write boilerplate code.&lt;/p&gt;

&lt;p&gt;In this case, the boilerplate code would be pulling out the value obtained by performing side effect and passing it to the next function in our chain of functions.&lt;/p&gt;

&lt;p&gt;They’re also quite similar to promises meaning that they guarantee the order of execution by creating a dependency on previous value for the function to execute. Example,&lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;main = function1 &amp;gt;&amp;gt;= function2 &amp;gt;&amp;gt;= function3
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;

&lt;p&gt;Here, function1 &lt;em&gt;depends *on the value returned by function2. It cannot run until function1 is finished. Similarly, function3&lt;/em&gt;* **cannot run until function2 has finished.&lt;/p&gt;

&lt;p&gt;If you want to actually see what bind function in IO monad does, watch this video. It is the best explanation I’ve found for IO monad.&lt;/p&gt;

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

&lt;blockquote&gt;
&lt;p&gt;** sidenote: &lt;a href="https://buzzdecafe.github.io/2018/04/10/no-promises-are-not-monads"&gt;Promise is not actually monad&lt;/a&gt;, &lt;strong&gt;but&lt;/strong&gt; it’s pretty close and solves the same problem that monads solve. My purpose here is to build intuition and not be 100% accurate.*&lt;/p&gt;
&lt;/blockquote&gt;

</description>
      <category>haskell</category>
      <category>monads</category>
      <category>functional</category>
      <category>programming</category>
    </item>
    <item>
      <title>How To Correctly Shuffle An Array in JavaScript</title>
      <dc:creator>Nitin Patel</dc:creator>
      <pubDate>Wed, 22 May 2019 06:34:56 +0000</pubDate>
      <link>https://dev.to/niinpatel/how-to-correctly-shuffle-an-array-in-javascript-19dl</link>
      <guid>https://dev.to/niinpatel/how-to-correctly-shuffle-an-array-in-javascript-19dl</guid>
      <description>&lt;p&gt;About 9 years ago, TechCrunch published &lt;a href="https://techcrunch.com/2010/02/22/microsoft-ballot-screen"&gt;this story&lt;/a&gt;. Microsoft had this browser ballot screen on browserchoice.eu where Microsoft was supposed to show all the different browser choices to users in random order.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--TTA_KdiO--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://thepracticaldev.s3.amazonaws.com/i/i64jopjl0j8fanpjt5mp.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--TTA_KdiO--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://thepracticaldev.s3.amazonaws.com/i/i64jopjl0j8fanpjt5mp.png" alt="microsoft ballot screen on browserchoice.eu"&gt;&lt;/a&gt;&lt;/p&gt;
"randomly" sorted


 

&lt;p&gt;Except, it was far from random. Internet Explorer showed up in the last position about 50% of the time and Chrome was most likely to show up in the top 3. What gives? Well, here’s the code they used for doing the random shuffle:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;array.sort(function (a, b) { return 0.5 — Math.random() })
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;



&lt;p&gt;At first glance, this seems like a reasonable solution. In fact, if you google search “random shuffle javascript” this code is the top result that pops up. &lt;br&gt;
The code uses javascript’s sort function with a custom comparator. This comparator a number between 0.5 and -0.5.&lt;/p&gt;

&lt;p&gt;One of the problems with this sorting algorithm, however, is that it does not work. If you want a random shuffle in which every permutation is equally likely. This algorithm fails badly at it. &lt;a href="http://www.robweir.com/blog/2010/02/microsoft-random-browser-ballot.html"&gt;Here’s an interesting statistical analysis on the results of this algorithm&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;Other than being wrong, it is also very inefficient. The time complexity of a regular sort function is O(n.logn). But in this case, the sort function is given a very inconsistent ordering. So, this could go into an infinite loop or stop after a few exchanges depending on the algorithm used for sorting.&lt;/p&gt;
&lt;h3&gt;
  
  
  The Correct Way — Fisher-Yates Algorithm
&lt;/h3&gt;

&lt;p&gt;Shuffling an array of values is one of the oldest problems in computer science. And the most popular solution to it has been known since 1938. It is the Fisher-Yates shuffle.&lt;/p&gt;

&lt;p&gt;Unlike the Microsoft shuffle, this algorithm actually shuffles the array randomly and has O(n) time complexity assuming you have a random number generator with O(1) complexity.&lt;/p&gt;

&lt;p&gt;The original fisher yates algorithm, described is 1938 goes something likes this:&lt;/p&gt;

&lt;blockquote&gt;
&lt;ol&gt;
&lt;li&gt;Write down the numbers from 1 through N.&lt;/li&gt;
&lt;li&gt;Pick a random number k between one and the number of unstruck numbers remaining (inclusive).&lt;/li&gt;
&lt;li&gt;Counting from the low end, strike out the kth number not yet struck out, and write it down at the end of a separate list.&lt;/li&gt;
&lt;li&gt;Repeat from step 2 until all the numbers have been struck out.&lt;/li&gt;
&lt;li&gt;The sequence of numbers written down in step 3 is now a random permutation of the original numbers.
Source: 
&lt;a href="https://en.wikipedia.org/wiki/Fisher%E2%80%93Yates_shuffle#Fisher_and_Yates'_original_method"&gt;https://en.wikipedia.org/wiki/Fisher%E2%80%93Yates_shuffle#Fisher_and_Yates'_original_method&lt;/a&gt;
&lt;/li&gt;
&lt;/ol&gt;
&lt;/blockquote&gt;

&lt;p&gt;The modern version of this algorithm (from the book &lt;a href="https://en.wikipedia.org/wiki/The_Art_of_Computer_Programming"&gt;The Art of Computer Programming&lt;/a&gt; by Donald E. Knuth) goes like this:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt; — To shuffle an array a of n elements (indices 0..n-1):
for i from n−1 downto 1 do
 j ← random integer such that 0 ≤ j ≤ i
 exchange a[j] and a[i]
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;



&lt;p&gt;In javascript, it’d be implemented as:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;for(let i = array.length — 1; i &amp;gt; 0; i--){
  const j = Math.floor(Math.random() * array.length)
  const temp = array[i]
  array[i] = array[j]
  array[j] = temp
}
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;



&lt;h3&gt;
  
  
  Final Thoughts
&lt;/h3&gt;

&lt;p&gt;When trying to solve a problem, look for tried-and-tested approaches.&lt;/p&gt;

&lt;p&gt;We as programmers stand on the shoulders of giants. These algorithms have been polished and refined in the last 7+ decades. There is very little chance that your own implementation is going to be better than that.&lt;/p&gt;

</description>
      <category>javascript</category>
      <category>algorithms</category>
    </item>
    <item>
      <title>Converting XML to JSON using Recursion</title>
      <dc:creator>Nitin Patel</dc:creator>
      <pubDate>Fri, 28 Sep 2018 12:39:09 +0000</pubDate>
      <link>https://dev.to/niinpatel/converting-xml-to-json-using-recursion-2k4j</link>
      <guid>https://dev.to/niinpatel/converting-xml-to-json-using-recursion-2k4j</guid>
      <description>&lt;p&gt;The other day, I was working on an app which needed to fetch data from a third party rest api, and what happened next is the thing of the one of the worst nightmares of a JavaScript developer.&lt;/p&gt;

&lt;p&gt;The server sent back response in.. gasp.. XML instead of JSON like any sane rest api would do.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Ft4deqh55prtd83ts8pno.jpeg" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Ft4deqh55prtd83ts8pno.jpeg" width="594" height="334"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;So, I came up with a way to easily convert XML into JavaScript Object. &lt;a href="https://gist.github.com/niinpatel/2c9923c30ecf356fa07b50b2d6c47f60" rel="noopener noreferrer"&gt;Here’s an example of the data I was trying to read.&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Keep in mind that this code makes use of WebAPIs so it is not available in server side javascript like NodeJS. This works great for front end applications like React or Angular.&lt;/p&gt;

&lt;p&gt;The format of XML is generally something like this:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;lt;book&amp;gt;
    &amp;lt;title&amp;gt;Some title&amp;lt;/title&amp;gt;
    &amp;lt;description&amp;gt;some description &amp;lt;/description&amp;gt;
    &amp;lt;author&amp;gt;
        &amp;lt;id&amp;gt;1&amp;lt;/id&amp;gt;
        &amp;lt;name&amp;gt;some author name&amp;lt;/name&amp;gt;
    &amp;lt;/author&amp;gt;
    &amp;lt;review&amp;gt;nice book&amp;lt;/review&amp;gt;
    &amp;lt;review&amp;gt;this book sucks&amp;lt;/review&amp;gt;
    &amp;lt;review&amp;gt;amazing work&amp;lt;/review&amp;gt;
&amp;lt;/book&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;I want the ouput to look a little something like this:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;{
  "book": {
    "title": "Some title",
    "description": "some description",
    "author": { "id": "1", "name": "some author name" },
    "review": ["nice book", "this book sucks", "amazing work"]
  }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Since, XML has a lot of nested tags, this problem is a perfect example of a practical application of recursion.&lt;/p&gt;

&lt;p&gt;Before we begin to code, we need to understand something called the &lt;a href="https://developer.mozilla.org/en-US/docs/Web/API/DOMParser" rel="noopener noreferrer"&gt;DOMParser&lt;/a&gt; Web API.&lt;/p&gt;

&lt;p&gt;According to the MDN documentation,&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;The &lt;code&gt;DOMParser&lt;/code&gt; interface provides the ability to parse &lt;a href="https://developer.mozilla.org/en-US/docs/Glossary/XML" rel="noopener noreferrer"&gt;XML&lt;/a&gt; or &lt;a href="https://developer.mozilla.org/en-US/docs/Glossary/HTML" rel="noopener noreferrer"&gt;HTML&lt;/a&gt; source code from a string into a DOM TREE.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;In simple words, it converts and XML string into a DOM Tree. Here’s how it works.&lt;/p&gt;

&lt;p&gt;Lets say we have an some XML stored in a string, strxml. We can parse the data in it as a DOM tree like this:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;let strxml = `&amp;lt;book&amp;gt;&amp;lt;title&amp;gt;Some title&amp;lt;/title&amp;gt;
&amp;lt;description&amp;gt;some description &amp;lt;/description&amp;gt;
&amp;lt;author&amp;gt;
    &amp;lt;id&amp;gt;1&amp;lt;/id&amp;gt;
    &amp;lt;name&amp;gt;some author name&amp;lt;/name&amp;gt;
&amp;lt;/author&amp;gt;
&amp;lt;review&amp;gt;nice book&amp;lt;/review&amp;gt;
&amp;lt;review&amp;gt;this book sucks&amp;lt;/review&amp;gt;
&amp;lt;review&amp;gt;amazing work&amp;lt;/review&amp;gt;&amp;lt;/book&amp;gt;
`;

const parser = new DOMParser();  // initialize dom parser
const srcDOM = parser.parseFromString(strxml, "application/xml");  // convert dom string to dom tree. 

// Now we can call DOM methods like GetElementById, etc. on scrDOM. 
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Now that we have got the basics right. Let’s start writing the psuedo code.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Initialize variable jsonResult is empty object. 
If scrDOM has no children nodes:
    return innerHTML of the DOM. // This is our base case.

For each childNode in children nodes:
    Check if childNode has siblings of same name. 
    If it has no siblings of same name: 
        set childnode name as key whose value is json of the child node. (we're calling the function recursively.)
    If it has no siblings of same name
        set childnode name as key whose value is an empty array, every child whose name is same as this pushed into this array.
return jsonResult
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Here’s the JavaScript code:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;/**
 * This function coverts a DOM Tree into JavaScript Object. 
 * @param srcDOM: DOM Tree to be converted. 
 */
function xml2json(srcDOM) {
  let children = [...srcDOM.children];

  // base case for recursion. 
  if (!children.length) {
    return srcDOM.innerHTML
  }

  // initializing object to be returned. 
  let jsonResult = {};

  for (let child of children) {

    // checking is child has siblings of same name. 
    let childIsArray = children.filter(eachChild =&amp;gt; eachChild.nodeName === child.nodeName).length &amp;gt; 1;

    // if child is array, save the values as array, else as strings. 
    if (childIsArray) {
      if (jsonResult[child.nodeName] === undefined) {
        jsonResult[child.nodeName] = [xml2json(child)];
      } else {
        jsonResult[child.nodeName].push(xml2json(child));
      }
    } else {
      jsonResult[child.nodeName] = xml2json(child);
    }
  }

  return jsonResult;
}

// testing the function
let xmlstr = `&amp;lt;book&amp;gt;&amp;lt;title&amp;gt;Some title&amp;lt;/title&amp;gt;
&amp;lt;description&amp;gt;some description &amp;lt;/description&amp;gt;
&amp;lt;author&amp;gt;
    &amp;lt;id&amp;gt;1&amp;lt;/id&amp;gt;
    &amp;lt;name&amp;gt;some author name&amp;lt;/name&amp;gt;
&amp;lt;/author&amp;gt;
&amp;lt;review&amp;gt;nice book&amp;lt;/review&amp;gt;
&amp;lt;review&amp;gt;this book sucks&amp;lt;/review&amp;gt;
&amp;lt;review&amp;gt;amazing work&amp;lt;/review&amp;gt;&amp;lt;/book&amp;gt;
`;

// converting to DOM Tree
const parser = new DOMParser();
const srcDOM = parser.parseFromString(xmlstr, "application/xml");

// Converting DOM Tree To JSON. 
console.log(xml2json(srcDOM));

/** The output will be
{
  "book": {
    "title": "Some title",
    "description": "some description",
    "author": { "id": "1", "name": "some author name" },
    "review": ["nice book", "this book sucks", "amazing work"]
  }
}
*/
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This is the basic algorithm / code for converting an XML string into a JSON object. Since, it uses recursion, it can go very deep into the DOM tree and parse every single element.&lt;/p&gt;

&lt;p&gt;This works for most of the cases. You can modify this algorithm according to your own needs or requirements.&lt;/p&gt;

</description>
      <category>xml</category>
      <category>json</category>
      <category>javascript</category>
    </item>
  </channel>
</rss>
