<?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 Ahsan Shibghotullah on Medium]]></title>
        <description><![CDATA[Stories by Ahsan Shibghotullah on Medium]]></description>
        <link>https://medium.com/@ahsanshibghotullah?source=rss-b8cd93b7d406------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*bAm9ILmN3DmvJjdwfwXYAw.jpeg</url>
            <title>Stories by Ahsan Shibghotullah on Medium</title>
            <link>https://medium.com/@ahsanshibghotullah?source=rss-b8cd93b7d406------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 04 Dec 2026 22:30:25 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@ahsanshibghotullah/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[Building a Hierarchical Tree View with Dynamic SVG Lines in React]]></title>
            <link>https://medium.com/@ahsanshibghotullah/building-a-hierarchical-tree-view-with-dynamic-svg-lines-in-react-fba03aad5e48?source=rss-b8cd93b7d406------2</link>
            <guid isPermaLink="false">https://medium.com/p/fba03aad5e48</guid>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[vitejs]]></category>
            <category><![CDATA[ui]]></category>
            <dc:creator><![CDATA[Ahsan Shibghotullah]]></dc:creator>
            <pubDate>Sat, 11 Oct 2025 09:28:06 GMT</pubDate>
            <atom:updated>2025-10-11T09:29:10.137Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/902/1*Ben5B3pX2GExltToDe7b5g.png" /></figure><p>Hi, long time not write something. But I will try to post something as I have a lot of thing that I want to share, including this one!</p><p>Some times ago I write a code to build a Tree View like in React, it’s not difficult but it’s tricky. I am using SVG as a lines because that the simplest way, you can replace it with Image if you want. The tricky part mostly is the logic. And by the way even though I said I will write it in React, you can implement it in whatever JavaScript framework you like.</p><h3>Prerequisites</h3><p>Before diving in, you should be comfortable with:</p><ul><li><strong>React fundamentals</strong>: Creating functional components with JSX</li><li><strong>TypeScript basics</strong>: Interfaces and type annotations</li><li><strong>React Hooks</strong>: Using useState for managing component state</li><li><strong>Recursive rendering</strong>: Understanding how components can render themselves</li></ul><p>If you can build a simple React component with props and state, you’re ready to follow along!</p><h3>Installation</h3><p>We build it from scratch if you want to just grab the code here is the Github <a href="https://github.com/albarkahdev/tree-view-react/tree/main">link</a>.</p><p>Ok, first we need to create our react app. I am using Vite because it’s simple and very easy to use and it capable with other framework not just React.</p><ol><li>Install Vite build tools</li></ol><pre>npm create vite@latest my-app</pre><p>2. You will get some option for framework, you can choose React.</p><p>3. And then there option for variant, you can choose Typescript.</p><p>4. And Voila you just created your Vite App</p><h3>Build the component</h3><p>We will make three component, <em>App.tsx</em>, <em>RootLine.tsx</em>, and <em>Section.tsx</em>.</p><p><em>App.tsx</em> , this component is our main entrypoint. It’s the parent of the other two.</p><pre>import { SectionListComponent, type Section } from &#39;./SectionList&#39;;<br>import &#39;./App.css&#39;<br><br>const App: React.FC = () =&gt; {<br>  return (<br>    &lt;div className=&quot;app-container&quot;&gt;<br>      &lt;div className=&quot;tree-view-container&quot;&gt;<br>        &lt;h1 className=&quot;tree-title&quot;&gt;Document Tree View&lt;/h1&gt;<br>        &lt;div className=&quot;tree-content&quot;&gt;<br>          &lt;SectionListComponent<br>            order={1}<br>            sectionList={sampleData}<br>          /&gt;<br>        &lt;/div&gt;<br>      &lt;/div&gt;<br>    &lt;/div&gt;<br>  );<br>};<br><br>export default App</pre><p>The main component will have simple layout where it import SectionListComponent from the same directory, notice we have sampeData. Here is the content:</p><pre>const sampleData: Section[] = [<br>  {<br>    section_id: &#39;1&#39;,<br>    section_name: &#39;1. Sample&#39;,<br>    sub_section: [<br>      {<br>        section_id: &#39;1.1&#39;,<br>        section_name: &#39;1.1 Web App Project: Sample&#39;,<br>        sub_section: [<br>          {<br>            section_id: &#39;1.1.1&#39;,<br>            section_name: &#39;1.1.1 Sample&#39;,<br>            sub_section: [<br>              {<br>                section_id: &#39;1.1.1.1&#39;,<br>                section_name: &#39;1.1.1.1 Sample&#39;,<br>                sub_section: [<br>                  {<br>                    section_id: &#39;1.1.1.1.1&#39;,<br>                    section_name: &#39;1.1.1.1.1 Sample&#39;,<br>                    sub_section: [<br>                      {<br>                        section_id: &#39;1.1.1.1.1.1&#39;,<br>                        section_name: &#39;Sample&#39;,<br>                      }<br>                    ]<br>                  },<br>                  {<br>                    section_id: &#39;1.1.1.1.2&#39;,<br>                    section_name: &#39;1.1.1.1.2 Sample&#39;,<br>                  },<br>                  {<br>                    section_id: &#39;1.1.1.1.3&#39;,<br>                    section_name: &#39;1.1.1.1.3 Sample&#39;<br>                  }<br>                ]<br>              }<br>            ]<br>          }<br>        ]<br>      },<br><br>      {<br>        section_id: &#39;1.2&#39;,<br>        section_name: &#39;1.2 Mobile App Project:  Sample&#39;,<br>      }<br>    ]<br>  }<br>];</pre><p>The structure will be like that where each section can have sub_section and so on.</p><p>Now for the <em>RootLine.tsx</em>, this will be our line component it’s just simple svg path, where we have vertical line and curved line with total width of 20. We also have props, isShowVerticalLine to show the vertical line, isShowCurvedLine to show the curved line, and then order this is for determine the position of the line. I will explain it later.</p><pre>interface RootLineProps {<br>  isShowVerticalLine: boolean;<br>  isShowCurvedLine: boolean;<br>  order: number;<br>}<br><br>export const RootLine: React.FC&lt;RootLineProps&gt; = ({<br>  isShowVerticalLine,<br>  isShowCurvedLine,<br>  order,<br>}) =&gt; {<br>  return (<br>    &lt;div <br>      className=&quot;root-line-container&quot; <br>      style={{ left: `${order * 24}px` }}<br>    &gt;<br>      &lt;svg <br>        className=&quot;root-line-svg&quot; <br>        style={{ <br>          width: &#39;20px&#39;, <br>          height: &#39;100%&#39;,<br>          left: &#39;0&#39;,<br>          top: &#39;0&#39;<br>        }}<br>      &gt;<br>        {isShowVerticalLine &amp;&amp; (<br>          &lt;line <br>            x1=&quot;2&quot; <br>            y1=&quot;0&quot; <br>            x2=&quot;2&quot; <br>            y2=&quot;100%&quot; <br>            stroke=&quot;#CBD5E0&quot; <br>            strokeWidth=&quot;1&quot;<br>          /&gt;<br>        )}<br>        {isShowCurvedLine &amp;&amp; (<br>          &lt;path<br>            d=&quot;M 2 0 L 2 16 Q 2 20, 6 20 L 20 20&quot;<br>            fill=&quot;none&quot;<br>            stroke=&quot;#CBD5E0&quot;<br>            strokeWidth=&quot;1&quot;<br>          /&gt;<br>        )}<br>      &lt;/svg&gt;<br>    &lt;/div&gt;<br>  );<br>};</pre><p>Lastly the most long code, <em>SectionList.tsx</em>. Where we have SectionListComponent and SectionItemComponent in it.</p><pre>import { useState } from &#39;react&#39;;<br>import { RootLine } from &#39;./RootLine&#39;;<br><br><br>export interface Section {<br>  section_id: string;<br>  section_name: string;<br>  sub_section?: Section[];<br>}<br><br>interface SectionItemProps {<br>  order: number;<br>  section: Section;<br>  isLastItem: boolean;<br>  parentLines: boolean[];<br>}<br><br>interface SectionListProps {<br>  order: number;<br>  sectionList: Section[];<br>  parentLines?: boolean[];<br>}<br><br>export const SectionItemComponent: React.FC&lt;SectionItemProps&gt; = ({<br>  order, <br>  section, <br>  isLastItem,<br>  parentLines <br>}) =&gt; {<br>  const [isExpand, setExpand] = useState(true);<br><br>  const isExpandable = section?.sub_section &amp;&amp; section?.sub_section?.length &gt; 0<br><br>  const handleExpand = () =&gt; {<br>    if (isExpandable) {<br>      setExpand(prev =&gt; !prev);<br>    }<br>  };<br><br>  return (<br>    &lt;&gt;<br>      &lt;div className=&quot;tree-item section-item&quot; onClick={handleExpand}&gt;<br>        {parentLines.map((showLine, i) =&gt; (<br>          &lt;RootLine <br>            key={i} <br>            order={i} <br>            isShowVerticalLine={showLine} <br>            isShowCurvedLine={false}<br>          /&gt;<br>        ))}<br><br>        &lt;RootLine <br>          order={order - 1} <br>          isShowVerticalLine={!isLastItem} <br>          isShowCurvedLine={true}<br>        /&gt;<br>        <br>        &lt;div <br>          className=&quot;tree-arrow&quot;<br>          style={{ marginLeft: `${(order * 24) - 4}px` }} <br>        &gt;<br>          {isExpandable &amp;&amp; (<br>            &lt;span className=&quot;arrow-icon&quot;&gt;<br>              {isExpand ? &#39;▼&#39; : &#39;▶&#39;}<br>            &lt;/span&gt;<br>          )}<br>        &lt;/div&gt;<br>        <br>        &lt;div className=&quot;tree-icon&quot;&gt;<br>          &lt;span className=&quot;icon-section&quot;&gt;📄&lt;/span&gt;<br>        &lt;/div&gt;<br>        <br>        &lt;div className=&quot;tree-label&quot;&gt;<br>          &lt;p className=&quot;tree-text&quot;&gt;{section.section_name}&lt;/p&gt;<br>        &lt;/div&gt;<br>      &lt;/div&gt;<br>      <br>      {isExpand &amp;&amp; section?.sub_section &amp;&amp; section?.sub_section?.length &gt; 0 &amp;&amp; (<br>        &lt;SectionListComponent<br>          order={order + 1}<br>          sectionList={section.sub_section}<br>          parentLines={[...parentLines, !isLastItem]}<br>        /&gt;<br>      )}<br>    &lt;/&gt;<br>  );<br>};<br><br>export const SectionListComponent: React.FC&lt;SectionListProps&gt; = ({ <br>  order, <br>  sectionList,<br>  parentLines = [] <br>}) =&gt; {<br>  if (!sectionList || sectionList.length === 0) {<br>    return null;<br>  }<br><br>  return (<br>    &lt;div className=&quot;section-list&quot;&gt;<br>      {sectionList.map((section, index) =&gt; {<br>        const isLastItem = index === sectionList.length - 1;<br>        <br>        return (<br>          &lt;SectionItemComponent<br>            key={section.section_id}<br>            order={order}<br>            section={section}<br>            isLastItem={isLastItem}<br>            parentLines={parentLines}<br>          /&gt;<br>        );<br>      })}<br>    &lt;/div&gt;<br>  );<br>};</pre><h3>Understanding the Tree View Logic</h3><h3>The Core Problem</h3><p>When building a tree view with connecting lines, the challenge is: <strong>How do we know which ancestor levels should continue showing vertical lines?</strong></p><p>Look at this example:</p><pre>├─ Section 1              ← Level 1, has siblings below, shows line<br>│  ├─ Section 1.1         ← Level 2, has siblings below, shows line<br>│  │  ├─ Section 1.1.1    ← Level 3, last item, NO line continues<br>│  │  └─ Section 1.1.2<br>│  └─ Section 1.2         ← Level 2, last item, line stops<br>└─ Section 2              ← Level 1, last item, no siblings below</pre><p>Notice how the vertical line at Level 1 continues through Section 1.1 and 1.1.1, but stops at Section 2 because there are no more siblings.</p><h3>The Solution: The parentLines Array</h3><p>We use a <strong>boolean array</strong> that tracks which ancestor levels should show vertical lines.</p><h3>Example:</h3><pre>parentLines = [true, false, true]</pre><p>This means:</p><ul><li>parentLines[0] = true → Show vertical line at Level 0 (great-grandparent level)</li><li>parentLines[1] = false → DON&#39;T show vertical line at Level 1 (grandparent level)</li><li>parentLines[2] = true → Show vertical line at Level 2 (parent level)</li></ul><h3>How SectionListComponent Works</h3><p>SectionListComponent is the <strong>container</strong> that renders multiple sections at the same level.</p><h3>Its Job:</h3><ol><li><strong>Loop through all sections</strong> at the current level</li><li><strong>Determine if each section is the last item</strong> in the list</li><li><strong>Pass the </strong><strong>parentLines array</strong> to each child</li></ol><h3>The Code:</h3><pre>const SectionListComponent: React.FC&lt;SectionListProps&gt; = ({ <br>  order,           // Current depth level (1, 2, 3...)<br>  sectionList,     // Array of sections to render<br>  parentLines = [] // Which ancestor levels show lines<br>}) =&gt; {<br>  return (<br>    &lt;div&gt;<br>      {sectionList.map((section, index) =&gt; {<br>        // Key decision: Is this the last item?<br>        const isLastItem = index === sectionList.length - 1;<br>        <br>        return (<br>          &lt;SectionItemComponent<br>            key={section.section_id}<br>            order={order}<br>            section={section}<br>            isLastItem={isLastItem}        // ← Critical info!<br>            parentLines={parentLines}       // ← Pass ancestor state<br>          /&gt;<br>        );<br>      })}<br>    &lt;/div&gt;<br>  );<br>};</pre><h3>Key Logic:</h3><ul><li><strong>isLastItem</strong>: If true, this section is the last among its siblings</li><li><strong>parentLines</strong>: Passed unchanged to children (they need to know ancestor state)</li></ul><h3>How SectionItemComponent Works</h3><p>SectionItemComponent renders a <strong>single section</strong> and decides when to show lines.</p><h3>Its Job:</h3><ol><li><strong>Render all ancestor lines</strong> based on parentLines</li><li><strong>Render its own line</strong> (current level)</li><li><strong>Calculate if it has children</strong> to determine line continuation</li><li><strong>Pass updated </strong><strong>parentLines</strong> to its children</li></ol><h3>The Code (Step by Step):</h3><h4>Step 1: Determine if expandable</h4><pre>const [isExpand, setExpand] = useState(true);</pre><pre>// Can this section be expanded?<br>const isExpandable = section?.sub_section &amp;&amp; section?.sub_section?.length &gt; 0</pre><p><strong>Why this matters:</strong> We need to know if the section can expand/collapse.</p><h4>Step 2: Render ancestor lines</h4><pre>{/* Render lines for all ancestor levels */}<br>{parentLines.map((showLine, i) =&gt; (<br>  &lt;RootLine <br>    key={i} <br>    order={i}                        // Position (0, 1, 2...)<br>    isShowVerticalLine={showLine}    // true/false from array<br>    isShowCurvedLine={false}         // Only curved at current level<br>  /&gt;<br>))}</pre><p><strong>What happens here:</strong></p><ul><li>Loop through parentLines array</li><li>For each ancestor level, draw a vertical line if showLine = true</li><li>These are the lines “passing through” from ancestors</li></ul><h4>Step 3: Render current level line (THE CRITICAL LOGIC)</h4><pre>&lt;RootLine <br>  order={order - 1}                    // Current level position<br>  isShowVerticalLine={!isLastItem}     // ← THE KEY LOGIC<br>  isShowCurvedLine={true}              // Show the branch connector<br>/&gt;</pre><p><strong>The Magic Formula:</strong></p><pre>isShowVerticalLine={!isLastItem}</pre><p>This line continues vertically IF:</p><ul><li><strong>!isLastItem</strong>: It&#39;s NOT the last sibling (more siblings below)</li></ul><p><strong>Examples:</strong></p><p>Scenario isLastItem isShowVerticalLine Why? First item false true More siblings below Middle item false true More siblings below Last item true false Nothing below, stop line</p><h4>Step 4: Render children with updated parentLines</h4><pre>{isExpand &amp;&amp; section?.sub_section &amp;&amp; section?.sub_section?.length &gt; 0 &amp;&amp; (<br>  &lt;SectionListComponent<br>    order={order + 1}                    // Go deeper (level 2 → 3)<br>    sectionList={section.sub_section}<br>    parentLines={[...parentLines, !isLastItem]}  // ← UPDATE THE ARRAY<br>  /&gt;<br>)}</pre><p><strong>The Array Update:</strong></p><pre>parentLines={[...parentLines, !isLastItem]}</pre><p>This means:</p><ul><li><strong>Spread</strong> the existing ancestor states: ...parentLines</li><li><strong>Append</strong> the current level’s state: !isLastItem</li><li>Children will know: “at my parent’s level, show line if parent wasn’t last”</li></ul><p><strong>Example Flow:</strong></p><pre>Level 1: parentLines = []<br>  ↓ Has more siblings below<br>  <br>Level 2: parentLines = [true]  // &quot;Show line at level 1&quot;<br>  ↓ Is last sibling<br>  <br>Level 3: parentLines = [true, false]  // &quot;Show at L1, stop at L2&quot;<br>  ↓ Has more siblings below<br>  <br>Level 4: parentLines = [true, false, true]  // &quot;Show at L1, stop at L2, show at L3&quot;</pre><h3>Visual Example</h3><p>Let’s trace through this structure:</p><pre>Section A (order=1, parentLines=[])<br>├─ Section A.1 (order=2, parentLines=[true])<br>│  ├─ Section A.1.1 (order=3, parentLines=[true, true])<br>│  └─ Section A.1.2 (order=3, parentLines=[true, false])<br>└─ Section A.2 (order=2, parentLines=[false])</pre><h3>Breakdown:</h3><p><strong>1. Section A</strong>:</p><ul><li>parentLines = [] (no ancestors)</li><li>Not last item → passes [true] to children</li><li>Line continues down</li></ul><p><strong>2. Section A.1</strong>:</p><ul><li>parentLines = [true] (line at level 1)</li><li>Not last item → passes [true, true] to children</li><li>Shows line at level 1 (from parent) + its own line</li></ul><p><strong>3. Section A.1.1</strong>:</p><ul><li>parentLines = [true, true] (lines at levels 1 &amp; 2)</li><li>Not last item → passes [true, true, true] to children</li><li>Shows all ancestor lines + its own</li></ul><p><strong>4. Section A.1.2</strong>:</p><ul><li>parentLines = [true, false] (line at level 1 only)</li><li>Last item → passes [true, false, false] to children</li><li>Line at level 2 stops here</li></ul><p><strong>5. Section A.2</strong>:</p><ul><li>parentLines = [false] (no line at level 1)</li><li>Last item → no line continues</li><li>Clean termination</li></ul><h3>Summary</h3><h3>SectionListComponent:</h3><ul><li><strong>Renders a list</strong> of sections</li><li><strong>Identifies last items</strong>: isLastItem = index === length - 1</li><li><strong>Passes state down</strong>: Gives children the parentLines array</li></ul><h3>SectionItemComponent:</h3><ul><li><strong>Renders one section</strong></li><li><strong>Draws ancestor lines</strong>: Loop through parentLines array</li><li><strong>Draws its own line</strong>: Uses formula !isLastItem</li><li><strong>Updates state for children</strong>: Appends !isLastItem to the array</li></ul><h3>The Key Formula:</h3><pre>// When to show vertical line at current level:<br>isShowVerticalLine = !isLastItem</pre><pre>// What to pass to children:<br>newParentLines = [...parentLines, !isLastItem]</pre><p>This elegant recursive pattern ensures every line appears exactly where it should, connecting parents to children while respecting the “last item” rule at every level.</p><p>Ok, that’s all from me. Thank you for reading all the way through here, hopefully it’s can help you to build your UI.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fba03aad5e48" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Easly handle realtime localstorage with React Hooks]]></title>
            <link>https://medium.com/@ahsanshibghotullah/easly-handle-realtime-localstorage-with-react-hooks-dbe24ac90e4?source=rss-b8cd93b7d406------2</link>
            <guid isPermaLink="false">https://medium.com/p/dbe24ac90e4</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[localstorage]]></category>
            <category><![CDATA[state-management]]></category>
            <category><![CDATA[realtime]]></category>
            <category><![CDATA[react]]></category>
            <dc:creator><![CDATA[Ahsan Shibghotullah]]></dc:creator>
            <pubDate>Sat, 29 Oct 2022 04:01:08 GMT</pubDate>
            <atom:updated>2022-10-29T04:25:11.693Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*otr8UxGABJ5zBzC6uAheag.jpeg" /><figcaption>Image by bublikhaus on Freepik</figcaption></figure><p>In the actual application, we tend to use a lot of data for displaying statistics or calculating something, or to keep tracking some changes. The data that we use we store somewhere in our application. In React application we can use something like <a href="https://beta.reactjs.org/apis/react/useState">useState</a> or <a href="https://beta.reactjs.org/apis/react/useReducer">useReducer</a>.</p><p>Suppose we have data to calculate the current order, which we can change many times by adding or subtracting it. We usually use useState.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aPbBNRtSi0uQNOREOT5pNA.png" /></figure><p>We set the first order to 1, and we display the current order.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/824/1*tESyP8nS8lDi-oUNz92T7Q.png" /></figure><p>We create a button for adding the order by 1 each time.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1012/1*KcTthtrG6MuCV1VRepwgYQ.png" /></figure><p>Now let’s test our apps.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-QGu6wNlMlrXPMz284Cj2g.gif" /></figure><p>Now our apps are working like we want them to, but there is a big problem. Every time we refresh our page the order is back to 1, if want to keep track of the order this can be fatal for the customers. What’s happening here? the thing is every time we refresh our page React apps will be rerendered and every state is back to its initial state, for example, currentOrder initial state is 1, so no matter how much we add if we refresh the page currentOrder value will be back to 1.</p><p>One of the solutions for that problem is we must persist in our state, we can use localstorage to do that. Let’s change our useState with localstorage.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cvA7oUSU7HJAaeGi78BZgw.gif" /></figure><p>Even though our state value is persistent when we refresh the page, the value does not immediately change after we add the order. Why? because value localstorage is not real-time. We must getItem for currentOrder every time we updated it.</p><p>There is a library called use-local-storage to solve this problem, let’s try it.</p><p>First, add the library to our apps with this command</p><p>Install with npm</p><pre>npm i use-local-storage</pre><p>Install with yarn</p><pre>yarn add use-local-storage</pre><p>Its usage is very similar to useState</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vJf3gioI5yV8ttmGpSyJCg.gif" /></figure><p>That’s all from me thank you.</p><p>See my work on <a href="https://github.com/albarkahdev">GitHub</a> or <a href="https://www.albarkahdev.com/">my web</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=dbe24ac90e4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Data Struktur dan Algoritma pada JavaScript (Stack) Part 1]]></title>
            <link>https://medium.com/@ahsanshibghotullah/data-struktur-dan-algoritma-pada-javascript-stack-part-1-3e2e244eac86?source=rss-b8cd93b7d406------2</link>
            <guid isPermaLink="false">https://medium.com/p/3e2e244eac86</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[indonesia]]></category>
            <category><![CDATA[data-structures]]></category>
            <dc:creator><![CDATA[Ahsan Shibghotullah]]></dc:creator>
            <pubDate>Sat, 13 Apr 2019 15:38:14 GMT</pubDate>
            <atom:updated>2019-04-13T15:38:14.785Z</atom:updated>
            <content:encoded><![CDATA[<p>Stack Data Structure.</p><p><em>Disclaimer: ini merupakan rangkuman dari </em><a href="https://www.youtube.com/watch?v=t2CEgPsws3U&amp;t=41s"><em>video youtube freeCodeCamp.org</em></a><em> , tulisan ini bertujuan untuk berbagi.</em></p><p>Anda bisa membayangkan struktur <em>Stack</em> ini sebagai suatu tumpukan buku. Di tumpukan buku paling atas adalah buku yang anda letakkan terakhir. Jika anda mengambil buku tersebut maka akan terlihat buku yang terakhir sebelumnya. Jadi buku terakhir yang anda letakan di tumpukan buku adalah buku pertama yang anda ambil dari tumpukan buku tersebut.</p><p>Dari contoh ini kita bisa membayangkan satu buah fungsi sederhana yaitu mengambil sebuah buku paling atas dari suatu tumpukan buku. Pada struktur Stack ini terdapat fungsi-fungsi lainnya juga, seperti fungsi menambah tumpukan buku, mengetahui jumlah tumpukan buku, dan juga melihat urutan terkahir dari tumpukan buku.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*JuZBs1a-RMu9dHfm" /><figcaption>Photo by <a href="https://unsplash.com/@morganharpernichols?utm_source=medium&amp;utm_medium=referral">Morgan Harper Nichols</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Contoh lainnya adalah tombol kembali pada Browser anda, saat anda mengakses halaman Facebook kemudian berpindah ke halaman Twitter maka anda membuat tumpukan dimana tumpukan paling atas adalah halaman Twitter karena Twitter adalah halaman terakhir yang anda kunjungi. Ketika anda menekan tombol kembali maka anda akan kembali ke halaman sebelumnya yaitu halaman Facebook. Karena halaman Facebook adalah halaman sebelum terakhir yang anda kunjungi.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/856/0*HEDDLwi8o1vusQJN" /></figure><p>Beberapa fungsi yang terdapat di dalam Stack adalah:</p><ul><li>Push: Untuk menambah data ke dalam Stack.</li><li>Pop: Untuk membuang elemen paling terakhir dari Stack.</li><li>Peek: Untuk menampilkan elemen terakhir dari Stack.</li><li>Length/Size: Untuk menentukan berapa banyak elemen yang terdapat dari suatu Stack.</li></ul><p>Salah satu fitur JavaScript yaitu objek array, objek array telah memiliki semua fungsi yang kita butuhkan untuk menggunakan Stack. Maka kamu bisa saja menggunakan sebuah array sebagai Stack.</p><p>Saya akan menunjukan bagaimana menggunakan fungsi-fungsi tersebut menggunakan array dan saya akan membuat sebuah kelas Stack dan bagaimana dia bekerja.</p><ol><li>Menentukan apakah suatu kata itu palindrom atau bukan.</li></ol><blockquote><a href="https://id.wikipedia.org/wiki/Palindrom"><strong>Palindrom</strong> adalah sebuah kata, frasa, angka maupun susunan lainnya yang dapat dibaca dengan sama baik dari depan maupun belakang (spasi antara huruf-huruf biasanya diperbolehkan).</a></blockquote><pre>var letter = [] // ini Stack kita</pre><pre>var word = &quot;sugus&quot;;</pre><pre>var rword = &quot;&quot;;</pre><p>Pertama-tama kita mendeklarasikan sebuah variabel letter yang menjadi Stack kita, lalu kita deklarasikan variabel word yang berisi kata palindrom, dan terakhir kita deklarasikan variable rword yang berisi string kosong untuk kita meletakkan kata terbalik.</p><p>Nantinya kita akan menggunakan Stack untuk mengisi variable rword dengan kebalikan kata dari variabel word.</p><pre>for (var i = 0; i &lt; word.length; i++) {<br>   letter.push(word[i]);<br>}</pre><p>Kita masukkan setiap huruf dari variabel word ke dalam Stack kita menggunakan <em>loop. </em>Dimulai dari index 0 hingga sebelum total huruf variabel word. Index di dalam string hanya untuk menentukan karakter mana yang kita lihat.</p><p>Di dalam fungsi <em>loop</em> tersebut kita menggunakan letter yaitu Stack kita, lalu kita menggunakan fungsi push untuk menambahkan data kedalam letter. Data yang kita tambahkan berupa word[i] yaitu huruf dengan index tertentu, contohnya word index 0 adalah huruf s, word index 1 adalah huruf u, dan seterunya.</p><pre>for (var i = 0; i &lt; word.length; i++) {<br>   rword += letter.pop();<br>}</pre><p>Sekarang kita menggunakan <em>loop</em> kembali untuk membalikan kata dari variabel word. Kita menggunakan variabel rword untuk menambahkan dengan hasil sebelumnya (<em>increment</em>) dari Stack dengan menggunakan fungsi <em>pop</em> huruf terakhir. Karena mereka di letakkan berurutan maka merekan akan di <em>pop</em> dengan urutan yang terbalik (dari akhir ke awal).</p><p>Maka sekarang variabel rword sudah terisi dengan kata balikan dari variabel word.</p><pre>if (word === rword) {<br>   console.log(word + &quot; adalah sebuah palindrom.&quot;);<br>}<br>else {<br>   console.log(word + &quot; bukan sebuah palindrom.&quot;);<br>}</pre><p>Kita print hasil dari fungsi kita dengan <a href="https://www.w3schools.com/js/js_output.asp">console.log</a> . Dengan cara klik kanan di halaman file code anda lalu pilih Inspect.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/514/1*uboNCy6Mmce4NrXpbtA72A.png" /></figure><p>Mungkin itu saja sedikit penjelasan tentang salah satu struktur data JavaScript, kurang lebihnya mohon maaf. Dan mohon untuk dikoreksi jika ada yang salah. Insyaa Allah saya akan lanjutkan pada part berikutkannya. Terimakasih. Assalamualaikum.</p><blockquote>Anda bisa mengambil kode di <a href="https://github.com/albarkahdev/datastructurejs">github saya.</a></blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3e2e244eac86" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>