<?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 Ritik Patel on Medium]]></title>
        <description><![CDATA[Stories by Ritik Patel on Medium]]></description>
        <link>https://medium.com/@ritik177?source=rss-9cd3a363b34d------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*MxolSSbma9EPD298</url>
            <title>Stories by Ritik Patel on Medium</title>
            <link>https://medium.com/@ritik177?source=rss-9cd3a363b34d------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 20:07:21 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@ritik177/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[ Sort a Linked List Using Merge Sort (Java) | Complete Explanation]]></title>
            <link>https://medium.com/@ritik177/sort-a-linked-list-using-merge-sort-java-complete-explanation-f69c7837c1a4?source=rss-9cd3a363b34d------2</link>
            <guid isPermaLink="false">https://medium.com/p/f69c7837c1a4</guid>
            <category><![CDATA[dsa-problem]]></category>
            <category><![CDATA[linked-lists]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[merge-sort]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Ritik Patel]]></dc:creator>
            <pubDate>Wed, 01 Apr 2026 03:05:07 GMT</pubDate>
            <atom:updated>2026-04-01T03:05:07.162Z</atom:updated>
            <content:encoded><![CDATA[<h3>🧠 Intuition</h3><p>Sorting a linked list efficiently is different from sorting an array because linked lists do not support random access. Due to this limitation, algorithms like quicksort are not ideal.</p><p>The best approach for linked lists is <strong>Merge Sort</strong> because:</p><ul><li>It works efficiently with sequential data</li><li>It does not require random access</li><li>Merging can be done in-place using pointers</li></ul><p>The idea is to:</p><ol><li>Split the linked list into two halves</li><li>Recursively sort each half</li><li>Merge the sorted halves</li></ol><p>To find the middle of the list, we use the <strong>slow and fast pointer technique</strong>.</p><h3>⚙️ Approach</h3><h3>Step 1: Base Case</h3><p>If the list is empty or has only one node, it is already sorted.</p><h3>Step 2: Find Middle (Slow &amp; Fast Pointer)</h3><ul><li>slow moves one step at a time</li><li>fast moves two steps at a time</li><li>When fast reaches the end, slow will be at the middle</li><li>Use a prev pointer to split the list</li></ul><h3>Step 3: Divide the List</h3><p>Split the list into:</p><ul><li>Left half → from head</li><li>Right half → from slow</li></ul><h3>Step 4: Recursively Sort</h3><p>Call the same function on both halves.</p><h3>Step 5: Merge Two Sorted Lists</h3><p>Merge the two sorted halves using a helper function.</p><h3>💻 Complete Code (Java)</h3><pre>/**<br> * Definition for singly-linked list.<br> * public class ListNode {<br> *     int val;<br> *     ListNode next;<br> *     ListNode() {}<br> *     ListNode(int val) { this.val = val; }<br> *     ListNode(int val, ListNode next) { this.val = val; this.next = next; }<br> * }<br> */</pre><pre>class Solution {<br>    public ListNode sortList(ListNode head) {<br>        // Base case<br>        if (head == null || head.next == null) {<br>            return head;<br>        }</pre><pre>        // Step 1: Find middle using slow-fast pointer<br>        ListNode slow = head;<br>        ListNode fast = head;<br>        ListNode prev = null;</pre><pre>        while (fast != null &amp;&amp; fast.next != null) {<br>            prev = slow;<br>            slow = slow.next;<br>            fast = fast.next.next;<br>        }</pre><pre>        // Break the list into two halves<br>        prev.next = null;</pre><pre>        // Step 2: Recursively sort both halves<br>        ListNode left = sortList(head);<br>        ListNode right = sortList(slow);</pre><pre>        // Step 3: Merge both sorted halves<br>        return merge(left, right);<br>    }</pre><pre>    // Helper function to merge two sorted linked lists<br>    private ListNode merge(ListNode l1, ListNode l2) {<br>        ListNode dummy = new ListNode(-1);<br>        ListNode temp = dummy;</pre><pre>        while (l1 != null &amp;&amp; l2 != null) {<br>            if (l1.val &lt; l2.val) {<br>                temp.next = l1;<br>                l1 = l1.next;<br>            } else {<br>                temp.next = l2;<br>                l2 = l2.next;<br>            }<br>            temp = temp.next;<br>        }</pre><pre>        // Attach remaining nodes<br>        if (l1 != null) temp.next = l1;<br>        if (l2 != null) temp.next = l2;</pre><pre>        return dummy.next;<br>    }<br>}</pre><h3>⏱️ Complexity Analysis</h3><ul><li><strong>Time Complexity: O(N log N)</strong><br>The list is divided into halves (log N levels), and merging takes O(N) at each level.</li><li><strong>Space Complexity: O(log N)</strong><br>Due to recursion stack (no extra data structures used).</li></ul><h3>🚀 Why Merge Sort for Linked List?</h3><p>AlgorithmSuitable for Linked List?Quick Sort❌ Not efficientBubble Sort❌ Too slow (O(N²))Merge Sort✅ Best choice</p><h3>💡 Key Takeaways</h3><ul><li>Use <strong>slow &amp; fast pointers</strong> to find the middle</li><li>Always break the list using prev.next = null</li><li>Use a <strong>dummy node</strong> to simplify merging</li><li>Merge Sort is the <strong>most optimal solution</strong> for linked list sorting</li></ul><h3>🔥 Bonus Tip (Interview Insight)</h3><p>If interviewer asks:<br>👉 Can you do it in <strong>O(1) space (no recursion)?</strong></p><p>Answer: Yes, using <strong>Bottom-Up Merge Sort (Iterative)</strong> — which is an advanced variation.</p><p>If you found this helpful, feel free to share 🚀</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f69c7837c1a4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ Zero-Downtime MongoDB Migration: From Embedded Instagram Data → Scalable Normalized Architecture]]></title>
            <link>https://medium.com/@ritik177/zero-downtime-mongodb-migration-from-embedded-instagram-data-scalable-normalized-architecture-fb72b3e9a904?source=rss-9cd3a363b34d------2</link>
            <guid isPermaLink="false">https://medium.com/p/fb72b3e9a904</guid>
            <category><![CDATA[database]]></category>
            <category><![CDATA[mongodb]]></category>
            <category><![CDATA[relational-databases]]></category>
            <category><![CDATA[migration]]></category>
            <category><![CDATA[database-migration]]></category>
            <dc:creator><![CDATA[Ritik Patel]]></dc:creator>
            <pubDate>Thu, 26 Mar 2026 03:47:14 GMT</pubDate>
            <atom:updated>2026-03-26T03:47:14.901Z</atom:updated>
            <content:encoded><![CDATA[<h3>🧠 Overview</h3><p>In this guide, I’ll walk you through how we migrated a production MongoDB database from a <strong>monolithic user schema</strong> (Instagram data embedded inside the User collection) to a <strong>fully normalized, scalable architecture</strong> — without downtime and without data loss.</p><p>This is a <strong>real-world production migration strategy</strong> used in scalable backend systems.</p><h3>📦 OLD ARCHITECTURE (PROBLEM)</h3><pre>User<br> ├── instagramId<br> ├── username<br> ├── followers<br> ├── insights[]<br> ├── averages<br> ├── accessToken<br> └── ...</pre><h3>❌ Problems:</h3><ul><li>Large user documents (performance issue)</li><li>Nested arrays (hard to scale)</li><li>Difficult analytics queries</li><li>Tight coupling (bad design)</li><li>Hard to extend for multiple platforms</li></ul><h3>🏗️ NEW ARCHITECTURE (SOLUTION)</h3><pre>User<br>   ↓<br>InstagramAccount<br>   ↓<br>InstagramPost<br>   ↓<br>InstagramPostInsight</pre><h3>✅ Benefits:</h3><ul><li>Clean separation of concerns</li><li>Scalable &amp; normalized</li><li>Faster queries</li><li>Easy analytics &amp; aggregation</li><li>Production-grade architecture</li></ul><h3>⚙️ STEP-BY-STEP MIGRATION PROCESS</h3><h3>✅ STEP 1: Add Reference in User Model</h3><pre>instagramAccount: {<br>  type: mongoose.Schema.Types.ObjectId,<br>  ref: &quot;InstagramAccount&quot;,<br>  default: null<br>}</pre><p>👉 This allows linking users to normalized Instagram data.</p><h3>✅ STEP 2: Create New Collections</h3><p>✔ InstagramAccount</p><p>✔ InstagramPost</p><p>✔ InstagramPostInsight</p><p>👉 These collections hold structured Instagram data instead of embedding it inside User.</p><h3>✅ STEP 3: Write Migration Script</h3><h3>Key Requirements:</h3><ul><li>Idempotent (safe to run multiple times)</li><li>Skip already migrated users</li><li>Handle duplicates</li><li>Bulk operations for speed</li></ul><h3>🚀 OPTIMIZED MIGRATION STRATEGY</h3><h3>✔ Avoid skip-based pagination ❌</h3><p>Use <strong>filter-based batching</strong> instead.</p><h3>✔ Use parallel execution:</h3><pre>await Promise.all(users.map(user =&gt; migrateSingleUser(user)));</pre><h3>✔ Use bulk insert:</h3><pre>insertMany({ ordered: false })</pre><h3>✔ Handle duplicates safely:</h3><ul><li>Use findOne before create</li><li>Use unique indexes</li></ul><h3>✅ STEP 4: Run Migration (Production)</h3><pre>node scripts/migrateInstagramData.js</pre><h3>✅ STEP 5: VERIFY MIGRATION</h3><h3>1️⃣ Total Users</h3><pre>db.users.countDocuments()</pre><h3>2️⃣ Migrated Users</h3><pre>db.users.countDocuments({<br>  instagramAccount: { $ne: null }<br>})</pre><h3>3️⃣ Not Migrated Users</h3><pre>db.users.countDocuments({<br>  instagramId: { $exists: true },<br>  instagramAccount: null<br>})</pre><p>👉 ✅ Result must be 0</p><h3>✅ STEP 6: Fix Skipped Users (IMPORTANT LESSON)</h3><h3>❌ Problem:</h3><p>Using .skip() caused users to be skipped during updates.</p><h3>✅ Fix:</h3><p>Use this instead:</p><pre>while (true) {<br>  const users = await User.find({<br>    instagramId: { $exists: true, $ne: null, $ne: &quot;&quot; },<br>    instagramAccount: null<br>  }).limit(50);</pre><pre>  if (!users.length) break;</pre><pre>  await Promise.all(users.map(migrateSingleUser));<br>}</pre><h3>✅ STEP 7: Data Validation</h3><pre>db.instagramaccounts.countDocuments()<br>db.instagramposts.countDocuments()<br>db.instagrampostinsights.countDocuments()</pre><p>👉 Ensure data is present and consistent.</p><h3>✅ STEP 8: Remove Legacy Fields (FINAL CLEANUP)</h3><pre>db.users.updateMany(<br>  {},<br>  {<br>    $unset: {<br>      username: &quot;&quot;,<br>      instagramId: &quot;&quot;,<br>      accountType: &quot;&quot;,<br>      instagramAccessToken: &quot;&quot;,<br>      instagramTokenExpiresAt: &quot;&quot;,<br>      instagramTokenRefreshedAt: &quot;&quot;,<br>      instagramFollowers: &quot;&quot;,<br>      instagramFollowing: &quot;&quot;,<br>      instagramMediaCount: &quot;&quot;,<br>      instagramProfilePicture: &quot;&quot;,<br>      instagramInsights: &quot;&quot;,<br>      instagramAverages: &quot;&quot;<br>    }<br>  }<br>)</pre><h3>✅ STEP 9: Remove Old Indexes</h3><pre>db.users.dropIndex(&quot;instagramId_1&quot;)<br>db.users.dropIndex(&quot;username_1&quot;)</pre><h3>✅ STEP 10: Update Backend Code</h3><ul><li>Remove dual logic</li><li>Remove legacy fallbacks</li><li>Use only normalized models</li><li>Update services/controllers</li></ul><h3>✅ STEP 11: Deploy to Production</h3><ul><li>Push updated code</li><li>Redeploy service</li><li>Monitor logs</li><li>Test APIs</li></ul><h3>🚨 COMMON ERRORS &amp; FIXES</h3><h3>❌ Duplicate Key Error</h3><pre>E11000 duplicate key error</pre><p>✔ Fix:</p><pre>findOne + create (instead of direct create)</pre><h3>❌ Slow Migration</h3><p>✔ Fix:</p><ul><li>Use parallel processing</li><li>Use bulk inserts</li><li>Avoid per-item DB calls</li></ul><h3>❌ Missing Data</h3><p>✔ Fix:</p><ul><li>Never run cleanup before migration</li><li>Always verify before deleting old fields</li></ul><h3>❌ Deployment Error (mongoose not found)</h3><p>✔ Fix:</p><pre>npm install mongoose</pre><p>Ensure it’s in &quot;dependencies&quot; not &quot;devDependencies&quot;</p><h3>🧠 KEY LEARNINGS</h3><pre>✔ Always write idempotent migration scripts<br>✔ Never use skip() during mutation<br>✔ Always verify before cleanup<br>✔ Keep rollback backup<br>✔ Separate data concerns early</pre><h3>🎯 FINAL RESULT</h3><pre>✔ Zero downtime migration<br>✔ No data loss<br>✔ Clean architecture<br>✔ Scalable backend system</pre><h3>🔥 CONCLUSION</h3><p>This migration transformed a tightly coupled schema into a <strong>modular, scalable system</strong>.</p><p>If you’re building production-grade apps, <strong>data normalization + safe migration strategy is a must-have skill</strong>.</p><p>💬 If this helped you, feel free to share or connect — happy to discuss more backend scaling strategies!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fb72b3e9a904" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Types of APIs (Complete Guide with Differences)]]></title>
            <link>https://medium.com/@ritik177/types-of-apis-complete-guide-with-differences-274c88ccd730?source=rss-9cd3a363b34d------2</link>
            <guid isPermaLink="false">https://medium.com/p/274c88ccd730</guid>
            <category><![CDATA[rest-api]]></category>
            <category><![CDATA[backend-development]]></category>
            <category><![CDATA[api]]></category>
            <category><![CDATA[graphql-api-vs-rest-api]]></category>
            <category><![CDATA[node]]></category>
            <dc:creator><![CDATA[Ritik Patel]]></dc:creator>
            <pubDate>Thu, 26 Mar 2026 03:31:31 GMT</pubDate>
            <atom:updated>2026-03-26T03:31:31.460Z</atom:updated>
            <content:encoded><![CDATA[<p>APIs (Application Programming Interfaces) allow different software systems to communicate with each other. There are multiple types of APIs based on <strong>architecture, accessibility, and usage</strong>.</p><h3>1. Based on Architecture Style</h3><h3>1.1 REST API (Representational State Transfer)</h3><ul><li>Most commonly used API style.</li><li>Uses HTTP methods: <strong>GET, POST, PUT, DELETE</strong></li><li>Stateless (each request is independent)</li><li>Data format: JSON (mostly)</li></ul><h3>Example:</h3><pre>GET /users<br>POST /users</pre><h3>Key Features:</h3><ul><li>Simple and scalable</li><li>Works over HTTP</li><li>Easy to integrate</li></ul><h3>1.2 SOAP API (Simple Object Access Protocol)</h3><ul><li>Protocol-based API (strict rules)</li><li>Uses XML format only</li><li>Highly secure and reliable</li></ul><h3>Example:</h3><pre>&lt;soap:Envelope&gt;<br>  &lt;soap:Body&gt;<br>    &lt;GetUserRequest /&gt;<br>  &lt;/soap:Body&gt;<br>&lt;/soap:Envelope&gt;</pre><h3>Key Features:</h3><ul><li>Built-in security (WS-Security)</li><li>Works over HTTP, SMTP</li><li>More complex than REST</li></ul><h3>1.3 GraphQL API</h3><ul><li>Query-based API developed by Facebook</li><li>Client can request only required data</li></ul><h3>Example:</h3><pre>query {<br>  user(id: 1) {<br>    name<br>    email<br>  }<br>}</pre><h3>Key Features:</h3><ul><li>No over-fetching or under-fetching</li><li>Single endpoint</li><li>Flexible queries</li></ul><h3>1.4 gRPC API</h3><ul><li>High-performance API developed by Google</li><li>Uses Protocol Buffers (Protobuf)</li><li>Works over HTTP/2</li></ul><h3>Key Features:</h3><ul><li>Very fast</li><li>Supports streaming</li><li>Strong typing</li></ul><h3>2. Based on Accessibility</h3><h3>2.1 Public API (Open API)</h3><ul><li>Available for external developers</li><li>Example: Google Maps API</li></ul><h3>Key Features:</h3><ul><li>Open for use</li><li>Requires API key</li><li>Used for integrations</li></ul><h3>2.2 Private API (Internal API)</h3><ul><li>Used within an organization only</li></ul><h3>Key Features:</h3><ul><li>Not exposed publicly</li><li>More secure</li><li>Used for internal systems</li></ul><h3>2.3 Partner API</h3><ul><li>Shared with specific business partners</li></ul><h3>Key Features:</h3><ul><li>Controlled access</li><li>Requires authentication</li><li>Used for B2B</li></ul><h3>3. Based on Communication Type</h3><h3>3.1 Web API</h3><ul><li>APIs over HTTP/HTTPS</li><li>Example: REST, GraphQL</li></ul><h3>3.2 Library API</h3><ul><li>APIs provided by libraries/frameworks</li></ul><h3>Example:</h3><pre>Math.random()</pre><h3>3.3 Operating System API</h3><ul><li>Used to interact with OS</li></ul><h3>Example:</h3><ul><li>File system API</li></ul><h3>4. Key Differences Between API Types</h3><p>FeatureREST APISOAP APIGraphQLgRPCData FormatJSONXMLJSONProtobufSpeedMediumSlowFastVery FastFlexibilityMediumLowHighMediumComplexityLowHighMediumHighUse CaseWeb appsEnterpriseModern appsMicroservices</p><h3>5. Summary</h3><ul><li><strong>REST</strong> → Simple, most popular</li><li><strong>SOAP</strong> → Secure but complex</li><li><strong>GraphQL</strong> → Flexible and efficient</li><li><strong>gRPC</strong> → High-performance systems</li></ul><h3>Conclusion</h3><p>Choosing the right API depends on your use case:</p><ul><li>Use <strong>REST</strong> for general web apps</li><li>Use <strong>GraphQL</strong> when you need flexible data fetching</li><li>Use <strong>gRPC</strong> for high-performance microservices</li><li>Use <strong>SOAP</strong> for enterprise-level security</li></ul><p>✔️ APIs are the backbone of modern software communication. Understanding their types helps you design better scalable systems.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=274c88ccd730" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Make Your Mac Terminal Powerful with Oh My Zsh (5 Minutes Setup)]]></title>
            <link>https://medium.com/@ritik177/how-to-make-your-mac-terminal-powerful-with-oh-my-zsh-5-minutes-setup-a92c3997d99d?source=rss-9cd3a363b34d------2</link>
            <guid isPermaLink="false">https://medium.com/p/a92c3997d99d</guid>
            <category><![CDATA[github]]></category>
            <category><![CDATA[terminal]]></category>
            <category><![CDATA[mac]]></category>
            <category><![CDATA[vscode]]></category>
            <category><![CDATA[git]]></category>
            <dc:creator><![CDATA[Ritik Patel]]></dc:creator>
            <pubDate>Sat, 14 Mar 2026 07:14:30 GMT</pubDate>
            <atom:updated>2026-03-14T07:14:30.991Z</atom:updated>
            <content:encoded><![CDATA[<p>If you’re a developer using macOS, customizing your terminal can significantly improve productivity and developer experience.</p><p>In this guide, we’ll set up a modern terminal using <strong>Oh My Zsh</strong> with autosuggestions and syntax highlighting.</p><h3>1️⃣ Install Oh My Zsh</h3><p>Run the following command in your terminal:</p><pre>sh -c &quot;$(curl -fsSL https://raw.githubusercontent.com/ohmyzsh/ohmyzsh/master/tools/install.sh)&quot;</pre><p>This will install <strong>Oh My Zsh</strong> and configure Zsh automatically.</p><h3>2️⃣ Change the Theme (Optional)</h3><p>Open your configuration file:</p><pre>nano ~/.zshrc</pre><p>Find the line:</p><pre>ZSH_THEME=&quot;robbyrussell&quot;</pre><p>Replace it with:</p><pre>ZSH_THEME=&quot;agnoster&quot;</pre><p>Save and exit.</p><p>Then reload the configuration:</p><pre>source ~/.zshrc</pre><h3>3️⃣ Install Autosuggestions Plugin</h3><p>This plugin suggests previously used commands as you type.</p><pre>git clone https://github.com/zsh-users/zsh-autosuggestions ${ZSH_CUSTOM:-~/.oh-my-zsh/custom}/plugins/zsh-autosuggestions</pre><h3>4️⃣ Install Syntax Highlighting Plugin</h3><p>This plugin highlights valid and invalid commands in the terminal.</p><pre>git clone https://github.com/zsh-users/zsh-syntax-highlighting.git ${ZSH_CUSTOM:-~/.oh-my-zsh/custom}/plugins/zsh-syntax-highlighting</pre><h3>5️⃣ Enable the Plugins</h3><p>Open .zshrc again:</p><pre>nano ~/.zshrc</pre><p>Find:</p><pre>plugins=(git)</pre><p>Replace with:</p><pre>plugins=(git zsh-autosuggestions zsh-syntax-highlighting)</pre><p>Save the file and reload:</p><pre>source ~/.zshrc</pre><h3>Final Result</h3><p>Your terminal will now have:</p><p>✅ Git integration<br>✅ Command autosuggestions<br>✅ Syntax highlighting<br>✅ A cleaner developer-friendly prompt</p><p>Example:</p><pre>~/project-name git:(main) ➜</pre><h3>🧹 Uninstall (Optional)</h3><p>If you ever want to remove Oh My Zsh:</p><pre>uninstall_oh_my_zsh</pre><p>💡 Small improvements like this can make your developer workflow faster and more enjoyable.</p><p>#DeveloperTools #MacOS #Terminal #OhMyZsh #Productivity</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a92c3997d99d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[JavaScript Promises — Complete Guide with Examples]]></title>
            <link>https://medium.com/@ritik177/javascript-promises-complete-guide-with-examples-c5774a2a08c6?source=rss-9cd3a363b34d------2</link>
            <guid isPermaLink="false">https://medium.com/p/c5774a2a08c6</guid>
            <category><![CDATA[javascript-interview]]></category>
            <category><![CDATA[javascript-development]]></category>
            <category><![CDATA[promises]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[javascript-tips]]></category>
            <dc:creator><![CDATA[Ritik Patel]]></dc:creator>
            <pubDate>Tue, 10 Mar 2026 03:01:08 GMT</pubDate>
            <atom:updated>2026-03-10T03:01:08.516Z</atom:updated>
            <content:encoded><![CDATA[<h3>What are Promises in JavaScript?</h3><p>A <strong>Promise</strong> is an object which represents the <strong>eventual completion or failure of an asynchronous operation in JavaScript</strong>.</p><p>At any point in time, a promise will be in one of the following states:</p><ul><li><strong>Fulfilled:</strong> Action related to the promise has succeeded.</li><li><strong>Rejected:</strong> Action related to the promise has failed.</li><li><strong>Pending:</strong> Promise is neither fulfilled nor rejected.</li><li><strong>Settled:</strong> Promise has either been fulfilled or rejected.</li></ul><p>Promises can be consumed by registering functions using the <strong>.then()</strong> and <strong>.catch()</strong> methods.</p><h3>Promise Constructor</h3><p>The <strong>Promise constructor</strong> takes <strong>one argument</strong>, which is a <strong>callback function</strong>.</p><p>This callback function receives <strong>two parameters</strong>:</p><ul><li>resolve</li><li>reject</li></ul><p>If the operations inside the callback function are successful, we call <strong>resolve()</strong>.<br>If the operations fail, we call <strong>reject()</strong>.</p><h3>Example</h3><pre>let promise = new Promise(function(resolve, reject) {<br>  const x = &quot;Saikrishna&quot;;<br>  const y = &quot;Saikrishna&quot;;</pre><pre>  if (x === y) {<br>    resolve(&quot;Valid&quot;);<br>  } else {<br>    let err = new Error(&quot;Invalid&quot;);<br>    reject(err);<br>  }<br>});</pre><pre>promise<br>  .then((response) =&gt; {<br>    console.log(&quot;success&quot;, response);<br>  })<br>  .catch((err) =&gt; {<br>    console.log(&quot;failed&quot;, err);<br>  });</pre><p>Output</p><pre>success Valid</pre><h3>Promise Utility Methods</h3><p>JavaScript provides several methods to work with <strong>multiple promises together</strong>.</p><ul><li>Promise.all()</li><li>Promise.allSettled()</li><li>Promise.any()</li><li>Promise.race()</li></ul><p>Let’s understand each one with examples.</p><h3>1. Promise.all()</h3><h3>Definition</h3><p><strong>Promise.all()</strong> takes an array of promises and returns a single promise that:</p><ul><li><strong>Resolves when all promises resolve</strong></li><li><strong>Rejects immediately if any promise rejects</strong></li></ul><h3>Example</h3><pre>const p1 = Promise.resolve(10);<br>const p2 = Promise.resolve(20);<br>const p3 = Promise.resolve(30);</pre><pre>Promise.all([p1, p2, p3])<br>  .then((result) =&gt; {<br>    console.log(result);<br>  })<br>  .catch((err) =&gt; {<br>    console.log(err);<br>  });</pre><p>Output</p><pre>[10, 20, 30]</pre><h3>Important Point</h3><p>If any promise fails:</p><pre>const p1 = Promise.resolve(&quot;Success&quot;);<br>const p2 = Promise.reject(&quot;Failed&quot;);<br>const p3 = Promise.resolve(&quot;Done&quot;);</pre><pre>Promise.all([p1, p2, p3])<br>  .then((res) =&gt; console.log(res))<br>  .catch((err) =&gt; console.log(err));</pre><p>Output</p><pre>Failed</pre><h3>2. Promise.allSettled()</h3><h3>Definition</h3><p><strong>Promise.allSettled()</strong> waits for <strong>all promises to complete</strong>, regardless of whether they are fulfilled or rejected.</p><p>It always returns an array of results describing the outcome of each promise.</p><h3>Example</h3><pre>const p1 = Promise.resolve(&quot;Success&quot;);<br>const p2 = Promise.reject(&quot;Error&quot;);<br>const p3 = Promise.resolve(&quot;Completed&quot;);</pre><pre>Promise.allSettled([p1, p2, p3]).then((result) =&gt; {<br>  console.log(result);<br>});</pre><p>Output</p><pre>[<br> { status: &quot;fulfilled&quot;, value: &quot;Success&quot; },<br> { status: &quot;rejected&quot;, reason: &quot;Error&quot; },<br> { status: &quot;fulfilled&quot;, value: &quot;Completed&quot; }<br>]</pre><h3>3. Promise.race()</h3><h3>Definition</h3><p><strong>Promise.race()</strong> returns the result of the <strong>first promise that settles (either resolve or reject)</strong>.</p><p>Whichever promise completes first will determine the result.</p><h3>Example</h3><pre>const p1 = new Promise((resolve) =&gt;<br>  setTimeout(() =&gt; resolve(&quot;First&quot;), 2000)<br>);</pre><pre>const p2 = new Promise((resolve) =&gt;<br>  setTimeout(() =&gt; resolve(&quot;Second&quot;), 1000)<br>);</pre><pre>Promise.race([p1, p2]).then((result) =&gt; {<br>  console.log(result);<br>});</pre><p>Output</p><pre>Second</pre><p>Because p2 finished first.</p><h3>4. Promise.any()</h3><h3>Definition</h3><p><strong>Promise.any()</strong> resolves as soon as <strong>any one promise resolves successfully</strong>.</p><p>It ignores rejected promises unless <strong>all promises fail</strong>.</p><h3>Example</h3><pre>const p1 = Promise.reject(&quot;Error 1&quot;);<br>const p2 = Promise.resolve(&quot;Success&quot;);<br>const p3 = Promise.resolve(&quot;Completed&quot;);</pre><pre>Promise.any([p1, p2, p3])<br>  .then((result) =&gt; {<br>    console.log(result);<br>  })<br>  .catch((err) =&gt; {<br>    console.log(err);<br>  });</pre><p>Output</p><pre>Success</pre><p>Because the <strong>first fulfilled promise is returned</strong>.</p><h3>Difference Between Promise Methods</h3><p>MethodResolves WhenRejects WhenResultPromise.all()All promises succeedAny promise failsArray of resultsPromise.allSettled()All promises finishNever rejectsStatus objectsPromise.race()First promise settlesFirst rejected promiseFirst resultPromise.any()First fulfilled promiseIf all promises failFirst success</p><h3>Quick Interview Summary</h3><ul><li><strong>Promise.all()</strong> → Use when <strong>all APIs must succeed</strong></li><li><strong>Promise.allSettled()</strong> → Use when you need <strong>results of all promises</strong></li><li><strong>Promise.race()</strong> → Use when <strong>fastest response matters</strong></li><li><strong>Promise.any()</strong> → Use when <strong>any one successful response is enough</strong></li></ul><h3>Conclusion</h3><p>Promises make asynchronous operations in JavaScript <strong>cleaner, more readable, and easier to manage</strong>.</p><p>Understanding how <strong>Promise.all(), Promise.allSettled(), Promise.any(), and Promise.race()</strong> work is essential for handling <strong>multiple API calls, parallel operations, and performance optimization</strong> in modern JavaScript applications.</p><p>If you found this helpful, feel free to share it with other developers 🚀</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c5774a2a08c6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding IP-Based Location Tracking: How It Works, Its Limitations, and How to Get Accurate…]]></title>
            <link>https://medium.com/@ritik177/understanding-ip-based-location-tracking-how-it-works-its-limitations-and-how-to-get-accurate-935a5181a241?source=rss-9cd3a363b34d------2</link>
            <guid isPermaLink="false">https://medium.com/p/935a5181a241</guid>
            <category><![CDATA[ip-based-tracking-and]]></category>
            <category><![CDATA[location-tracking]]></category>
            <category><![CDATA[geolocation]]></category>
            <category><![CDATA[mern-stack]]></category>
            <dc:creator><![CDATA[Ritik Patel]]></dc:creator>
            <pubDate>Thu, 05 Mar 2026 05:30:37 GMT</pubDate>
            <atom:updated>2026-03-05T05:34:41.916Z</atom:updated>
            <content:encoded><![CDATA[<h3>Understanding IP-Based Location Tracking: How It Works, Its Limitations, and How to Get Accurate User Location</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NOmxMjePsYGoOvkVEoW06g.png" /></figure><p>Location tracking is widely used in analytics, affiliate marketing, fraud detection, and personalization systems. Many developers initially rely on <strong>IP-based geolocation</strong> to determine where users are visiting from. While this method is simple to implement, it often leads to confusion because the returned location may not match the user’s exact location.</p><p>This article explains:</p><ul><li>How IP-based location tracking works</li><li>Why it often returns incorrect or approximate locations</li><li>How to check a user’s IP address in the browser</li><li>How to implement IP-based tracking in your backend</li><li>How to obtain <strong>exact location</strong> using browser APIs</li></ul><p>The goal is to help developers understand both the <strong>capabilities and limitations</strong> of IP-based geolocation.</p><h3>1. What Is IP-Based Location Tracking?</h3><p>Every device connected to the internet is assigned an <strong>IP address (Internet Protocol address)</strong> by an Internet Service Provider (ISP) such as Jio, Airtel, Vodafone, or a broadband provider.</p><p>IP-based location tracking works by mapping this IP address to a <strong>geolocation database</strong> maintained by companies that collect network routing and ISP information.</p><p>These databases estimate a user’s location based on:</p><ul><li>ISP network infrastructure</li><li>Routing data</li><li>Regional IP allocations</li><li>Data center or network gateway locations</li></ul><p>Developers can use public APIs to convert an IP address into location data such as:</p><ul><li>Country</li><li>Region / State</li><li>City</li><li>ISP</li><li>Latitude &amp; Longitude (approximate)</li></ul><p>Example APIs:</p><ul><li>ip-api.com</li><li>ipinfo.io</li><li>ipapi.co</li></ul><p>Example request:</p><pre>http://ip-api.com/json/152.59.179.56</pre><p>Example response:</p><pre>{<br>  &quot;country&quot;: &quot;India&quot;,<br>  &quot;regionName&quot;: &quot;Uttar Pradesh&quot;,<br>  &quot;city&quot;: &quot;Kanpur&quot;,<br>  &quot;isp&quot;: &quot;Reliance Jio Infocomm Limited&quot;<br>}</pre><h3>2. Why IP Location Is Often Incorrect</h3><p>Many developers expect IP location to show the <strong>exact city or street</strong>, but that is not how IP geolocation works.</p><p>The main reason is that <strong>IP addresses represent networks, not individual devices</strong>.</p><h3>Example scenario</h3><pre>Actual user location: Jhansi<br>IP API response: Kanpur</pre><p>This happens because the IP address belongs to a <strong>network gateway or ISP routing hub located in Kanpur</strong>, not the user’s physical device location.</p><h3>3. Why This Problem Happens</h3><p>There are several technical reasons why IP-based location can be inaccurate.</p><h3>3.1 Carrier Grade NAT (CGNAT)</h3><p>Mobile networks often use <strong>Carrier Grade NAT</strong>, where thousands of users share a single public IP address.</p><p>Example:</p><pre>Public IP: 152.59.179.56<br>Users sharing it: thousands<br>Network owner: Reliance Jio</pre><p>Because many users share the same IP, the location reflects the <strong>ISP network node</strong>, not individual users.</p><h3>3.2 ISP Routing Infrastructure</h3><p>ISPs route traffic through major <strong>regional network centers</strong>.</p><p>For example:</p><pre>User location: Jhansi<br>ISP routing hub: Kanpur</pre><p>The geolocation database associates that IP block with the <strong>routing hub city</strong>.</p><h3>3.3 Dynamic IP Addresses</h3><p>Most internet connections use <strong>dynamic IP addresses</strong>, meaning they change periodically.</p><p>For example:</p><pre>Today:     152.59.179.56<br>Tomorrow:  152.59.181.12</pre><p>Even though the user did not move, their IP may change.</p><h3>4. Accuracy of IP-Based Location</h3><p>Typical accuracy levels:</p><p>Data TypeAccuracyCountryVery accurateState/RegionMostly accurateCityApproximateStreet / HouseNot possible</p><p>Typical range:</p><pre>10 km – 100 km</pre><p>Therefore, IP location is suitable for:</p><ul><li>Analytics dashboards</li><li>Regional personalization</li><li>Fraud detection</li><li>Affiliate traffic analysis</li></ul><p>But <strong>not for exact user positioning</strong>.</p><h3>5. How to Check Your IP Address from a Browser</h3><p>You can easily check your public IP address using these services.</p><p>Open this in your browser:</p><pre>https://api.ipify.org?format=json</pre><p>Example response:</p><pre>{<br> &quot;ip&quot;: &quot;152.59.179.56&quot;<br>}</pre><p>You can also use:</p><pre>https://whatismyipaddress.com/</pre><p>Once you know the IP, you can test it with a geolocation API.</p><p>Example:</p><pre>http://ip-api.com/json/152.59.179.56</pre><h3>6. How to Implement IP-Based Tracking in a Backend</h3><p>In a Node.js backend, you typically capture the user’s IP address from the request.</p><p>Example:</p><pre>const userIp =<br>  req.headers[&#39;x-forwarded-for&#39;]?.split(&#39;,&#39;)[0]?.trim() ||<br>  req.socket.remoteAddress;</pre><p>Then call a geolocation API:</p><pre>const axios = require(&quot;axios&quot;);</pre><pre>const response = await axios.get(<br>  `http://ip-api.com/json/${userIp}?fields=country,regionName,city`<br>);</pre><pre>console.log(response.data);</pre><p>Example output:</p><pre>{<br> country: &quot;India&quot;,<br> regionName: &quot;Uttar Pradesh&quot;,<br> city: &quot;Kanpur&quot;<br>}</pre><p>This information can then be stored in your database for analytics.</p><h3>7. How to Get Exact User Location</h3><p>If you need <strong>accurate location</strong>, IP-based tracking is not enough.</p><p>Instead, you must use the <strong>Browser Geolocation API</strong>, which uses:</p><ul><li>GPS</li><li>Wi-Fi positioning</li><li>Cell tower triangulation</li></ul><p>Example:</p><pre>navigator.geolocation.getCurrentPosition((position) =&gt; {<br>  console.log(position.coords.latitude);<br>  console.log(position.coords.longitude);<br>});</pre><p>Example output:</p><pre>Latitude: 25.4502<br>Longitude: 78.5689</pre><p>Accuracy:</p><pre>10 – 50 meters</pre><p>However, this requires <strong>user permission</strong>.</p><p>Browsers will display a popup asking the user to allow location access.</p><h3>8. Best Practice: Hybrid Location Tracking</h3><p>Most modern analytics and affiliate systems combine multiple methods.</p><p>Typical architecture:</p><pre>IP Geolocation<br>+<br>Browser Geolocation (optional)<br>+<br>Timezone<br>+<br>Language<br>+<br>Device fingerprint</pre><p>Workflow example:</p><ol><li>Capture IP location automatically</li><li>Request precise location if user permission is granted</li><li>Store both datasets for analytics</li></ol><p>Example stored data:</p><pre>Country: India<br>City: Kanpur<br>ISP: Reliance Jio<br>Timezone: Asia/Kolkata<br>Latitude: 25.45<br>Longitude: 78.56</pre><h3>9. When to Use Each Method</h3><p>MethodUse CaseIP LocationAnalytics, affiliate trackingBrowser GeolocationDelivery apps, ride-sharingGPSMobile applicationsHybridAdvanced analytics systems</p><h3>Conclusion</h3><p>IP-based geolocation is a useful tool for <strong>high-level location insights</strong>, but it cannot provide precise user locations. The data reflects the <strong>network infrastructure of the ISP</strong>, not the exact position of the user.</p><p>For applications requiring accurate positioning, developers should use the <strong>Browser Geolocation API or GPS-based methods</strong>, ideally combined with IP-based tracking for additional context.</p><p>Understanding these differences helps developers design more reliable tracking systems and avoid common misconceptions about IP geolocation accuracy.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=935a5181a241" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Difference between shallow copy and deep copy]]></title>
            <link>https://medium.com/@ritik177/difference-between-shallow-copy-and-deep-copy-f486e65e6d08?source=rss-9cd3a363b34d------2</link>
            <guid isPermaLink="false">https://medium.com/p/f486e65e6d08</guid>
            <category><![CDATA[deep-copy]]></category>
            <category><![CDATA[shallow-copy]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Ritik Patel]]></dc:creator>
            <pubDate>Tue, 24 Feb 2026 03:44:21 GMT</pubDate>
            <atom:updated>2026-02-24T03:53:07.208Z</atom:updated>
            <content:encoded><![CDATA[<h3>Shallow Copy vs Deep Copy</h3><p>Shallow copy and deep copy are two ways to duplicate objects and arrays in JavaScript. They differ in how they handle nested objects and references.</p><h3>Shallow Copy</h3><p>A shallow copy creates a new object/array, but inserts copies of the references of nested objects into it. The top-level properties are copied, but nested objects are still linked to the original.</p><h3>How Shallow Copy Works:</h3><ul><li>Creates a new object/array</li><li>Copies primitive values directly</li><li>Copies references for nested objects (they still point to the same memory location)</li></ul><h3>Methods for Shallow Copy:</h3><blockquote><strong><em>Original object with nested structure</em></strong><em><br>const original = {<br> name: “John”,<br> age: 30,<br> address: {<br> city: “New York”,<br> country: “USA”<br> },<br> hobbies: [“reading”, “gaming”]<br>};</em></blockquote><blockquote><strong><em>Method 1: Object.assign()</em></strong><em><br>const shallowCopy1 = Object.assign({}, original);</em></blockquote><blockquote><strong><em>Method 2: Spread operator</em></strong><em><br>const shallowCopy2 = { …original };</em></blockquote><blockquote><strong><em>Method 3: Array slice() for arrays</em></strong><em><br>const arrayOriginal = [1, 2, [3, 4]];<br>const arrayCopy = arrayOriginal.slice();</em></blockquote><blockquote><strong><em>Method 4: Array.from() for arrays</em></strong><em><br>const arrayCopy2 = Array.from(arrayOriginal);</em></blockquote><blockquote><strong><em>Method 5: Object.create()</em></strong><em><br>const shallowCopy3 = Object.create(original);</em></blockquote><h3>Demonstrating Shallow Copy Behavior:</h3><blockquote>const original = {<br> name: “John”,<br> address: {<br> city: “New York”,<br> zip: 10001<br> }<br>};</blockquote><blockquote>const shallowCopy = { …original };</blockquote><blockquote><strong><em>Modifying primitive value in copy (doesn’t affect original)</em></strong><br>shallowCopy.name = “Jane”;<br>console.log(original.name); // “John” — unchanged<br>console.log(shallowCopy.name); // “Jane”</blockquote><blockquote><strong><em>Modifying nested object in copy (affects original!)</em></strong><br>shallowCopy.address.city = “Boston”;<br>console.log(original.address.city); // “Boston” — changed!<br>console.log(shallowCopy.address.city); // “Boston”</blockquote><blockquote><strong><em>Both objects reference the same nested object</em></strong><br>console.log(shallowCopy.address === original.address); // true</blockquote><h3>Deep Copy</h3><p>A deep copy creates a completely independent clone of the original object, including all nested objects. Changes to the copy don’t affect the original at any level.</p><h3>Methods for Deep Copy:</h3><blockquote><strong><em>Original object with nested structure</em></strong><em><br>const original = {<br> name: “John”,<br> age: 30,<br> address: {<br> city: “New York”,<br> country: “USA”,<br> coordinates: {<br> lat: 40.7128,<br> lng: -74.0060<br> } },<br> hobbies: [“reading”, “gaming”, { difficulty: “medium” }],<br> date: new Date()<br>};</em></blockquote><blockquote><strong><em>Method 1: JSON.parse/JSON.stringify (limited — doesn’t work with functions, undefined, etc.)</em></strong><em><br>const deepCopy1 = JSON.parse(JSON.stringify(original));</em></blockquote><blockquote><strong><em>Method 2: Recursive function</em></strong><em><br>function deepCopy(obj) {<br> </em><strong><em>Handle null or non-objects</em></strong><em><br> if (obj === null || typeof obj !== ‘object’) {<br> return obj;<br> }<br> <br> </em><strong>Handle Date</strong><em><br> if (obj instanceof Date) {<br> return new Date(obj.getTime());<br> }<br> <br> // Handle Array<br> if (Array.isArray(obj)) {<br> return obj.map(item =&gt; deepCopy(item));<br> }<br> <br> // Handle Object<br> const clonedObj = {};<br> for (let key in obj) {<br> if (obj.hasOwnProperty(key)) {<br> clonedObj[key] = deepCopy(obj[key]);<br> } }<br> <br> return clonedObj;<br>}</em></blockquote><blockquote><em>const deepCopy2 = deepCopy(original);</em></blockquote><blockquote><strong><em>Method 3: Using structuredClone (modern browsers)</em></strong><em><br>const deepCopy3 = structuredClone(original);</em></blockquote><blockquote><strong><em>Method 4: Using libraries (Lodash)</em></strong><em><br>const deepCopy4 = _.cloneDeep(original);</em></blockquote><h3>Demonstrating Deep Copy Behavior:</h3><blockquote>const original = {<br> name: “John”,<br> address: {<br> city: “New York”,<br> zip: 10001<br> }};</blockquote><blockquote>// Using JSON method<br>const deepCopy = JSON.parse(JSON.stringify(original));</blockquote><blockquote>// Modifying primitive value in copy<br>deepCopy.name = “Jane”;<br>console.log(original.name); // “John” — unchanged</blockquote><blockquote>// Modifying nested object in copy<br>deepCopy.address.city = “Boston”;<br>console.log(original.address.city); // “New York” — unchanged!<br>console.log(deepCopy.address.city); // “Boston”</blockquote><blockquote>// Objects have different references<br>console.log(deepCopy.address === original.address); // false</blockquote><h3>Example 1: Array with Nested Objects</h3><p>const users = [<br> { id: 1, name: “John”, settings: { theme: “dark” } },<br> { id: 2, name: “Jane”, settings: { theme: “light” } }<br>];</p><p>// Shallow copy<br>const shallowUsers = […users];<br>shallowUsers[0].settings.theme = “blue”;<br>console.log(users[0].settings.theme); // “blue” — changed!</p><p>// Deep copy<br>const deepUsers = JSON.parse(JSON.stringify(users));<br>deepUsers[0].settings.theme = “green”;<br>console.log(users[0].settings.theme); // “blue” — unchanged<br>console.log(deepUsers[0].settings.theme); // “green”</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f486e65e6d08" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>