<?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 Sambit Dash on Medium]]></title>
        <description><![CDATA[Stories by Sambit Dash on Medium]]></description>
        <link>https://medium.com/@sambitdash129?source=rss-8c0d53d5034b------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*RWyNqTzxNQWX4ECp</url>
            <title>Stories by Sambit Dash on Medium</title>
            <link>https://medium.com/@sambitdash129?source=rss-8c0d53d5034b------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Thu, 03 Dec 2026 16:34:52 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@sambitdash129/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[LLD Interview Question: Design a Nested Checkbox Tree with Checked, Unchecked, and Indeterminate…]]></title>
            <link>https://medium.com/@sambitdash129/lld-interview-question-design-a-nested-checkbox-tree-with-checked-unchecked-and-indeterminate-f83891fd9a9b?source=rss-8c0d53d5034b------2</link>
            <guid isPermaLink="false">https://medium.com/p/f83891fd9a9b</guid>
            <dc:creator><![CDATA[Sambit Dash]]></dc:creator>
            <pubDate>Tue, 07 Oct 2025 05:34:48 GMT</pubDate>
            <atom:updated>2025-10-07T06:03:17.648Z</atom:updated>
            <content:encoded><![CDATA[<h3>LLD Interview Question: Design a Nested Checkbox Tree with Checked, Unchecked, and Indeterminate States</h3><p>Recently I was asked to build a nested checkbox component UI similar to category selectors seen in admin dashboards in an interview. The UI must handle checked, unchecked, and indeterminate states at any nesting level.</p><h3>Nested Checkboxes?</h3><p>If there’s an UI where users can select entire categories (“Fruits”) or drill down to individual items (“Mango”). The business expectation is simple:</p><ul><li>If all children are selected, then parent’s checkbox is checked.</li><li>If some (but not all) children are selected, then parent is indeterminate.</li><li>If no children are selected, then parent is unchecked.</li></ul><p><strong>Challenge</strong>: state updates that cascade both down (parent to children) and up (child to parent), updating checked and indeterminate correctly across the tree.</p><h3>Data Structure</h3><p>The core of any UI is the data. Let’s define the data model :</p><pre>const nodes = [<br>  {<br>    label: &quot;Fruits&quot;,<br>    children: [<br>      { label: &quot;Mango&quot;, children: [] },<br>      { label: &quot;Apple&quot;, children: [] },<br>      { label: &quot;Pears&quot;, children: [] },<br>    ],<br>  },<br>  // ...other nodes<br>];</pre><p>Building on that, we add extra properties for UI state:</p><pre>const initData = (data) =&gt; {<br>  return data.map((node) =&gt; ({<br>    ...node,<br>    checked: false,<br>    indeterminate: false,<br>    children: initData(node.children || []),<br>  }));<br>};</pre><p>This function ensures every node knows if it’s checked, indeterminate, or neither, and initializes deeply nested trees.</p><h3>The Tree Component</h3><p>At the top level, maintain our checkbox tree’s state:</p><pre>export default function CheckBoxes() {<br>  const [tree, setTree] = useState(initData(nodes));<br>  const updateNode = (updatedNode, index) =&gt; {<br>    const nodes = [...tree];<br>    nodes[index] = updatedNode;<br>    setTree(nodes);<br>  };<br>  return (<br>    &lt;div&gt;<br>      {tree.map((node, index) =&gt; (<br>        &lt;TreeNode<br>          node={node}<br>          updateNode={(updatedNode) =&gt; updateNode(updatedNode, index)}<br>        /&gt;<br>      ))}<br>    &lt;/div&gt;<br>  );<br>}</pre><p>Each root node gets a handler to update itself in the global array.</p><h3>Syncing State Between Parents and Children</h3><p>The tricky part is state propagation. When a parent’s checkbox changes, so must all of its children. When any child updates, its parent must potentially become checked, unchecked, or indeterminate.</p><p><strong>Top-Down</strong>: When toggling a parent, update all descendants recursively.</p><pre>const setChildren = (node, checked) =&gt; ({<br>  ...node,<br>  checked,<br>  indeterminate: false,<br>  children: node.children.map((child) =&gt; setChildren(child, checked)),<br>});</pre><p><strong>Bottom-Up</strong>: When a child updates, re-calculate up the tree for parent state.</p><pre>const computeStateFromChildren = (node) =&gt; {<br>  if (!node.children.length) return node;<br>  const children = node.children.map(computeStateFromChildren);<br>  const allChecked = children.every((child) =&gt; child.checked);<br>  const someChecked = children.some((child) =&gt; child.checked);<br><br>  return {<br>    ...node,<br>    checked: allChecked,<br>    indeterminate: someChecked &amp;&amp; !allChecked,<br>    children,<br>  };<br>};</pre><h3>The TreeNode Component</h3><p>Each node (parent or child) needs a controlled checkbox and custom logic for state syncing:</p><pre>const TreeNode = ({ node, updateNode }) =&gt; {<br>  const checkBoxRef = useRef();<br><br><br>  useEffect(() =&gt; {<br>    if (checkBoxRef.current) {<br>      checkBoxRef.current.indeterminate = node.indeterminate;<br>    }<br>  }, [node.indeterminate]);<br><br><br>  const handleChange = (e) =&gt; {<br>    const updatedNode = setChildren(node, e.target.checked);<br>    updateNode(updatedNode);<br>  };<br><br>  const handleChildNodeUpdate = (updatedChild, index) =&gt; {<br>    const children = [...node.children];<br>    children[index] = updatedChild;<br>    const nodeData = computeStateFromChildren({ ...node, children });<br>    updateNode(nodeData);<br>  };<br><br>  return (<br>    &lt;ul&gt;<br>      &lt;label&gt;<br>        &lt;input<br>          type=&quot;checkbox&quot;<br>          ref={checkBoxRef}<br>          checked={node.checked}<br>          onChange={handleChange}<br>        /&gt;<br>        {node.label}<br>      &lt;/label&gt;<br>      {node.children.length &gt; 0 &amp;&amp;<br>        node.children.map((childNode, index) =&gt; (<br>          &lt;TreeNode<br>            key={childNode.label}<br>            node={childNode}<br>            updateNode={(updatedChild) =&gt; handleChildNodeUpdate(updatedChild, index)}<br>          /&gt;<br>        ))}<br>    &lt;/ul&gt;<br>  );<br>};</pre><h3>Handling the Indeterminate State in React</h3><p>Checkboxes in HTML support an “indeterminate” visual, but it’s only available via the DOM, not as a regular prop. That’s why we needref.</p><pre>useEffect(() =&gt; {<br>  if (checkBoxRef.current) {<br>    checkBoxRef.current.indeterminate = node.indeterminate;<br>  }<br>}, [node.indeterminate]);</pre><h3>Notes:</h3><ul><li>We should always give a key to recursive children based on something unique.</li><li>Don’t mutating node data in-place — React’s state diffing relies on immutability.</li><li>Start the code by getting checked/unchecked sync working before layering indeterminate logic.</li></ul><h3>Wrapping Up</h3><p>With this structure, adding new nodes or hierarchies is a matter of updating the data, not rewriting logic. The separation of descending (setChildren), ascending (computeStateFromChildren), and local state (TreeNode) patterns keeps logic clean even as trees grow.</p><p>Building trees with checked, unchecked, and indeterminate states is a classic UI exercise in recursion and immutable data patterns. Master this, and advanced filter UIs or category selectors in React become a very easy.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f83891fd9a9b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Designing a VS Code-like Folder Structure in React (Low-Level Design Interview Question)]]></title>
            <link>https://medium.com/@sambitdash129/designing-a-vs-code-like-folder-structure-in-react-low-level-design-interview-question-3a6fc257efe8?source=rss-8c0d53d5034b------2</link>
            <guid isPermaLink="false">https://medium.com/p/3a6fc257efe8</guid>
            <dc:creator><![CDATA[Sambit Dash]]></dc:creator>
            <pubDate>Wed, 24 Sep 2025 16:37:15 GMT</pubDate>
            <atom:updated>2025-09-26T10:02:04.883Z</atom:updated>
            <content:encoded><![CDATA[<p>One of the most interesting front-end interview questions I faced recently was:</p><p><em>“How would you design a VS Code–like folder and file explorer in React?”</em></p><p>At first glance, it feels like a UI challenge, but once you deep dive into it, it touches on data modelling, component structure, recursion, and state management — all the important aspects that interviewers would like to test.</p><p>In this post, I’ll walk through my thought process on approaching this problem in a low-level design (LLD) style, breaking it down step by step.</p><h3>First try to Understand the Problem:</h3><p>We need to replicate a file explorer-like tree where:</p><ul><li>Folders can expand or collapse.</li><li>Files sit inside folders.</li><li>Nested folders can go as deep as needed.</li><li>The structure should be dynamic, based on data.</li></ul><p>This maps perfectly to a recursive tree structure, which means our data should itself be recursive</p><h3>Data Model</h3><p>Before working on the React components, let’s model the data structure. A folder can contain either files or more folders. That naturally suggests a structure like this:</p><pre>const fileExplorerData = {<br>  name: &quot;root&quot;,<br>  type: &quot;folder&quot;,<br>  children: [<br>    {<br>      name: &quot;src&quot;,<br>      type: &quot;folder&quot;,<br>      children: [<br>        { name: &quot;App.js&quot;, type: &quot;file&quot; },<br>        { name: &quot;index.js&quot;, type: &quot;file&quot; },<br>        {<br>          name: &quot;components&quot;,<br>          type: &quot;folder&quot;,<br>          children: [<br>            { name: &quot;App.js&quot;, type: &quot;file&quot; },<br>            { name: &quot;Header.js&quot;, type: &quot;file&quot; },<br>            { name: &quot;Menu.js&quot;, type: &quot;file&quot; },<br>            { name: &quot;Footer.js&quot;, type: &quot;file&quot; },<br>            { name: &quot;Home.js&quot;, type: &quot;file&quot; }<br>          ]<br>        }<br>      ]<br>    },<br>    { name: &quot;package.json&quot;, type: &quot;file&quot; }<br>  ]<br>};</pre><p>A few design decisions I made here:</p><ul><li>Each node has a type, either file or folder (We can have boolean key also like ‘isFolder’ <strong>true/false</strong> instead of a ‘<strong>type</strong>’ key).</li><li>Folders have a children array. Files don’t need one.</li><li>The root node is still treated as a folder.</li></ul><p>This is a real file system and is flexible for recursion.</p><h3>Component Design</h3><p>From a React perspective, this breaks down into just three components:</p><ol><li>Folder — displays the folder name, manages expand/collapse state, and renders children.</li><li>File — displays a single file.</li><li>FileExplorer — Container component to anchor these two</li></ol><p>Since folders can contain other folders, recursion becomes the key.</p><h3>Recursive Rendering</h3><p>Here’s the component structure:</p><pre>export default function File({ name }) {<br>  return (<br>    &lt;div&gt;<br>      &lt;h1&gt;{name}&lt;/h1&gt;<br>    &lt;/div&gt;<br>  );<br>}<br><br><br>export default function Folder({ children, name, isOpen, handleFolderToggle }) {<br>  let ops = !isOpen[name] ? &quot;+&quot; : &quot;-&quot;;<br>  return (<br>    &lt;div&gt;<br>      &lt;span onClick={handleFolderToggle}&gt;<br>        {name} {ops}<br>      &lt;/span&gt;<br>      {isOpen[name] &amp;&amp; children}<br>    &lt;/div&gt;<br>  );<br>}</pre><p>Here Folder recursively renders either another Folder or a File inside. That single recursive step makes the tree handle any depth automatically.</p><h3>Putting It Together</h3><p>At the top-level, we just render our container:</p><pre>import { useState } from &quot;react&quot;;<br>import Folder from &quot;./Folder&quot;;<br>import File from &quot;./File&quot;;<br><br>export default function FileExplorer({ nodes }) {<br>  const [isOpen, setIsOpen] = useState({});<br>  const handleFolderToggle = (node) =&gt; {<br>    const { name } = node || {};<br>    setIsOpen((prev) =&gt; {<br>      return { ...prev, [name]: !prev[name] };<br>    });<br>  };<br>  return (<br>    &lt;div&gt;<br>      {nodes &amp;&amp;<br>        nodes.map((node, index) =&gt; {<br>          const { name, type, children } = node || {};<br>          if (type === &quot;file&quot;) {<br>            return &lt;File name={name} type={type} /&gt;;<br>          }<br>          if (type === &quot;folder&quot;) {<br>            return (<br>              &lt;Folder<br>                name={name}<br>                isOpen={isOpen}<br>                handleFolderToggle={() =&gt; handleFolderToggle(node)}<br>              &gt;<br>                &lt;FileExplorer nodes={children} /&gt;<br>              &lt;/Folder&gt;<br>            );<br>          }<br>        })}<br>    &lt;/div&gt;<br>  );<br>}<br><br>// Render in App.js<br><br>&lt;FileExplorer data={fileExplorerData} /&gt;;<br></pre><h3>LLD Interview Takeaways</h3><p>When you present this in an interview, focus not just on code but also on design decisions:</p><ul><li>Data Shape: Why a recursive tree structure is the best fit.</li><li>Recursion in Components: Keeps code clean, scalable for any depth level.</li><li>State Management: Each folder owns its own isOpen state, which makes it independent.</li></ul><p>Potential follow-ups you might get:</p><ul><li>How would you add right-click menus (e.g., “New File”, “Delete”)?</li><li>How would you persist open/closed state across sessions (local storage)?</li><li>How would you handle huge file trees (virtualization)?</li></ul><h3>Final Thoughts</h3><p>This LLD question highlights the combination between UI coding and architectural reasoning. The beauty lies in realizing that a React component can mirror your data structure recursively.</p><p>The same pattern can be applied to menus, organization charts, or any hierarchical data. So the next time someone asks you to build a VS Code–like explorer in an interview, you’ll know exactly how to explain both the thought process and the implementation.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3a6fc257efe8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building a Stopwatch with Lap Memory Using React]]></title>
            <link>https://medium.com/@sambitdash129/building-a-stopwatch-with-lap-memory-using-react-8df15dbc21fa?source=rss-8c0d53d5034b------2</link>
            <guid isPermaLink="false">https://medium.com/p/8df15dbc21fa</guid>
            <dc:creator><![CDATA[Sambit Dash]]></dc:creator>
            <pubDate>Fri, 12 Sep 2025 08:08:54 GMT</pubDate>
            <atom:updated>2025-09-12T08:14:44.488Z</atom:updated>
            <content:encoded><![CDATA[<p>A while ago, I appeared for an interview for a Big Tech , I was asked to build a stop watch feature in LLD round. This article shares how to put together a real-time stopwatch in React, with start/stop, reset, and lap features. No fancy libraries, just React hooks and state management done right.</p><h3>Managing State for this app</h3><p>Lets start by putting the essential state hooks:</p><ul><li>Elapsed time.</li><li>Running state.</li><li>Lap history.</li><li>Interval reference (using useRef).</li></ul><pre>const [isRunning, setIsRunning] = React.useState(false);<br>const [elapsedTime, setElapsedTime] = React.useState(0);<br>const [laps, setLaps] = React.useState([]);<br>const timerRef = React.useRef(null);</pre><h3>Implementing Start, Stop, and Reset</h3><p>I chose setInterval for ticking, and used Date.now() for timing.</p><pre>const handleStart = () =&gt; {<br>  if (!isRunning) {<br>    const startAt = Date.now() - elapsedTime;<br>    setIsRunning(true);<br>    timerRef.current = setInterval(() =&gt; {<br>      setElapsedTime(Date.now() - startAt);<br>    }, 10);<br>  }<br>};<br><br>const handleStop = () =&gt; {<br>  setIsRunning(false);<br>  clearInterval(timerRef.current);<br>};<br><br>const handleReset = () =&gt; {<br>  handleStop();<br>  setElapsedTime(0);<br>  setLaps([]);<br>};</pre><h3>Capturing Laps</h3><pre>const handleLap = () =&gt; {<br>  if (isRunning) {<br>    setLaps([...laps, elapsedTime]);<br>  }<br>};</pre><h3>Formatting and Display</h3><pre>function formatTime(ms) {<br>  const minutes = Math.floor(ms / 60000);<br>  const seconds = Math.floor((ms % 60000) / 1000);<br>  const centiseconds = Math.floor((ms % 1000) / 10);<br>  return (<br>    String(minutes).padStart(2, &#39;0&#39;) + &#39;:&#39; +<br>    String(seconds).padStart(2, &#39;0&#39;) + &#39;:&#39; +<br>    String(centiseconds).padStart(2, &#39;0&#39;)<br>  );<br>}</pre><p>Laps look like:</p><pre>{laps.map((lapTime, i) =&gt; {<br>  const prev = i === 0 ? 0 : laps[i - 1];<br>  const split = lapTime - prev;<br>  return (<br>    &lt;li key={i}&gt;<br>      Lap {i + 1}: {formatTime(split)} ({formatTime(lapTime)})<br>    &lt;/li&gt;<br>  );<br>})}</pre><h3>The UI</h3><pre>function Stopwatch() {<br>  // -- state, helper and event handlers as mentioned above<br><br>  return (<br>    &lt;div&gt;<br>      &lt;h2&gt;React Stopwatch with Laps&lt;/h2&gt;<br>      &lt;div&gt;{formatTime(elapsed)}&lt;/div&gt;<br>      &lt;div&gt;<br>        &lt;button onClick={handleStart} disabled={isRunning}&gt;Start&lt;/button&gt;<br>        &lt;button onClick={handleStop} disabled={!isRunning}&gt;Stop&lt;/button&gt;<br>        &lt;button onClick={handleLap} disabled={!isRunning}&gt;Lap&lt;/button&gt;<br>        &lt;button onClick={handleReset}&gt;Reset&lt;/button&gt;<br>      &lt;/div&gt;<br>      &lt;h3&gt;Laps&lt;/h3&gt;<br>      &lt;ul&gt;<br>        {laps.map((lapTime, i) =&gt; {<br>          const prev = i === 0 ? 0 : laps[i - 1];<br>          const split = lapTime - prev;<br>          return (<br>            &lt;li key={i}&gt;<br>              Lap {i + 1}: {formatTime(split)} ({formatTime(lapTime)})<br>            &lt;/li&gt;<br>          );<br>        })}<br>      &lt;/ul&gt;<br>    &lt;/div&gt;<br>  );<br>}</pre><p>This is a pluggable component for your react app.</p><h3>Closing Thoughts</h3><p>React hooks make time-tracking very simple. Laps work properly by using references and functional updates. Try this for your next coding challenge, and tweak it to log times or export laps.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8df15dbc21fa" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Custom Deep Copy Function in JavaScript]]></title>
            <link>https://medium.com/@sambitdash129/custom-deep-copy-function-in-javascript-59d886135e59?source=rss-8c0d53d5034b------2</link>
            <guid isPermaLink="false">https://medium.com/p/59d886135e59</guid>
            <dc:creator><![CDATA[Sambit Dash]]></dc:creator>
            <pubDate>Mon, 25 Aug 2025 10:18:00 GMT</pubDate>
            <atom:updated>2025-08-25T10:19:52.009Z</atom:updated>
            <content:encoded><![CDATA[<p>When working with JavaScript, sooner or later you’ll get into a common problem: copying objects. At first, calling Object.assign() or spreading with { ...obj } may feel like the solution. But those only make shallow copies — and if your object has nested arrays or objects inside, you may get some unpleasant surprises.</p><p>Let’s walk through why that happens and try to write a proper custom deep copy function.</p><h3>The Problem with Shallow Copies</h3><p>Lets have this simple example:</p><p>const user = {<br> name: “Test User Name”,<br> hobbies: [“h1”, “h2”],<br>};</p><p>const userCopy = { …user };</p><p>userCopy.hobbies.push(“h3”);</p><p>console.log(user.hobbies); // -&gt; [“h1”, “h2”, “h3”]</p><p>Even though we spread into a new object, the hobbies array is still a shared reference. That’s because the spread operator only copies the reference of nested objects/arrays, not their values.</p><p>So if we want a true independent copy, we need a deep copy.</p><h3>JSON Parse</h3><p>const deepCopy = JSON.parse(JSON.stringify(obj));</p><p>This works surprisingly well for plain data. But it falls apart with things like Date, Map, Set, undefined, functions, or circular references.</p><h3>Building a Custom Deep Copy Function</h3><p>We need to handle a few cases carefully:</p><ol><li>Primitive types → (string, number, boolean, null, undefined) → copy as-is.</li><li>Arrays → create a new array and recursively copy each element.</li><li>Objects → create a new object and recursively copy each key.</li><li>Special objects (Date, RegExp, Map, Set) → handle separately.</li><li>Circular references → Avoid infinite loops by tracking references.</li></ol><p>Lets code:</p><p>function deepCopy(value, trackerMap = new WeakMap()) {<br> // Handle null or primitive values<br> if (value === null || typeof value !== “object”) {<br> return value;<br> }</p><p>// If we’ve this object already (circular ref), return stored copy — we are using trackerMap as weak map to store the reference<br> if (trackerMap.has(value)) {<br> return trackerMap.get(value);<br> }</p><p>// Handle Date<br> if (value instanceof Date) {<br> return new Date(value);<br> }</p><p>// Handle RegExp<br> if (value instanceof RegExp) {<br> return new RegExp(value);<br> }</p><p>// Handle Array<br> if (Array.isArray(value)) {<br> const arrCopy = [];<br> trackerMap.set(value, arrCopy);<br> value.forEach((item, i) =&gt; {<br> arrCopy[i] = deepCopy(item, trackerMap);<br> });<br> return arrCopy;<br> }</p><p>// Handle Map<br> if (value instanceof Map) {<br> const mapCopy = new Map();<br> trackerMap.set(value, mapCopy);<br> value.forEach((val, key) =&gt; {<br> mapCopy.set(key, deepCopy(val, trackerMap));<br> });<br> return mapCopy;<br> }</p><p>// Handle Set<br> if (value instanceof Set) {<br> const setCopy = new Set();<br> trackerMap.set(value, setCopy);<br> value.forEach((val) =&gt; {<br> setCopy.add(deepCopy(val, trackerMap));<br> });<br> return setCopy;<br> }</p><p>// Handle plain objects<br> const objCopy = {};<br> trackerMap.set(value, objCopy);<br> Object.keys(value).forEach((key) =&gt; {<br> objCopy[key] = deepCopy(value[key], trackerMap);<br> });<br> return objCopy;<br>}</p><h3>Testing the solution with example</h3><p>Let’s test our solution:</p><p>const originalObject = {<br> name: “Test Name”,<br> birthdate: new Date(),<br> favorites: {<br> colors: [“c1”, “c2”],<br> },<br>};</p><p>const clonedObject = deepCopy(originalObject);</p><p>// Change clone object<br>clonedObject.favorites.colors.push(“c3”);</p><p>// Original stays intact<br>console.log(originalObject.favorites.colors); // [“c1”, “c2”]<br>console.log(originalObject.favorites.colors); // [“c1”, “c2”, “c3”]</p><h3>Wrapping Up</h3><p>While libraries like Lodash give you _.cloneDeep(), sometimes it’s a good learning to implement on your own. Writing this function from scratch helps you understand how references work in JavaScript, and gives you full control over what gets copied and how.</p><p>If you’re working with complex data structures, this custom deep copy function will work always.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=59d886135e59" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Deep Dive into the JavaScript Event Loop]]></title>
            <link>https://medium.com/@sambitdash129/deep-dive-into-the-javascript-event-loop-78701ad39466?source=rss-8c0d53d5034b------2</link>
            <guid isPermaLink="false">https://medium.com/p/78701ad39466</guid>
            <dc:creator><![CDATA[Sambit Dash]]></dc:creator>
            <pubDate>Wed, 06 Aug 2025 09:26:26 GMT</pubDate>
            <atom:updated>2025-08-06T09:26:26.275Z</atom:updated>
            <content:encoded><![CDATA[<p>If you’ve ever stopped to wonder, how JavaScript manages to handle user clicks, timers, and network calls — all seemingly at once — despite being single-threaded, then you’ve bumped into one of the coolest parts of JS, the event loop. Understanding it genuinely helps you write better, faster, and less buggy code.</p><p>Let’s unpack what the event loop is, why it matters, and how it really works under the hood.</p><h3>What’s the Event Loop ?</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Lxhm3TPWKEyH9Lplp545pQ.png" /><figcaption>Event loop</figcaption></figure><p>Imagine the event loop as the engine powering your JavaScript app. The tricky part is, JavaScript can only do one thing at a time, running code function by function on what’s called the <em>call stack</em>. This sounds limiting, but here’s where the event loop works its magic: it schedules lots of things to happen <em>asynchronously</em> in the background.</p><p>Why does this matter?</p><ul><li>Because without it, any long task like a fetching data from a server or waiting on a timer would make your whole UI or backend freeze.</li><li>The event loop lets JavaScript do multiple tasks, so your app stays smooth and responsive.</li></ul><h3>The Building Blocks: Call Stack, Web APIs, and Queues</h3><p>To really get this, you need to know a few parts:</p><ul><li>Call Stack: The place where your JS code is executed, line-by-line, function-by-function.</li><li>Web APIs: These are browser or Node.js provided tools (like timers, AJAX calls, event listeners) that handle asynchronous work outside the main thread.</li><li>Queues: Tasks wait here for their turn:</li><li>Microtask Queue — for Promise callbacks and “fast-track” jobs.</li><li>Macrotask Queue — handles things like timers, I/O, and UI events, which run after microtasks finish.</li></ul><h3>How Polling and Interrupts Come Into Play:</h3><ul><li><strong>Polling</strong>: The event loop doesn’t just wait passively — it polls, meaning it keeps checking if async things like I/O or timers are done. Once they are, their callbacks get dispatched immediately. This is how your app knows it’s “ready” to do more work.</li><li><strong>Interrupts</strong>: Unlike hardware interrupts you might see in embedded systems, JavaScript relies on what you can think of as “soft interrupts.” When an event listener fires or a callback is ready, they interrupt the main flow briefly, the callback runs, and then your program picks up right where it left off.</li></ul><h3>The Event Loop in Action</h3><p>Here’s a code snippet that shows the event loop doing its thing:</p><pre>console.log(&quot;Start&quot;);<br>setTimeout(() =&gt; {<br>  console.log(&quot;Callback&quot;);<br>}, 0);<br>Promise.resolve().then(() =&gt; {<br>  console.log(&quot;Resolved&quot;);<br>});<br>console.log(&quot;End&quot;);</pre><p>What outputs on the console?</p><pre>Start<br>End<br>Resolved<br>Callback</pre><p>Why does this happen?</p><ul><li>&quot;Start&quot; and &quot;End&quot; log first because they’re synchronous calls on the stack.</li><li>The resolved Promise callback moves to the microtask queue, which is given priority before any macrotasks.</li><li>The setTimeout callback is put in the macrotask queue, so it runs last.</li></ul><h3>Poll Phase</h3><p>If you’re working in Node.js especially, the poll phase is where the event loop waits for I/O (think filesystem or network requests) to complete. It’s basically “listening” and ready to run your callbacks as soon as these events finish. If nothing’s happening, Node actually pauses here to save resources.</p><h3>Wrapping Up</h3><p>Getting your head around the event loop is more than just an academic exercise. It’s a core skill that helps you understand tricky asynchronous bugs, why some callbacks run before others, and how to avoid freezing your UI or crashing your server processes.</p><p>If you’ve ever wrestled with weird timing issues or odd callback order, the event loop holds a huge piece of the puzzle.</p><p>Got a tough async story or a curious bug you’ve solved ? Drop a comment.</p><p><em>Happy coding, and may your event loops always spin smoothly!</em></p><p>#JavaScript #EventLoop #Async #WebDevelopment #NodeJS #CodingTips</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=78701ad39466" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Implementing Fuzzy Search in React JS with Fuse.JS]]></title>
            <link>https://medium.com/@sambitdash129/implementing-fuzzy-search-in-react-js-with-fuse-js-79dcb000ec03?source=rss-8c0d53d5034b------2</link>
            <guid isPermaLink="false">https://medium.com/p/79dcb000ec03</guid>
            <dc:creator><![CDATA[Sambit Dash]]></dc:creator>
            <pubDate>Tue, 29 Jul 2025 08:32:33 GMT</pubDate>
            <atom:updated>2025-07-29T09:07:20.415Z</atom:updated>
            <content:encoded><![CDATA[<p>Exceptional search is crucial for any application, especially when users have some typos. Here’s a guide for developing a fuzzy search with Fuse.JS in React.</p><p><strong>Fuzzy Search and Fuse.JS</strong></p><p>Traditional search approaches — using <strong>includes</strong>, <strong>indexOf</strong>, or simple string matching — fall short when users mistype or when search input is incomplete. Fuzzy search, or approximate string matching, closes that gap by surfacing results that are “almost” right, as well as those that are spot-on.</p><p>Fuse.JS is a JavaScript library for fuzzy searching. It brings lightning-fast, typo-friendly results to your React projects with minimal setup.</p><p><strong>Setting Up the React Project:</strong></p><blockquote>npm create vite@latest fuzzy-search-app — — template react</blockquote><blockquote>cd fuzzy-search-app</blockquote><blockquote>npm install</blockquote><blockquote>Now, add Fuse.JS:</blockquote><blockquote>npm install fuse.js</blockquote><p>Fuzzy Search Component Code</p><p>If have a dataset, like a list of users with attributes like name and email. The below code shows a Fuzzy search implemenattion</p><p><strong>1. Import ‘Fuse’ from fuse.js</strong></p><p>import Fuse from “fuse.js”;</p><p><strong>2. Mock Data</strong></p><p>const data = [</p><p>{ name: “test name1 “, email: “testname1@mail.com” },</p><p>{ name: “test name2, email: “testname2@mail.com”}</p><p>];</p><p><strong>3. Fuse.JS Options</strong></p><p>Customise how Fuse will compare and score results.</p><p>const filterOptions = {</p><p>keys: [“name”, “email”],</p><p>includeScore: true,</p><p>threshold: 0.1,</p><p>};</p><p><strong>4. The React Fuzzy Search Component</strong></p><p>function FuzzySearchComponent() {</p><p>const [filterText, setFilterText] = useState(“”);</p><p>const [results, setResults] = useState(items);</p><p>const fuse = new Fuse(data, filterOptions);</p><p>const handleSearch = (e) =&gt; {</p><p>const text = e.target.value;</p><p>setFilterText(input);</p><p>if (!text) {</p><p>setResults(items);</p><p>return;</p><p>}</p><p>const filteredResults = fuse.search(text).map(({ item }) =&gt; item);</p><p>setResults(filteredResults);</p><p>};</p><p>return (</p><p>&lt;div&gt;</p><p>&lt;input</p><p>type=”text”</p><p>placeholder=”Search the data”</p><p>value={filterText}</p><p>onChange={(e) =&gt; handleSearch(e)}</p><p>/&gt;</p><p>&lt;ul&gt;</p><p>{results.length ? (</p><p>results.map((item, index) =&gt; &lt;li key={index}&gt;{item.name} — {item.email}&lt;/li&gt;)</p><p>) : (</p><p>&lt;li&gt;No data found.&lt;/li&gt;</p><p>)}</p><p>&lt;/ul&gt;</p><p>&lt;/div&gt;</p><p>);</p><p>}</p><p>export default FuzzySearchComponent;</p><p><strong>Customise the Experience</strong></p><p><strong>- Threshold value</strong>:<br> A threshold of 0 means exact matches, 1 is the fuzziest. Most use cases feel right around 0.2–0.4.</p><p><strong>- Search for Multiple Fields</strong>:<br> Add more keys (e.g., <strong>[“name”, “email”…]</strong>), and Fuse.JS will look in all specified fields.</p><p><strong>- Get More Detailed Results</strong>:<br> Use <strong>includeScore</strong> and <strong>includeMatches</strong> to get metadata about match quality and the specific part of the string that matched.</p><p><strong>Conclusion</strong></p><p>Adding fuzzy search capability to React app with Fuse.JS takes just a few minutes and enhances the search experience for the users. It’s lightweight, powerful, and friendly to both developers and end users.</p><p>Happy coding!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=79dcb000ec03" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building React from Scratch: My Journey with Webpack, Babel, and Loaders]]></title>
            <link>https://medium.com/@sambitdash129/building-react-from-scratch-my-journey-with-webpack-babel-and-loaders-0db513ceb0d7?source=rss-8c0d53d5034b------2</link>
            <guid isPermaLink="false">https://medium.com/p/0db513ceb0d7</guid>
            <dc:creator><![CDATA[Sambit Dash]]></dc:creator>
            <pubDate>Thu, 24 Jul 2025 06:44:44 GMT</pubDate>
            <atom:updated>2025-07-24T06:53:55.459Z</atom:updated>
            <content:encoded><![CDATA[<p>In today’s world of powerful abstractions and starter kits, we often forget the learning and satisfaction gained from building something entirely from the scratch. Recently, I decided to step away from <strong>create-react-app</strong> and instead, set up a React project by hand — using Webpack, Babel, and an efficient system of loaders.</p><p>The process taught me a lot about what happens behind the scenes and made modern web development feel less like magic, more like craftsmanship.</p><p>Why Setting Up from Scratch?</p><ul><li><strong>Learning:</strong> Every configuration nudges you to learn what’s happening and why.</li><li><strong>Customisation:</strong> Freedom to tailor the setup exactly to project needs.</li><li><strong>Debugging:</strong> When something breaks, you know where to look.</li></ul><p>The Webpack Advantage: Bundling &amp; Minifying</p><ul><li><strong>Bundling:</strong> Think of it as connecting all your JS, CSS, images, and even fonts, and spitting out compact files browsers understands.</li><li><strong>Minification:</strong> Removes the unnecessary code, whitespace, comments, and even renames variables so you serve the smallest, fastest site possible.</li></ul><blockquote>Basic Webpack Setup</blockquote><blockquote>mkdir my-react-app</blockquote><blockquote>cd my-react-app</blockquote><blockquote>npm init -y</blockquote><blockquote>npm install react react-dom</blockquote><p><strong>npm install — save-dev webpack webpack-cli webpack-dev-server</strong></p><blockquote><strong>Create a webpack.config.js:</strong></blockquote><blockquote>const path = require(‘path’);</blockquote><blockquote>const HtmlWebpackPlugin = require(‘html-webpack-plugin’);</blockquote><blockquote>module.exports = {</blockquote><blockquote>entry: ‘./src/index.js’,</blockquote><blockquote>output: {</blockquote><blockquote>filename: ‘bundle.js’,</blockquote><blockquote>path: path.resolve(__dirname, ‘dist’),</blockquote><blockquote>clean: true,</blockquote><blockquote>},</blockquote><blockquote>module: {</blockquote><blockquote>rules: [</blockquote><blockquote>// Loaders go here (see next section!)</blockquote><blockquote>],</blockquote><blockquote>},</blockquote><blockquote>plugins: [</blockquote><blockquote>new HtmlWebpackPlugin({</blockquote><blockquote>template: ‘./public/index.html’,</blockquote><blockquote>}),</blockquote><blockquote>],</blockquote><blockquote>devServer: {</blockquote><blockquote>static: ‘./dist’,</blockquote><blockquote>hot: true,</blockquote><blockquote>open: true,</blockquote><blockquote>},</blockquote><blockquote>mode: ‘development’,</blockquote><blockquote>};</blockquote><p><strong>Loaders:</strong></p><blockquote>Loaders are the secret sauce — the tools that let Webpack process not just JavaScript, but everything a real app depends on</blockquote><blockquote>babel-loader — JS and JSX transpilation</blockquote><blockquote>css-loader — Handles CSS imports</blockquote><blockquote>style-loader — Injects styles into DOM</blockquote><blockquote>sass-loader — Compiles SASS/SCSS to CSS</blockquote><blockquote>asset/resource -Imports images/files</blockquote><blockquote>ts-loader — Adds TypeScript support</blockquote><p><strong>Example: Adding Babel and CSS Loaders</strong></p><p>Install dependencies:</p><p>npm install — save-dev babel-loader @babel/core @babel/preset-env @babel/preset-react css-loader style-loader</p><p>Update <strong>webpack.config.js</strong>:</p><p>module.exports = {</p><p>// …</p><p>module: {</p><p>rules: [</p><p>{</p><p>test: /\.(js|jsx)$/,</p><p>exclude: /node_modules/,</p><p>use: ‘babel-loader’</p><p>},</p><p>{</p><p>test: /\.css$/,</p><p>use: [‘style-loader’, ‘css-loader’]</p><p>},</p><p>{</p><p>test: /\.(png|jpg|gif|svg)$/i,</p><p>type: ‘asset/resource’,</p><p>}</p><p>],</p><p>},</p><p>// …</p><p>};</p><p>Your basic project layout might look like:</p><p>my-react-app/</p><p>├── src/</p><p>│ ├── index.js</p><p>│ └── App.jsx</p><p>├── public/</p><p>│ └── index.html</p><p>└── webpack.config.js</p><blockquote>src/index.js:</blockquote><blockquote>import React from “react”;</blockquote><blockquote>import ReactDOM from “react-dom/client”;</blockquote><blockquote>import App from “./App”;</blockquote><blockquote>const root = ReactDOM.createRoot(document.getElementById(“root”));</blockquote><blockquote>root.render(&lt;App /&gt;);</blockquote><blockquote>src/App.jsx:</blockquote><blockquote>import React from “react”;</blockquote><blockquote>import “./styles.css”;</blockquote><blockquote>const App = () =&gt; &lt;h1&gt;Hello React from Scratch!&lt;/h1&gt;;</blockquote><blockquote>export default App;</blockquote><blockquote>HTML Template (public/index.html):</blockquote><blockquote>&lt;!DOCTYPE html&gt;</blockquote><blockquote>&lt;html lang=”en”&gt;</blockquote><blockquote>&lt;head&gt;</blockquote><blockquote>&lt;meta charset=”UTF-8&quot; /&gt;</blockquote><blockquote>&lt;title&gt;React from Scratch&lt;/title&gt;</blockquote><blockquote>&lt;/head&gt;</blockquote><blockquote>&lt;body&gt;</blockquote><blockquote>&lt;div id=”root”&gt;&lt;/div&gt;</blockquote><blockquote>&lt;/body&gt;</blockquote><blockquote>&lt;/html&gt;</blockquote><blockquote><strong>Webpack’s production mode gives you minification out-of-the-box:</strong></blockquote><blockquote>“scripts”: {</blockquote><blockquote>“start”: “webpack serve — mode development”,</blockquote><blockquote>“build”: “webpack — mode production”</blockquote><blockquote>}</blockquote><blockquote>or advanced control, add the Terser plugin:</blockquote><blockquote>const TerserPlugin = require(‘terser-webpack-plugin’);</blockquote><blockquote>module.exports = {</blockquote><blockquote>// …</blockquote><blockquote>optimization: {</blockquote><blockquote>minimize: true,</blockquote><blockquote>minimizer: [</blockquote><blockquote>new TerserPlugin({</blockquote><blockquote>terserOptions: {</blockquote><blockquote>compress: { drop_console: true },</blockquote><blockquote>mangle: true</blockquote><blockquote>}</blockquote><blockquote>})</blockquote><blockquote>],</blockquote><blockquote>},</blockquote><blockquote>mode: ‘production’</blockquote><blockquote>};</blockquote><p><strong>CSS, Images, and Beyond</strong></p><ul><li>Add SASS/SCSS with <strong>sass-loader</strong> and <strong>sass</strong>.</li><li>Minify CSS using <strong>css-minimizer-webpack-plugin</strong>.</li><li>With asset/resource, images and fonts are bundled efficiently.</li></ul><p><strong>Final Thougths:</strong></p><ul><li>I gained full control over my dev environment.</li><li>Troubleshooting got easier because I understood every moving part.</li><li>Optimised builds meant faster load times and happier users.</li></ul><p>If you’ve always relied on boilerplates, give this manual approach a try — you’ll level up your debugging, customisation, and performance-tuning skills in a big way. Happy coding!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0db513ceb0d7" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>