<?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 Ziyo Shams on Medium]]></title>
        <description><![CDATA[Stories by Ziyo Shams on Medium]]></description>
        <link>https://medium.com/@ziyoshams?source=rss-394aa3bad17c------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*tRJpheO3ekdsRTdd7r1Y_Q.jpeg</url>
            <title>Stories by Ziyo Shams on Medium</title>
            <link>https://medium.com/@ziyoshams?source=rss-394aa3bad17c------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 23 Nov 2026 00:00:39 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@ziyoshams/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[Graph Data Structure in JavaScript]]></title>
            <link>https://medium.com/@ziyoshams/graphs-in-javascript-cc0ed170b156?source=rss-394aa3bad17c------2</link>
            <guid isPermaLink="false">https://medium.com/p/cc0ed170b156</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[breadth-first-search]]></category>
            <category><![CDATA[bfs-dfs]]></category>
            <category><![CDATA[graph]]></category>
            <category><![CDATA[depth-first-search]]></category>
            <dc:creator><![CDATA[Ziyo Shams]]></dc:creator>
            <pubDate>Mon, 30 Jul 2018 15:58:27 GMT</pubDate>
            <atom:updated>2018-08-01T15:48:12.586Z</atom:updated>
            <content:encoded><![CDATA[<p>Unfortunately there isn’t many sources for JavaScript when it comes to <strong>Data</strong> <strong>Structures</strong>. I have decided to share my knowledge about <strong>Graphs</strong>, so someone like you could find and learn from it. Firstly, I am assuming that you already have some idea about what <strong>Graphs</strong> are. I won’t bore you with the definition. Let’s get started with implementation.</p><h3>Create an <strong>ES6 class</strong></h3><p>We will be implementing <strong>Directed Graph (Digraph)</strong><em> </em>with<em> </em><strong>Adjacency List.<em> </em></strong>Also I will be using some <strong>ECMA2015+</strong> syntax, which should not be difficult to understand.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/039e71364f4a7ebbfba255ec9bf59e30/href">https://medium.com/media/039e71364f4a7ebbfba255ec9bf59e30/href</a></iframe><p>In the constructor we create a new instance of <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map">Map</a> object and we call it AdjList. (<em>If you are not comfortable with </em><strong>Maps</strong><em> use </em><strong>Object</strong><em>, they are very similar. Example: </em>this.AdjList = {}).</p><h3>Add basic Graph methods</h3><h4>Add Vertex method</h4><pre>addVertex(<em>vertex</em>) {<br>  if (!<em>this</em>.AdjList.has(vertex)) {<br><em>    this</em>.AdjList.set(vertex, []);<br>  } else {<br>    throw &#39;Already Exist!!!&#39;;<br>  }<br>}</pre><p>This method takes a vertex as an argument and adds it to the graph.</p><p>For example, create an <em>instance of the Graph</em> and add several <em>vertices</em>:</p><pre>let graph = new Graph();<br>graph.addVertex(&#39;A&#39;);<br>graph.addVertex(&#39;B&#39;);<br>graph.addVertex(&#39;C&#39;);<br>graph.addVertex(&#39;D&#39;);</pre><p>Now our AdjList variable contains this:</p><pre>Map {<br>  &#39;A&#39; =&gt; [],<br>  &#39;B&#39; =&gt; [],<br>  &#39;C&#39; =&gt; [],<br>  &#39;D&#39; =&gt; []<br>}</pre><p>Why do we have <strong>values</strong> as an <strong>empty array</strong>? In that array we will be storing <strong>edges</strong>. Here is an illustration:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/820/1*4s5Z7gVwVqmKcslgiamRyw.png" /></figure><p>If we were to implement the graph on the illustration then our <strong>Map</strong> would look like this:</p><pre>Map {<br>  &#39;A&#39; =&gt; [&#39;B&#39;, &#39;C&#39;, &#39;D&#39;],<br>  &#39;B&#39; =&gt; [],<br>  &#39;C&#39; =&gt; [&#39;B&#39;],<br>  &#39;D&#39; =&gt; [&#39;C&#39;]<br>}</pre><p>Let’s implement addEdge method which will populate those empty arrays.</p><h4>Add Edge method</h4><pre>addEdge(<em>vertex</em>, <em>node</em>) {<br>  if (<em>this</em>.AdjList.has(vertex)) {<br>    if (<em>this</em>.AdjList.has(node)){<br>      let arr = <em>this</em>.AdjList.get(vertex);<br>      if(!arr.includes(node)){<br>        arr.push(node);<br>      }<br>    }else {<br>      throw `Can&#39;t add non-existing vertex -&gt;&#39;${node}&#39;`;<br>    }<br>  } else {<br>    throw `You should add &#39;${vertex}&#39; first`;<br>  }<br>}</pre><p>Before we add an <strong>edge</strong> to a <strong>vertex</strong>, we have to verify if that <strong>vertex</strong> exists. After that make sure that <strong>edge </strong>that we are trying to add<strong> </strong>does not already exist. If all checks pass, then we can add the <strong>edge</strong> to a <strong>vertex</strong>. (<em>We could use </em><strong><em>Set</em></strong><em> instead of </em><strong><em>array</em></strong><em>, but that is too much of </em><strong><em>ES6</em></strong>).</p><h3>Add print method</h3><p>This step is not necessary, but after adding <strong>vertices</strong> and <strong>edges</strong> we want to see if they are being added properly.</p><pre>print() {<br>  for (let [key, value] of <em>this</em>.AdjList) {<br>    console.log(key, value);<br>  }<br>}</pre><h3>Here is what you should have by now:</h3><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4dd93355aa249b7ecba382638ec4099e/href">https://medium.com/media/4dd93355aa249b7ecba382638ec4099e/href</a></iframe><h3>Let’s build a Graph</h3><pre>let g = new Graph();<br>let arr = [&#39;A&#39;, &#39;B&#39;, &#39;C&#39;, &#39;D&#39;, &#39;E&#39;, &#39;F&#39;];</pre><pre>for (let i = 0; i &lt; arr.length; i++) {<br>  g.addVertex(arr[i]);<br>}</pre><pre>g.addEdge(&#39;A&#39;, &#39;B&#39;);<br>g.addEdge(&#39;A&#39;, &#39;D&#39;);<br>g.addEdge(&#39;A&#39;, &#39;E&#39;);<br>g.addEdge(&#39;B&#39;, &#39;C&#39;);<br>g.addEdge(&#39;D&#39;, &#39;E&#39;);<br>g.addEdge(&#39;E&#39;, &#39;F&#39;);<br>g.addEdge(&#39;E&#39;, &#39;C&#39;);<br>g.addEdge(&#39;C&#39;, &#39;F&#39;);<br>g.print();</pre><pre>/* PRINTED */<br>// A [ &#39;B&#39;, &#39;D&#39;, &#39;E&#39; ]<br>// B [ &#39;C&#39; ]<br>// C [ &#39;F&#39; ]<br>// D [ &#39;E&#39; ]<br>// E [ &#39;F&#39;, &#39;C&#39; ]<br>// F []</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*I_LgoFZ6uPb1GFCoxWH4Dw.png" /></figure><p>So far, this is what you need to create a <strong>Graph</strong>. But, 99% of the time you will be asked to implement two more methods. Let’s get those aside too. We will be adding <strong>Breadth First Search</strong> and <strong>Depth First Search</strong> methods.</p><h3>Breadth First Search (BFS)</h3><p><strong>BFS</strong> in <strong>Graphs</strong> is almost the same as in <strong>Binary Search Tree</strong>, but there is a little difference. The main difference is that you can have loops in Graphs. You have to keep track of the <em>nodes</em> that you visit. Here is how you do it:</p><ul><li>BFS gets a starting node as an argument. (e.g &#39;A&#39; )</li><li>initialize an <em>empty object</em> called visited .</li><li>initialize an <em>empty array</em> called q which will be used as a <strong>Queue</strong>.</li><li>mark the starting node as <strong>visited</strong>. ( visited = {&#39;A&#39;: true} )</li><li>put the starting node in the queue. ( q = [&#39;A&#39;] )</li><li><strong>loop</strong> until queue is empty</li></ul><p>Inside the <strong>loop</strong>:</p><ul><li>take an element from the q and store it in a variable. ( let current = q.pop() )</li><li>print current</li><li>get edges for current from the graph. (let arr = this.AdjList.get(current)). Lets say we popped A from the queue and got arr = [&#39;B&#39;,&#39;D&#39;,&#39;E&#39;] .</li><li>if element is <strong>not visited</strong>, mark each element as visited and put it in the queue.</li></ul><pre>visited = {<br>  &#39;A&#39;: true,<br>  &#39;B&#39;: true,<br>  &#39;D&#39;: true,<br>  &#39;E&#39;: true<br>}</pre><pre>q = [&#39;B&#39;, &#39;D&#39;, &#39;E&#39;]</pre><h3>BFS method code snippet</h3><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/697418d1acea0972c537c1db4b89af35/href">https://medium.com/media/697418d1acea0972c537c1db4b89af35/href</a></iframe><h3>Depth First Search (DFS)</h3><p>This method will accept a starting node like BFS and keep track of visited nodes. We will implement this method recursively and the <strong>helper</strong> function will do the recursion. Here is how we do it:</p><ul><li>Accept a starting point as an argument dfs(startingNode) .</li><li>Create <strong>visited</strong> object let visited = this.createVisitedObject() .</li><li>Call the helper function passing starting node and visited object this.dfsHelper(startingNode, visited) .</li><li>dfsHelper will mark it as visited and print it.</li></ul><p>It will be very hard for me to illustrate recursion here, but examine the for loop to understand what is happening. Here is a code snippet.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ee2cbe0c2efa47de7bbdb7651f3f5b33/href">https://medium.com/media/ee2cbe0c2efa47de7bbdb7651f3f5b33/href</a></iframe><p>Let’s go an extra mile and implement a method that checks if there is a path between two <strong>vertices.</strong></p><h3>Does path exist method</h3><p>The reason it is easy to implement this method is that it is almost identical to <strong>BFS </strong>method. You can use DFS to look for a path but it will not be optimal. For more information on this topic watch <a href="https://www.youtube.com/watch?v=zaBhtODEL0w">Gayle Laakmann McDowell, the author of Cracking The Coding Interview book.</a> Since you already know what <strong>BFS</strong> is and how it works, I will leave the code here for you to analyze.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b4fa4f4fb5c57203024663ce947677b6/href">https://medium.com/media/b4fa4f4fb5c57203024663ce947677b6/href</a></iframe><h3>And here is a playground for you to play and test this code.</h3><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Frepl.it%2F%40ziyoshams%2FGraph-JS%3Flite%3Dtrue&amp;url=https%3A%2F%2Frepl.it%2F%40ziyoshams%2FGraph-JS%3Flite%3Dtrue&amp;image=https%3A%2F%2Frepl.it%2Fpublic%2Fimages%2Freplit-logo-800x600.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=repl" width="800" height="600" frameborder="0" scrolling="no"><a href="https://medium.com/media/f5d46f7f3a10d5cf4183b7d5f5f49f0a/href">https://medium.com/media/f5d46f7f3a10d5cf4183b7d5f5f49f0a/href</a></iframe><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cc0ed170b156" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Deep copying Javascript Arrays]]></title>
            <link>https://medium.com/@ziyoshams/deep-copying-javascript-arrays-4d5fc45a6e3e?source=rss-394aa3bad17c------2</link>
            <guid isPermaLink="false">https://medium.com/p/4d5fc45a6e3e</guid>
            <category><![CDATA[shallow-copy]]></category>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[deep-clone]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[deep-copy-array]]></category>
            <dc:creator><![CDATA[Ziyo Shams]]></dc:creator>
            <pubDate>Tue, 26 Jun 2018 04:10:00 GMT</pubDate>
            <atom:updated>2018-10-16T13:14:43.165Z</atom:updated>
            <content:encoded><![CDATA[<p>Most people know the concept of <em>shallow copy</em>, but they come across <em>deep copy</em> less often. Let’s start by defining what these two terms mean:</p><h3>What is “shallow copy”?</h3><p>Before we talk about <em>shallow copy</em>,<em> </em>let’s quickly talk about <strong>reference </strong>to an object. Let’s use a simple example by declaring a variable that holds values for a one dimensional array.</p><pre>const array1 = [1, 2, 3, 4, 5, 6, 7, 8]</pre><p>And then we try to “copy” it to another variable.</p><pre>const array2 = array1;</pre><p>Guess what? Arrays are <strong>mutable</strong> type in Javascript! That means the value of the array can be changed after it has been declared. In this case array2 is copying the <em>reference</em> of array1. This is <strong>not a shallow copy</strong>, rather it is called copying a <em>reference of an object</em>. In short, both variables are pointing to the same memory address. It would look like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/610/1*EqkczskfPhAaPgPweDjf_Q.png" /></figure><p>Whenever you <strong>modify</strong> one of these arrays, you will be <strong>modifying both arrays</strong>. There are a few cases where you might want to do that, but in most cases you are advised to avoid mutating original values.</p><p><strong>Shallow copy</strong> stands in between <em>copy by reference</em> and <em>deep copy</em>. According to <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/slice">MDN</a> Array.prototype.slice() returns a shallow copy of the selected portion of the array. A quick example:</p><pre>const array1 = [1, 2, 3, [4, 5], 6];<br>const array2 = array1.slice(); // array2 = [1, 2, 3, [4, 5], 6];</pre><p>At first it looks like we <em>deep copied</em> an array, except we didn’t. This is an example of a <strong>shallow copy.</strong> Indeed we copied 1, 2, 3, 6 to array2, but we copied a <strong>reference</strong> of [4, 5] . If we were to change one of the values in array1[0] = &#39;a&#39;; our array2 values will stay the same. If we change a value in array1[3][0] = &#39;x&#39; our array2 will be modified. Another example:</p><pre>const array1 = [[1, &#39;a&#39;], 2, 3, 4, 5];<br>const array2 = array1.slice();</pre><pre>console.log(array1); // [[ 1, &#39;a&#39; ], 2, 3, 4, 5]<br>console.log(array2); // [[ 1, &#39;a&#39; ], 2, 3, 4, 5]</pre><pre>array1[0][1] = &#39;b&#39;; // changing array1 values only<br>array1[2] = 100</pre><pre>console.log(array1); // [[ 1, &#39;b&#39; ], 2, 100, 4, 5]<br>console.log(array2); // [[ 1, &#39;b&#39; ], 2, 3, 4, 5] <br>// array2 has been modified</pre><p>How do we go about this? Of course <strong>deep copying an array</strong>.</p><h3>What is “deep copy”?</h3><p>Short answer — it is the opposite of <strong>shallow copy</strong>. Deep copy means that variables don’t share the same memory address, and we don’t copy anything by reference. A variable would have a copy of the original array in a different memory location.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/610/1*mxnKUZu79Z_-n5ty1IjX1w.png" /></figure><p>Let’s see some examples of how we<em> deep copy </em>an array. There are many ways to approach this depending how complex the array is. To start with, let’s use the same example (one dimensional array):</p><pre>const array1 = [1, 2, 3, 4, 5, 6, 7, 8]</pre><p><strong>Approach #1</strong></p><pre>// Use built-in array methods<br>const array2 = array1.map(elem =&gt; elem);</pre><p><strong>Approach #2</strong></p><pre>// Use Spread operator<br>const array2 = [...array1];</pre><p><strong>Approach #3</strong></p><pre>const array2 = [];</pre><pre>array1.forEach(elem =&gt; {<br>    array2.push(elem)<br>});</pre><p>All of above mentioned methods are fine <strong><em>if and only if</em></strong><em> </em>your array is<strong> one dimensional</strong> or it<strong> does not </strong>contain<strong> </strong>any other<strong> mutable type(<em>object</em>).</strong> In case an array contains another array as one of its elements const array1 = [1, 2, 3, [&#39;a&#39;, &#39;b&#39;, &#39;c&#39;, &#39;d&#39;], 5, 6, 7, 8], none of the above mentioned methods would work. The issue is how Array structure is implemented in Javascript.</p><p>This is what happens when you try to deep copy using one of the above mentioned methods. <em>This illustration may not be 100% accurate, but it will give you a rough idea how array structure is implemented.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/610/1*2cpUv_sTlVyGw-rCUwyZOg.png" /></figure><p>In order to copy elements properly, we have to go and copy each element individually. One of many solutions to <em>deep copying </em>a<em> </em>multidimensional array is iterating through the array recursively. Here is a quick example of a multidimensional array and recursive solution:</p><pre>// set up a function that iterates through a given array<br>// if one of the elements is an array, call itself with that element<br>// (Edited)<br>// if elements of the array is an object, we make sure to take care of that too.</pre><pre>const deepCopy = (<em>arr</em>) =&gt; {<br>  let copy = [];<br>  arr.forEach(<em>elem</em> =&gt; {<br>    if(Array.isArray(elem)){<br>      copy.push(deepCopy(elem))<br>    }else{<br>      if (typeof elem === &#39;object&#39;) {<br>        copy.push(deepCopyObject(elem))<br>    } else {<br>        copy.push(elem)<br>      }<br>    }<br>  })<br>  return copy;<br>}</pre><pre>// Helper function to deal with Objects<br>const deepCopyObject = (obj) =&gt; {<br>  let tempObj = {};<br>  for (let [key, value] of Object.entries(obj)) {<br>    if (Array.isArray(value)) {<br>      tempObj[key] = deepCopy(value);<br>    } else {<br>      if (typeof value === &#39;object&#39;) {<br>        tempObj[key] = deepCopyObject(value);<br>      } else {<br>        tempObj[key] = value<br>      }<br>    }<br>  }<br>  return tempObj;<br>}</pre><pre>const array1 = [<br>  1, <br>  2, <br>  [6, 7, 8], <br>  &#39;foo&#39;, <br>  [&#39;bar&#39;, [9, 10], 11], <br>  12, <br>  13<br>];</pre><pre>const array2 = deepCopy(array1); <br>// now array2 has a separate copy of array1</pre><p>That was it! Hope this was informative. Here is an example that you can play with. Examine the code, look at the console and you should be able to form a deeper understanding of shallow and deep copy. 👇👇👇👇👇</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fcodepen.io%2Fziyoshams%2Fembed%2Fpreview%2FgKjpON%3Fheight%3D600%26slug-hash%3DgKjpON%26default-tabs%3Djs%2Cresult%26host%3Dhttps%3A%2F%2Fcodepen.io%26embed-version%3D2&amp;url=https%3A%2F%2Fcodepen.io%2Fziyoshams%2Fpen%2FgKjpON%3Feditors%3D0010&amp;image=https%3A%2F%2Fs3-us-west-2.amazonaws.com%2Fm.cdpn.io%2Fscreenshot-coming-soon-small.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=codepen" width="800" height="600" frameborder="0" scrolling="no"><a href="https://medium.com/media/f9c7df4212ce9e96ef6b4c6d72fe15d5/href">https://medium.com/media/f9c7df4212ce9e96ef6b4c6d72fe15d5/href</a></iframe><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4d5fc45a6e3e" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>