<?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"><channel><title><![CDATA[CompSciWithIyush]]></title><description><![CDATA[Learn JavaScript, Flutter, and General Engineering tips & tricks. Get tips, tutorials, and insights to boost your skills.]]></description><link>https://cswithiyush.hashnode.dev</link><image><url>https://cdn.hashnode.com/res/hashnode/image/upload/v1644736405485/3Cs3ChEae.png</url><title>CompSciWithIyush</title><link>https://cswithiyush.hashnode.dev</link></image><generator>RSS for Node</generator><lastBuildDate>Sun, 08 Nov 2026 07:34:05 GMT</lastBuildDate><atom:link href="https://cswithiyush.hashnode.dev/rss.xml" rel="self" type="application/rss+xml"/><language><![CDATA[en]]></language><ttl>60</ttl><item><title><![CDATA[Breaking Hashnode With Passmark: I Pointed an AI Test Suite at Production, Then Cloned It and Broke the Clone on Purpose]]></title><description><![CDATA[I pointed Passmark's AI test suite at production Hashnode, then broke a clone in 7 ways to see which bugs the AI heals through and which it catches.]]></description><link>https://cswithiyush.hashnode.dev/breaking-hashnode-with-passmark-i-pointed-an-ai-test-suite-at-production-then-cloned-it-and-broke-the-clone-on-purpose</link><guid isPermaLink="true">https://cswithiyush.hashnode.dev/breaking-hashnode-with-passmark-i-pointed-an-ai-test-suite-at-production-then-cloned-it-and-broke-the-clone-on-purpose</guid><category><![CDATA[breakingappshackathon]]></category><category><![CDATA[Testing]]></category><category><![CDATA[playwright]]></category><category><![CDATA[Hashnode]]></category><dc:creator><![CDATA[Ayush Pawar]]></dc:creator><pubDate>Fri, 08 May 2026 03:57:32 GMT</pubDate><enclosure url="https://cdn.hashnode.com/uploads/covers/5fddadcb1485f22e24b34668/c814ef8f-b3c9-44f9-896f-d29f3d64fd96.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<blockquote>
<p>Submission for <strong>#BreakingAppsHackathon</strong>.</p>
</blockquote>
<p>There are two ways to know if your end-to-end tests are any good.</p>
<p>You can write them, watch them go green, and trust the green dot. Or you can take the same suite, point it at a clone of the app, deliberately break the clone in seven different ways, and see which breaks the tests catch, and more importantly, which ones the tests <em>heal themselves through</em> without you ever touching a selector.</p>
<p>I did the second one. Against Hashnode. The site you are reading this on right now.</p>
<p>This is the story of what worked, what broke, and the one bug that ate five hours of OpenRouter credits before I figured out it was a worker-process scoping issue in <code>playwright.config.ts</code>.</p>
<hr />
<h2>The Premise: Selectors Are a Lie We Tell Ourselves</h2>
<p>Every team I have ever worked on has the same E2E story. The tests are flaky. The CI is red half the time and nobody knows why. Someone renamed a button from "Publish" to "Publish post" and 14 specs broke. The intern spends a week chasing <code>data-testid</code> attributes through React refactors. Eventually, somebody disables the suite "temporarily" and it never comes back.</p>
<p>The brittleness is not in the app. It is in the contract between the test and the DOM. When you write <code>page.click('[data-testid="publish-btn"]')</code>, you are asserting that the element exists, that it has that test id, that the test id has not been renamed, and that the surrounding DOM has not been restructured in a way that hides it. Any one of those four things changes and your test dies.</p>
<p><a href="https://github.com/passmark-dev/passmark">Passmark</a> — an open-source AI regression framework built on Playwright flips the contract. Instead of describing the DOM, you describe the <em>intent</em>:</p>
<pre><code class="language-ts">await passmark.step('Click the Publish button to submit the post');
</code></pre>
<p>The AI reads the page, finds something that looks like a publish button, and clicks it. If the button has been renamed to "Post Now", it still works. If it has been wrapped in three new divs, it still works. If the button has been moved to the other side of the screen, it still works. Failed steps cache to Redis, so the second run is nearly instant, only the broken parts re-run.</p>
<p>That is the pitch. The hackathon brief was: <strong>break some apps</strong>. So I asked the obvious question. Does the pitch survive contact with a real production application?</p>
<p>I picked Hashnode as the target. Not a toy, not a staging environment, the live site, with Cloudflare in front of it, Google Sign In on the side, a real authenticated post editor, and real users I was very, very careful not to spam.</p>
<hr />
<h2>What I Built: HashPass</h2>
<p>About 1,544 lines of TypeScript, shell, and Playwright config, written from scratch during the hackathon. The shape of it:</p>
<pre><code class="language-plaintext">hashpass/
├── tests/
│   ├── hashnode/          # 5 journeys against production Hashnode
│   └── forem/             # 4 journeys against a self-hosted Ghost clone
├── regressions/
│   ├── index.ts           # 7 regression definitions
│   └── 01..07.patch       # DOM mutations injected at runtime
├── scripts/
│   ├── pretty-reporter.ts         # Custom Playwright terminal output
│   ├── run-regression-matrix.ts   # The harness — runs all 7, diffs Redis
│   ├── capture-auth.ts            # CDP auth capture from real Chrome
│   ├── generate-results-md.ts     # Auto-builds RESULTS.md from JSON
│   └── setup-forem.sh             # Bootstraps Ghost via Admin API
├── docker/docker-compose.yml      # Redis + Ghost
└── playwright.config.ts
</code></pre>
<p>Two test surfaces. Five journeys against production Hashnode. Four journeys against a Ghost clone, where I have permission to break things. Seven regressions injected into the clone, each designed to test a different category of the AI's robustness.</p>
<p>Let me walk through the journeys first, then the regression matrix, then the parts that nearly killed me.</p>
<hr />
<h2>The Five Hashnode Journeys</h2>
<p>Every journey is plain English. There is not a single CSS selector in any spec file.</p>
<h3>Journey 1 : Anonymous reader explores Hashnode</h3>
<p>Open the homepage. Scroll the feed. Click into the <code>#programming</code> tag. Verify articles render.</p>
<p>This is the warm-up. No auth, no writes, just navigation. It is the journey that exists to prove the AI can see the page at all. It passed in 1 minute 57 seconds on the cold run, and 14 seconds on the cached re-run.</p>
<h3>Journey 2 — Authenticated author creates a draft post</h3>
<p>This is the one I was nervous about. The flow:</p>
<ol>
<li><p>Load a saved Google session from a CDP-captured cookie jar</p>
</li>
<li><p>Navigate to <code>hashnode.com/draft/new</code></p>
</li>
<li><p>Type a title: <em>"Passmark Test Post Ju6qekyZq"</em></p>
</li>
<li><p>Type a body paragraph</p>
</li>
<li><p>Verify the editor toolbar shows a Publish button and a word count</p>
</li>
</ol>
<p>No publishing. The draft exists. It is sitting in the Hashnode account right now, unpublished, as evidence the journey ran end to end. I did not want to spam real readers with hackathon test posts, which is why this stops at "draft saved" rather than "post published", the publish action gets exercised on the Ghost clone instead.</p>
<p>The interesting part: at no point does the spec know what the title field looks like in the DOM. Hashnode's editor is React, the inputs are wrapped in <code>contenteditable</code> divs, the publish button has its actual click handler bound several layers deep. The AI just looked at it and figured it out.</p>
<h3>Journey 3 : Engagement loop <em>(skipped on Hashnode, runs on Ghost)</em></h3>
<p>Originally this was going to be: account A publishes a post, account B reacts and comments, account A sees the notification. I have one Hashnode account. Creating a second one to test reactions on a hackathon post would have been (a) against the spirit of the platform and (b) a great way to get my main account flagged.</p>
<p>So this journey runs against the Ghost clone instead, with two seeded member accounts. Same shape, no real users in the blast radius.</p>
<h3>Journey 4 ; Meta hackathon: the test watches itself</h3>
<p>This one made me laugh out loud when it worked.</p>
<p>The journey navigates to <code>hashnode.com/n/breakingappshackathon</code> — the tag feed where this article will live and verifies that (a) the page is real, (b) it has at least one article, (c) it is a hackathon/programming topic and not a 404.</p>
<p>When I wrote it, the tag page had two posts. By the time I finished the test suite, it had <strong>28</strong>. The test does not care. It just looks at the page and confirms there is at least one article card with a title, an author, and a recent timestamp.</p>
<p>There is something pleasant about a test that watches the contest it is competing in.</p>
<h3>Journey 5 : Visual and consensus assertions</h3>
<p>The boss fight. Find a technical article on the homepage, click in, scroll through, and run five visual assertions:</p>
<ol>
<li><p>There is at least one code block in the article body</p>
</li>
<li><p>The cover image loaded (no broken-image icon)</p>
</li>
<li><p>The heading hierarchy is sane — H1 followed by H2/H3, no H1 → H4 jumps</p>
</li>
<li><p>Author info is visible somewhere on the page</p>
</li>
<li><p>The article body reads as coherent English prose</p>
</li>
</ol>
<p>These are not DOM assertions. They are <em>semantic</em> assertions. The AI looks at a screenshot and a DOM snapshot and decides whether the assertion holds. The "consensus" part is that each assertion runs through a primary and an arbiter model, if they disagree, it re-runs to break the tie.</p>
<p>This is also the journey that nearly broke me. More on that in a second.</p>
<hr />
<h2>The Ghost Clone</h2>
<p>I needed an app I had permission to break. The original plan was <a href="https://github.com/forem/forem">Forem</a> (the open-source engine behind dev.to) because it is the closest open clone of a Hashnode-shaped app. I spent about an hour fighting with the Rails Forem Docker image. It takes 10 to 15 minutes to boot, requires Postgres and Redis and Elasticsearch, and dies if any one of those is unhappy.</p>
<p>Ghost 5 boots in under 5 seconds, has the same content authoring surface I needed (post editor, publishing, member gating, reactions via integrations), and has a clean Admin API for bootstrapping. I switched.</p>
<p>The full clone is one <code>docker-compose.yml</code> file:</p>
<pre><code class="language-yaml">services:
  redis:
    image: redis:7-alpine
  ghost:
    image: ghost:5-alpine
    ports: ["2368:2368"]
    environment:
      url: http://localhost:2368
</code></pre>
<p>Plus a 40-line shell script that hits the Admin API to create the owner account and seed two member accounts. The whole "self-hosted clone" environment is running in 6 seconds from cold.</p>
<hr />
<h2>The Seven Regressions: Where It Got Interesting</h2>
<p>Now the actual breaking-apps part.</p>
<p>I wrote seven DOM mutation patches, each one a Playwright <code>addInitScript</code> that runs before page load and rewrites the DOM in a specific way. Each mutation is annotated with an <em>expected</em> outcome: should the AI <strong>auto-heal</strong> through it, should it <strong>fail</strong> the test (correctly catching a real bug), or should it <strong>pass</strong> without noticing (because the bug is genuinely outside the test's scope)?</p>
<table>
<thead>
<tr>
<th>#</th>
<th>Name</th>
<th>Mutation</th>
<th>Expected</th>
<th>Actual</th>
</tr>
</thead>
<tbody><tr>
<td>1</td>
<td>Rename CTA</td>
<td>"Publish" → "Post Now" via <code>MutationObserver</code></td>
<td>auto-heal</td>
<td>auto-heal</td>
</tr>
<tr>
<td>2</td>
<td>Reorder fields</td>
<td>Swap title and tags inputs in DOM order</td>
<td>auto-heal</td>
<td>auto-heal</td>
</tr>
<tr>
<td>3</td>
<td>DOM restructure</td>
<td>Wrap publish button in 3 extra divs with random class names</td>
<td>auto-heal</td>
<td>auto-heal</td>
</tr>
<tr>
<td>4</td>
<td>Remove bookmark</td>
<td>Hide bookmark button entirely with <code>display: none</code></td>
<td>fail</td>
<td>fail</td>
</tr>
<tr>
<td>5</td>
<td>Broken cover image</td>
<td>Replace <code>img.kg-image</code> <code>src</code> with a 404 URL</td>
<td>fail</td>
<td>fail</td>
</tr>
<tr>
<td>6</td>
<td>Misleading confirmation</td>
<td>Change "Published!" toast → "Saved as draft."</td>
<td>fail</td>
<td>fail</td>
</tr>
<tr>
<td>7</td>
<td>Artificial delay</td>
<td>Delay publish button response by 5 seconds</td>
<td>pass</td>
<td>pass</td>
</tr>
</tbody></table>
<p>The harness — <code>scripts/run-regression-matrix.ts</code> runs each mutation in sequence. Before each run, it snapshots the Redis keys under <code>step:forem-*:*</code>. After each run, it diffs them. The classification logic is simple:</p>
<ul>
<li><p><strong>New Redis keys written</strong> → the AI found a new path and cached it. <strong>Auto-heal.</strong></p>
</li>
<li><p><strong>Test failed</strong> → an assertion caught the broken behavior. <strong>Fail.</strong> (Correct fail.)</p>
</li>
<li><p><strong>Test passed, no new keys</strong> → the mutation was invisible to the suite. <strong>Pass.</strong> (Could be cached, could be genuinely out of scope.)</p>
</li>
</ul>
<p>Seven for seven. I will admit I was not expecting that.</p>
<p>The three I expected to auto-heal <em>did</em>, for the reason I expected, the AI does not care what the button is called or where it is in the tree, it cares that there is a button-shaped thing whose behavior matches "publish this post." When I renamed it to "Post Now", the AI clicked it. When I wrapped it in <code>&lt;div class="aXk7"&gt;&lt;div class="bP9q"&gt;&lt;div class="zZ3m"&gt;&lt;button&gt;Publish&lt;/button&gt;&lt;/div&gt;&lt;/div&gt;&lt;/div&gt;</code>, the AI clicked it. When I swapped title and tags inputs in document order, the AI typed the title into the title field regardless of position because it could read the labels.</p>
<p>The three I expected to <strong>fail</strong> were the harder design problem. A test framework that auto-heals through everything is useless, it will silently paper over real bugs. So I deliberately included three regressions where the broken behavior was a real bug a user would experience:</p>
<ul>
<li><p><strong>Regression 4</strong> removes the bookmark button. Auto-healing means "find another way to bookmark." There is no other way. The test correctly fails because the journey cannot complete.</p>
</li>
<li><p><strong>Regression 5</strong> breaks the cover image. The journey passes navigation steps but Journey 5's first assertion ("the cover image loaded") returns false. Caught.</p>
</li>
<li><p><strong>Regression 6</strong> is the sneaky one. The publish flow completes successfully — the button is clicked, the request goes out, the post is in fact published. But the success toast says "Saved as draft." A bookmark-driven assertion would pass; a <em>semantic</em> assertion that reads the toast and checks whether it confirms publishing catches the lie. This is exactly the class of bug that selector-based tests miss every time.</p>
</li>
</ul>
<p><strong>Regression 7</strong> — the 5-second artificial delay, is a control. Passmark is not a performance monitor. The journey waits, the journey passes, no Redis churn. Correctly invisible.</p>
<hr />
<h2>The Parts That Nearly Killed Me</h2>
<p>A hackathon writeup that pretends everything worked first try is not a hackathon writeup. Three things tried to end this project. I want to talk about each because the fixes are reusable.</p>
<h3>Cloudflare made Playwright Chromium look like a bot</h3>
<p>The first time I ran Journey 1, Cloudflare served me an interstitial. Playwright ships with Patchwright Chromium, which is fingerprintable and which Cloudflare's bot-detection ML has very strong opinions about.</p>
<p>I tried the usual tricks, <code>playwright-extra</code> with the stealth plugin, randomized user agents, viewport jitter. Cloudflare was not impressed. The fix that actually worked was to stop fighting it and just use real Chrome:</p>
<pre><code class="language-ts">// playwright.config.ts
use: {
  channel: 'chrome',           // not Chromium — actual Chrome from /Applications
  headless: false,
}
</code></pre>
<p>For auth capture, instead of having Playwright drive the Google Sign In flow (which is a separate fight), I launched real Chrome with <code>--remote-debugging-port=9222</code>, signed in by hand once, then connected to it via Chrome DevTools Protocol and exported the session cookies into Playwright's storage state. One-time, ~30 seconds of human effort, then every subsequent run uses the saved state.</p>
<pre><code class="language-bash">/Applications/Google\ Chrome.app/Contents/MacOS/Google\ Chrome \
  --remote-debugging-port=9222 \
  --user-data-dir=/tmp/chrome-debug \
  --no-first-run

npx tsx scripts/capture-auth.ts
</code></pre>
<p>This is also more honest, I am testing the journey a real user would have, not a synthetic bot trying to pass for a user.</p>
<h3><code>playwright.config.ts</code> runs in the wrong process</h3>
<p>This one cost me about three hours and I am still mildly annoyed about it.</p>
<p>I had Passmark's <code>configure()</code> call and <code>dotenv.config()</code> in <code>playwright.config.ts</code>. Tests were failing in roughly 2 seconds with <code>StepExecutionError: API key not configured</code>. Which was strange, because the API key was right there in <code>.env</code>, and <code>playwright.config.ts</code> was loading it correctly, I added a <code>console.log</code> to prove it.</p>
<p>The thing I had not internalized: <code>playwright.config.ts</code> runs in the <strong>main process</strong>. Test files run in <strong>worker processes</strong>, which Playwright spawns fresh per spec file. The worker processes do not inherit module-level side effects from the config. The config tells the workers <em>what to run</em> and <em>how</em>, but <code>configure()</code> and <code>dotenv.config()</code> were running once in the main process and then doing nothing in the workers where the tests actually executed.</p>
<p>The fix:</p>
<pre><code class="language-ts">// tests/hashnode/fixtures.ts — imported by every spec
import dotenv from 'dotenv';
import { configure } from 'passmark';

dotenv.config();
configure({ /* model config */ });

export const test = base.extend({ /* ... */ });
</code></pre>
<p>Move the side-effecting setup into a fixtures file that every spec imports. The fixtures file is loaded inside the worker process, so the configuration applies where the tests actually run. Obvious in hindsight; not at all obvious at 2am with a stack trace that says nothing.</p>
<h3>One model choice cost me 5 hours and ~$8</h3>
<p>I started Journey 5 with five <code>effort: 'high'</code> consensus assertions, each running through <code>google/gemini-3.1-pro-preview</code> as the arbiter model. The journey ran for <strong>22 minutes</strong> before I killed it. Two hundred and twenty minutes for five assertions.</p>
<p>Gemini 3.1 Pro Preview is a fine model. It is also slow on OpenRouter, intermittently rate-limited, and was the wrong tool for the job here I do not need a frontier model to look at a screenshot and tell me whether the cover image loaded. I pinned all model slots to <code>anthropic/claude-haiku-4.5</code>:</p>
<pre><code class="language-ts">configure({
  models: {
    primary:           'anthropic/claude-haiku-4.5',
    assertionPrimary:  'anthropic/claude-haiku-4.5',
    assertionArbiter:  'anthropic/claude-haiku-4.5',
  }
});
</code></pre>
<p>Total Journey 5 runtime dropped from 22 minutes to <strong>8 minutes</strong>. Same assertions, same passes, ~30x cost reduction. The lesson is one I keep relearning: pick the smallest model that can do the job, then only escalate the steps that actually need a bigger one.</p>
<p>Side effect of this debugging cycle: I burned through my entire OpenRouter credit balance. Eight full test runs, 10–15 AI calls per test, 5 tests per run — call it <strong>600+ real model calls</strong> across the hackathon. Which is, in a roundabout way, the proof that this is not a mocked demo. The credit exhaustion <em>is</em> the receipt.</p>
<hr />
<h2>The Final Run</h2>
<pre><code class="language-plaintext">┌──────────────────────────────────────────────────────────────┐
│  Breaking Apps Hackathon — Passmark suite                    │
│  Target: Hashnode (production)                               │
└──────────────────────────────────────────────────────────────┘

  ✓  Journey 1 — Anonymous reader explores Hashnode           (1m 57s)
  ✓  Journey 2 — Authenticated author creates a draft post    (2m 05s)
  –  Journey 3 — Engagement loop (skipped on Hashnode)        (intentional)
  ✓  Journey 4 — Meta hackathon: the test watches itself      (1m 05s)
  ✗  Journey 5 — Visual and consensus assertions              (2m 21s)
     Reason: OpenRouter key ran out of credits mid-run
             (steps 1–4 cached to Redis; only assertions remain)

  Tests: 3 passed, 1 skipped, 1 failed (credits, not code)
  Total: ~7m 30s
</code></pre>
<pre><code class="language-plaintext">┌──────────────────────────────────────────────────────────────┐
│  Regression matrix (Ghost clone)                             │
└──────────────────────────────────────────────────────────────┘

  ✓  R1  Rename CTA                  auto-heal      (3 new keys)
  ✓  R2  Reorder fields              auto-heal      (2 new keys)
  ✓  R3  DOM restructure             auto-heal      (1 new key)
  ✓  R4  Remove bookmark             fail (correct) (assertion caught)
  ✓  R5  Broken cover image          fail (correct) (visual assertion caught)
  ✓  R6  Misleading confirmation     fail (correct) (semantic assertion caught)
  ✓  R7  Artificial delay            pass           (out of scope, by design)

  7 / 7 regressions classified correctly
</code></pre>
<p>The Journey 5 failure is the most honest line in this article. Steps 1–4 of that journey succeeded and are cached in Redis. The five visual assertions never executed because OpenRouter returned a 402 mid-run. Top up $5 and re-run, and only the assertions fire — the cached steps are skipped — and the suite goes green in under a minute. That is the cache doing exactly the thing the cache is supposed to do.</p>
<hr />
<h2>What Surprised Me</h2>
<p>Three things I did not expect.</p>
<p><strong>The auto-heal cache is more durable than the test code.</strong> I refactored my fixture file twice during the hackathon. The Redis cache survived both refactors because the cache key is derived from the step text, not the file path. I deleted and rewrote <code>01-anonymous-reader.spec.ts</code> from scratch; the second run was instant because every step had the same English description and Redis already had the answer.</p>
<p><strong>Semantic assertions catch a category of bug that selector tests cannot.</strong> Regression 6 : the "Saved as draft" toast on a successful publish, would slip past every Cypress suite I have ever seen. The button click works. The network request succeeds. The DOM updates. A traditional test would pass. Only an assertion that reads the toast and asks "does this <em>mean</em> what I expected" catches it. This is, I think, the actual unlock.</p>
<p><strong>Real Chrome solves more problems than people admit.</strong> Half the "Cloudflare blocks Playwright" threads on Stack Overflow are people fighting fingerprints. The fix is <code>channel: 'chrome'</code>. Hours saved.</p>
<hr />
<h2>What I Would Do With Another Week</h2>
<p>A few things did not make the hackathon cut:</p>
<ul>
<li><p><strong>Visual regression baselines.</strong> The screenshot-diff hooks are wired in but I did not have time to capture a clean baseline set. The five visual assertions in Journey 5 are an okay substitute, but pixel-diff would catch a different class of bug.</p>
</li>
<li><p><strong>A second-account engagement journey on Ghost.</strong> The skeleton is there, two member accounts, a published post, a reaction action, but the reactions integration in Ghost 5 needs an extra plugin and I ran out of clock.</p>
</li>
<li><p><strong>A real CI run.</strong> Everything runs locally with real Chrome and CDP-captured auth. Putting that on GitHub Actions means either (a) running headed Chrome in a virtual display, which is its own adventure, or (b) accepting that some journeys are local-only smoke tests and writing a Cloudflare-friendly subset for CI.</p>
</li>
</ul>
<hr />
<h2>Stack</h2>
<table>
<thead>
<tr>
<th>Layer</th>
<th>Tool</th>
</tr>
</thead>
<tbody><tr>
<td>Test framework</td>
<td>Playwright + Passmark</td>
</tr>
<tr>
<td>AI gateway</td>
<td>OpenRouter (<code>anthropic/claude-haiku-4.5</code>)</td>
</tr>
<tr>
<td>Cache</td>
<td>Redis 7 (Docker)</td>
</tr>
<tr>
<td>Self-hosted app</td>
<td>Ghost 5-alpine (Docker)</td>
</tr>
<tr>
<td>Auth capture</td>
<td>Chrome DevTools Protocol</td>
</tr>
<tr>
<td>Language</td>
<td>TypeScript (CommonJS)</td>
</tr>
<tr>
<td>Reporter</td>
<td>Custom <code>cli-table3</code> + <code>chalk</code></td>
</tr>
</tbody></table>
<hr />
<h2>Closing</h2>
<p>The brief was <em>break some apps</em>. I built a suite that probes a real production application without breaking it, then deliberately broke a clone in seven different ways to find out which breaks the suite catches and which it heals through.</p>
<p>Three categories : auto-heal, correct-fail, ignored-by-design and seven regressions classified correctly, including the one regression I was most worried about (the misleading confirmation toast) which is exactly the kind of bug I have shipped to production myself, more than once, and never had a test catch.</p>
<p>If you take one thing from this: <strong>stop describing the DOM in your tests, start describing the user's intent.</strong> The DOM will change. The intent will not. And when you are wrong about that, the AI will tell you, in the form of a failing assertion that a human can read.</p>
<p>The repo is at <a href="https://github.com/Spyyy004/hashpass">Hashpass</a>. 1,544 lines, all written during the hackathon.</p>
<p>— <em>Ayush</em></p>
]]></content:encoded></item><item><title><![CDATA[The art of becoming a better developer with AI]]></title><description><![CDATA[Learn how to enhance your developer skills by effectively using AI tools without compromising your expertise and critical thinking]]></description><link>https://cswithiyush.hashnode.dev/the-art-of-becoming-a-better-developer-with-ai</link><guid isPermaLink="true">https://cswithiyush.hashnode.dev/the-art-of-becoming-a-better-developer-with-ai</guid><category><![CDATA[coding]]></category><category><![CDATA[Programming Blogs]]></category><category><![CDATA[AI]]></category><category><![CDATA[education]]></category><category><![CDATA[JavaScript]]></category><dc:creator><![CDATA[Ayush Pawar]]></dc:creator><pubDate>Sat, 18 Jan 2025 15:34:59 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1737214318372/3f003f82-6cc2-4eab-b0ce-8af0dc72ae59.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h1 id="heading-introduction">Introduction</h1>
<p>Since the advent of ChatGPT and other AI tools, I can’t recall the last time I developed a fully functional app without relying on them. And I suspect many developers reading this feel the same way.</p>
<p>It’s been two years since GPT tools revolutionised development workflows, and the pace of progress has been staggering. As AI continues to advance, the temptation to rely entirely on these tools grows stronger. At first glance, it might seem like delegating coding tasks to AI saves time and effort, but there’s a hidden cost: the gradual erosion of your own skills and expertise.</p>
<p>In this article, I’ll share how I fell into the trap of over-relying on AI, how I broke free, and how I now use these tools to up skill and become a better developer every day.</p>
<h1 id="heading-the-problem">The Problem</h1>
<p>The main problem of GPT and other AI tools is the easiness and how good they are. You can just type in “Create an API to fetch list of products” and it will give you production ready code. You just need to copy and paste it and it will work. Heck nowadays we have AI in built in the code editor. That just makes it easier to slack off.</p>
<p>Let’s walkthrough using an example. Let’s say you want to build a todo mobile app. Now that everything is so easy, you just write a prompt “I want to build a todo app. Help me writing code for the homepage”.</p>
<p>You get the code, you paste it, you run and everything is working fine. You think alright good results, now let’s move on to second page, third page and so on. Suddenly, the AI hallucinates in one of the responses and you encounter a bug. Since you have written 0 lines of code, you are definately not going to debug this.</p>
<p>Next step? Copy the buggy code, paste it in the chat box and hope that the AI gives you the solution. In a lot of cases it does, but when it doesn’t it just doesn’t. You go on and on with it chatting and trying different prompts, giving it context of n number of files in the hope that it will solve it for you.</p>
<p>And when you lose all your patience, that is when you thing of debugging it for yourself and search the error on google and try to find a solution. In my experience, most of the times the problem was that the buggy code was outdated and was using functions that the latest version of framework/library/package didn’t support. Such a simple and common problem and you wasted so much time with gpt.</p>
<p>You didn’t waste time because you are not skilled to debug, you did it because you were lazy. Since you wrote 0 lines of code, you never did put in the hard work and you were never really active. Hence, you just never felt like actively debugging the code and find the solution. You think that oh i already know how to code in this language or framework, why should I write this let the AI write the code I already understand what the code does.</p>
<p>I mean debugging is an art in itself and getting your code to work after trying various methods after reading the docs or understanding what actually is wrong gives an immense satisfaction. At least it does to me.</p>
<p>So yeah, this is the big problem. We end up relying on GPT from minute 0 and in that process, we waste our time. Also, majority of the times when this happen, we end up learning nothing from the project or the work that we are doing.</p>
<h1 id="heading-the-solution">The Solution</h1>
<p>Now that we have gone over the problem, let’s look at how I changed the way I code with AI’s help.</p>
<p>First of all, I stopped writing prompts such as “Write code for this page” or “write an api”. I started looking AI as an expert reviewer instead of an expert creator.</p>
<p>Going back to the same example, what I do now is I write the code for the home page of the todo app. I then select particular parts of code, paste it in the chat box and ask GPT to review it. I then also go through the review and actually try to understand what it is trying to tell. Because, it might be that the review is not helpful so can’t blindly copy paste AI’s code again.</p>
<p>In this way, I also remember the changes GPT suggested and i learn new things as they are small changes made by AI’s review. Also, if i face a bug, I know what code I have written and since I am actively writing code, I debug the code without showing any laziness.</p>
<p>I also noticed that while writing code, i rarely paste my error output in GPT first. I go to the google search bar first and if I don’t find any help from Stack Overflow or Github issues, then I turn to GPT.</p>
<p>This helps in saving time. This also helps me up skill as I learn from my mistakes rather than making no mistakes at all and just seeing AI write my code. This also gives me the happiness of debugging my own issues.</p>
<p>This keeps me confident in my skills and makes me believe that no this AI won’t take my job as it is not the creator but the reviewer.</p>
<h1 id="heading-conclusion">Conclusion</h1>
<p>At the end of the day, the most rewarding part of being a developer is solving challenges, building something meaningful, and growing through the process.</p>
<p>When you sit to write code, you think a lot. You think of how you will place the div, how you will structure your functions, how you will create the interfaces and much more. When you make AI write code from scratch, you miss doing all this.</p>
<p>AI can be a powerful tool to help you along the way, but your unique abilities—your critical thinking, creativity, and determination—are what truly make you irreplaceable.</p>
<p>I would love to hear your views on this topic. On that note. Goodbye and Keep Coding!</p>
]]></content:encoded></item><item><title><![CDATA[Program vs Process. A deep dive into concepts of OS]]></title><description><![CDATA[Discover the differences between programs and processes, their structures, and why this knowledge is vital for developers and enthusiasts]]></description><link>https://cswithiyush.hashnode.dev/program-vs-process-a-deep-dive-into-concepts-of-os</link><guid isPermaLink="true">https://cswithiyush.hashnode.dev/program-vs-process-a-deep-dive-into-concepts-of-os</guid><category><![CDATA[operating system]]></category><category><![CDATA[Beginner Developers]]></category><category><![CDATA[Blogging]]></category><category><![CDATA[Tutorial]]></category><dc:creator><![CDATA[Ayush Pawar]]></dc:creator><pubDate>Sat, 05 Oct 2024 14:47:23 GMT</pubDate><content:encoded><![CDATA[<p>Have you ever wondered what really happens when you double-click an <code>.exe</code> file or run a command in your terminal? You see the program open and perform its tasks, but behind the scenes, a lot is happening within your computer. The terms <strong>program</strong> and <strong>process</strong> are often used interchangeably, but they represent two very different stages in the lifecycle of software execution.</p>
<p>In this post, we’re going to explore the differences between <strong>programs</strong> and <strong>processes</strong>, dissect how a process is structured, and understand why it matters for developers and computer enthusiasts alike.</p>
<hr />
<h3 id="heading-1-what-is-a-program">1. <strong>What is a Program?</strong></h3>
<p>At its simplest, a <strong>program</strong> is just a collection of instructions stored in a file. When you write a program and compile it (for instance, turning your C++ or Java code into an executable <code>.exe</code> file), this file is stored in secondary memory—your hard drive or SSD. But at this stage, it’s static. It’s just a set of instructions waiting to be used, not doing anything by itself.</p>
<p><strong>Key Takeaway</strong>: A program is inactive code sitting on disk, a blueprint of operations the computer will execute when called upon.</p>
<hr />
<h3 id="heading-2-what-is-a-process">2. <strong>What is a Process?</strong></h3>
<p>Once you click on that <code>.exe</code> file and start running the program, it gets loaded into the main memory (RAM) and becomes a <strong>process</strong>. A process is an active entity. While a program is just code, a process is an executing instance of that code.</p>
<p><strong>Think of it like this</strong>: the program is the recipe, while the process is the cooking! Until you start following the recipe (running the process), nothing gets done.</p>
<p>A <strong>process</strong> has a specific structure in memory, divided into four key parts: <strong>Code</strong>, <strong>Data</strong>, <strong>Heap</strong>, and <strong>Stack</strong>. Let's break these down.</p>
<hr />
<h3 id="heading-3-the-structure-of-a-process">3. <strong>The Structure of a Process</strong></h3>
<h4 id="heading-a-code-section">a) <strong>Code Section</strong></h4>
<p>The <strong>code section</strong> (also known as the <strong>text section</strong>) contains the actual compiled instructions of the program. This is the part of the process that holds the executable code, which tells the CPU what operations to perform.</p>
<p>For example, if you're running a program that adds two numbers, the <strong>code section</strong> contains the instructions telling the CPU how to perform the addition.</p>
<p><strong>Key Point</strong>: The code section is read-only and doesn’t change while the program runs.</p>
<hr />
<h4 id="heading-b-data-section">b) <strong>Data Section</strong></h4>
<p>The <strong>data section</strong> holds all the global and static variables defined in the program. These variables are initialized before the program starts and are accessible throughout the lifetime of the process.</p>
<p>For instance, if your program has a static counter that tracks how many times a certain function is called, this counter resides in the data section.</p>
<ul>
<li><p><strong>Global Variables</strong>: Accessible from anywhere in the program.</p>
</li>
<li><p><strong>Static Variables</strong>: Retain their value between function calls but are not global.</p>
</li>
</ul>
<p><strong>Why it matters</strong>: Understanding how data is stored and accessed allows you to better manage memory, especially in larger programs with many global or static variables.</p>
<hr />
<h4 id="heading-c-heap-section">c) <strong>Heap Section</strong></h4>
<p>The <strong>heap</strong> is used for <strong>dynamic memory allocation</strong>. This is where memory is allocated during runtime, and it’s often used for data structures like linked lists, trees, or objects in object-oriented languages.</p>
<p>Unlike the stack (which we’ll get to next), memory in the heap must be manually allocated and freed, typically using functions like <code>malloc()</code> and <code>free()</code> in C, or <code>new</code> and <code>delete</code> in languages like C++.</p>
<p><strong>Key Insight</strong>: Improper handling of heap memory can lead to memory leaks, which is why efficient memory management is crucial for performance optimization.</p>
<hr />
<h4 id="heading-d-stack-section">d) <strong>Stack Section</strong></h4>
<p>The <strong>stack</strong> handles function calls, local variables, and control flow. When a function is called, the program pushes a new "stack frame" onto the stack, containing all local variables and the return address (where the program should continue once the function is done).</p>
<p>Once the function returns, its stack frame is popped off, and control goes back to where the function was called. This temporary nature makes the stack extremely efficient, but also limited in size. If you use too much stack space (say, with deep recursion), you can run into stack overflow errors.</p>
<p><strong>Key Takeaway</strong>: The stack grows and shrinks dynamically as functions are called and return. It’s fast but needs to be managed carefully to avoid issues like stack overflows.</p>
<hr />
<h3 id="heading-4-program-vs-process-why-the-difference-matters">4. <strong>Program vs. Process: Why the Difference Matters</strong></h3>
<ul>
<li><p><strong>Concurrency</strong>: While a program is a single static file, multiple <strong>processes</strong> can run the same program simultaneously. For instance, you can open multiple tabs in a web browser, each of which runs as a separate process.</p>
</li>
<li><p><strong>Resource Management</strong>: A process takes up system resources (memory, CPU cycles), and how these resources are managed affects the performance of your machine. Developers need to understand the inner workings of processes to optimize memory usage and avoid bottlenecks.</p>
</li>
<li><p><strong>Debugging</strong>: Knowing how a process is structured makes it easier to track down bugs. For example, segmentation faults often arise from mishandling the memory in the heap or stack. Understanding these structures helps you debug more effectively.</p>
</li>
<li><p><strong>Security</strong>: The clear separation of a process into code, data, heap, and stack also improves security. Modern operating systems use techniques like Data Execution Prevention (DEP), which prevents code from being executed from the data section, to thwart malicious exploits.</p>
</li>
</ul>
<hr />
<h3 id="heading-5-conclusion-from-program-to-process">5. <strong>Conclusion: From Program to Process</strong></h3>
<p>A <strong>program</strong> is the blueprint, while a <strong>process</strong> is the living, breathing execution of that blueprint. By understanding the different parts of a process—<strong>code</strong>, <strong>data</strong>, <strong>heap</strong>, and <strong>stack</strong>—you gain insight into how programs are executed, how memory is managed, and how your machine efficiently handles multiple tasks simultaneously.</p>
<p>For developers, understanding the nuances of processes can make all the difference when it comes to optimizing performance, debugging errors, and creating more efficient software.</p>
<p>Next time you hit <strong>Run</strong> on your code, take a moment to appreciate the complexity behind the scenes!</p>
<hr />
<h3 id="heading-tldr">TL;DR</h3>
<ul>
<li><p><strong>Program</strong>: Static code on disk (.exe).</p>
</li>
<li><p><strong>Process</strong>: Active execution in memory with a structure divided into <strong>Code</strong>, <strong>Data</strong>, <strong>Heap</strong>, and <strong>Stack</strong>.</p>
</li>
<li><p>Understanding these concepts is key for optimizing performance, managing resources, and debugging.</p>
</li>
</ul>
<p>Stay curious and keep exploring! 🚀</p>
]]></content:encoded></item><item><title><![CDATA[Isolates Decoded: The Secret Weapon for Flutter Performance]]></title><description><![CDATA[Boost Flutter app performance with Dart Isolates: learn their benefits, usage, and best practices]]></description><link>https://cswithiyush.hashnode.dev/isolates-decoded-the-secret-weapon-for-flutter-performance</link><guid isPermaLink="true">https://cswithiyush.hashnode.dev/isolates-decoded-the-secret-weapon-for-flutter-performance</guid><category><![CDATA[Flutter]]></category><category><![CDATA[Mobile Development]]></category><category><![CDATA[Mobile apps]]></category><category><![CDATA[Flutter Examples]]></category><category><![CDATA[coding]]></category><dc:creator><![CDATA[Ayush Pawar]]></dc:creator><pubDate>Fri, 13 Sep 2024 14:18:47 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1726237076924/845afe40-3eec-42b7-90a2-df0feda8d30c.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h1 id="heading-introduction">Introduction</h1>
<p>In the world of Flutter development, performance is king. As applications grow more complex, developers often find themselves needing to perform heavy computations without compromising the smoothness of the user interface. Enter Dart Isolates: a powerful yet often misunderstood feature that can significantly boost your app's performance. Let's dive deep into the world of Isolates and discover how they can revolutionize your Flutter applications.</p>
<h2 id="heading-what-are-isolates">What are Isolates?</h2>
<p>In Dart, an Isolate is a separate unit of execution that runs concurrently with the main execution thread. Think of it as a lightweight thread that doesn't share memory with other Isolates. This isolation (hence the name) ensures that each Isolate can run independently without interfering with others.</p>
<h2 id="heading-why-use-isolates">Why Use Isolates?</h2>
<p>Flutter apps run on a single thread by default. This means that long-running tasks can block the UI, leading to janky animations and unresponsive interfaces. Isolates allow you to offload heavy computations to a separate thread, keeping your UI buttery smooth.</p>
<h2 id="heading-how-isolates-work">How Isolates Work</h2>
<p>Unlike traditional multi-threading models, Isolates don't share memory. Instead, they communicate through message passing. This model eliminates many common pitfalls of concurrent programming, such as race conditions and deadlocks.</p>
<p>Here's a basic example of how to spawn and use an Isolate:</p>
<pre><code class="lang-dart"><span class="hljs-keyword">import</span> <span class="hljs-string">'dart:isolate'</span>;

<span class="hljs-keyword">void</span> heavyComputation(SendPort sendPort) {
  <span class="hljs-comment">// Simulate a long running task</span>
  <span class="hljs-built_in">int</span> sum = <span class="hljs-number">0</span>;
  <span class="hljs-keyword">for</span> (<span class="hljs-built_in">int</span> i = <span class="hljs-number">0</span>; i &lt; <span class="hljs-number">1000000000</span>; i++) {
    sum += i;
  }
  sendPort.send(sum);
}

Future&lt;<span class="hljs-keyword">void</span>&gt; main() <span class="hljs-keyword">async</span> {
  <span class="hljs-keyword">final</span> receivePort = ReceivePort();
  <span class="hljs-keyword">await</span> Isolate.spawn(heavyComputation, receivePort.sendPort);

  <span class="hljs-keyword">final</span> result = <span class="hljs-keyword">await</span> receivePort.first;
  <span class="hljs-built_in">print</span>(<span class="hljs-string">'The result is: <span class="hljs-subst">$result</span>'</span>);
}
</code></pre>
<p>In this example, we spawn a new Isolate to perform a computationally intensive task without blocking the main thread.</p>
<h2 id="heading-isolates-in-flutter">Isolates in Flutter</h2>
<p>While the above example works in plain Dart, Flutter provides a more convenient way to work with Isolates through the <code>compute</code> function:</p>
<pre><code class="lang-dart"><span class="hljs-keyword">import</span> <span class="hljs-string">'package:flutter/foundation.dart'</span>;

<span class="hljs-built_in">int</span> heavyComputation(<span class="hljs-built_in">int</span> iterations) {
  <span class="hljs-built_in">int</span> sum = <span class="hljs-number">0</span>;
  <span class="hljs-keyword">for</span> (<span class="hljs-built_in">int</span> i = <span class="hljs-number">0</span>; i &lt; iterations; i++) {
    sum += i;
  }
  <span class="hljs-keyword">return</span> sum;
}

<span class="hljs-keyword">void</span> main() <span class="hljs-keyword">async</span> {
  <span class="hljs-keyword">final</span> result = <span class="hljs-keyword">await</span> compute(heavyComputation, <span class="hljs-number">1000000000</span>);
  <span class="hljs-built_in">print</span>(<span class="hljs-string">'The result is: <span class="hljs-subst">$result</span>'</span>);
}
</code></pre>
<p>The <code>compute</code> function handles the creation and communication with the Isolate for you, making it easier to offload work to a background thread.</p>
<h2 id="heading-advanced-isolate-techniques">Advanced Isolate Techniques</h2>
<h3 id="heading-1-long-living-isolates">1. Long-Living Isolates</h3>
<p>Sometimes, you might need an Isolate that lives throughout the app's lifecycle:</p>
<pre><code class="lang-dart"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">IsolateManager</span> </span>{
  Isolate? _isolate;
  <span class="hljs-keyword">late</span> ReceivePort _receivePort;
  <span class="hljs-keyword">late</span> SendPort _sendPort;

  Future&lt;<span class="hljs-keyword">void</span>&gt; init() <span class="hljs-keyword">async</span> {
    _receivePort = ReceivePort();
    _isolate = <span class="hljs-keyword">await</span> Isolate.spawn(_isolateEntry, _receivePort.sendPort);
    _sendPort = <span class="hljs-keyword">await</span> _receivePort.first;
  }

  <span class="hljs-keyword">static</span> <span class="hljs-keyword">void</span> _isolateEntry(SendPort sendPort) {
    <span class="hljs-keyword">final</span> receivePort = ReceivePort();
    sendPort.send(receivePort.sendPort);

    receivePort.listen((message) {
      <span class="hljs-comment">// Handle incoming messages</span>
    });
  }

  <span class="hljs-keyword">void</span> dispose() {
    _receivePort.close();
    _isolate?.kill();
  }
}
</code></pre>
<h3 id="heading-2-handling-errors-in-isolates">2. Handling Errors in Isolates</h3>
<p>Error handling is crucial when working with Isolates:</p>
<pre><code class="lang-dart"><span class="hljs-keyword">void</span> runIsolate() <span class="hljs-keyword">async</span> {
  <span class="hljs-keyword">final</span> receivePort = ReceivePort();
  <span class="hljs-keyword">final</span> errorPort = ReceivePort();

  <span class="hljs-keyword">try</span> {
    <span class="hljs-keyword">await</span> Isolate.spawn(
      _isolateFunction, 
      receivePort.sendPort,
      onError: errorPort.sendPort,
    );

    errorPort.listen((error) {
      <span class="hljs-built_in">print</span>(<span class="hljs-string">'Error in isolate: <span class="hljs-subst">$error</span>'</span>);
    });

    <span class="hljs-comment">// Rest of your code</span>
  } <span class="hljs-keyword">catch</span> (e) {
    <span class="hljs-built_in">print</span>(<span class="hljs-string">'Error spawning isolate: <span class="hljs-subst">$e</span>'</span>);
  }
}
</code></pre>
<h3 id="heading-3-passing-complex-data">3. Passing Complex Data</h3>
<p>While Isolates can't share memory, you can pass complex data by carefully structuring your messages:</p>
<pre><code class="lang-dart"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">ComplexMessage</span> </span>{
  <span class="hljs-keyword">final</span> <span class="hljs-built_in">int</span> id;
  <span class="hljs-keyword">final</span> <span class="hljs-built_in">String</span> data;
  <span class="hljs-keyword">final</span> <span class="hljs-built_in">List</span>&lt;<span class="hljs-built_in">int</span>&gt; numbers;

  ComplexMessage(<span class="hljs-keyword">this</span>.id, <span class="hljs-keyword">this</span>.data, <span class="hljs-keyword">this</span>.numbers);
}

<span class="hljs-keyword">void</span> isolateFunction(SendPort sendPort) {
  <span class="hljs-keyword">final</span> receivePort = ReceivePort();
  sendPort.send(receivePort.sendPort);

  receivePort.listen((message) {
    <span class="hljs-keyword">if</span> (message <span class="hljs-keyword">is</span> ComplexMessage) {
      <span class="hljs-comment">// Process the complex message</span>
    }
  });
}
</code></pre>
<h2 id="heading-best-practices-and-considerations">Best Practices and Considerations</h2>
<ol>
<li><p><strong>Use Isolates Judiciously</strong>: Not every operation needs an Isolate. Use them for computationally intensive tasks that might block the UI.</p>
</li>
<li><p><strong>Be Mindful of Communication Overhead</strong>: While Isolates are powerful, the message passing between Isolates does have some overhead. For very short tasks, this overhead might outweigh the benefits.</p>
</li>
<li><p><strong>Lifecycle Management</strong>: Always properly dispose of Isolates when they're no longer needed to prevent memory leaks.</p>
</li>
<li><p><strong>State Management</strong>: Remember that Isolates can't access your app's state directly. Design your architecture to handle this limitation.</p>
</li>
<li><p><strong>Platform Channels</strong>: When using platform-specific code, be aware that Isolates might not have access to the same platform channel instances as your main Isolate.</p>
</li>
</ol>
<h2 id="heading-conclusion">Conclusion</h2>
<p>Dart Isolates offer a powerful way to handle concurrency in Flutter applications. By leveraging Isolates, you can keep your UI responsive while performing heavy computations in the background. While they require careful management, the performance benefits can be substantial.</p>
<p>As you continue to develop more complex Flutter applications, keep Isolates in your toolkit. They might just be the key to unlocking the next level of performance in your apps.</p>
]]></content:encoded></item><item><title><![CDATA[The Scope of Closure: A JavaScript Romance]]></title><description><![CDATA[Understanding JavaScript's closures and lexical scoping to write powerful, flexible code]]></description><link>https://cswithiyush.hashnode.dev/the-scope-of-closure-a-javascript-romance</link><guid isPermaLink="true">https://cswithiyush.hashnode.dev/the-scope-of-closure-a-javascript-romance</guid><category><![CDATA[JavaScript]]></category><category><![CDATA[Web Development]]></category><category><![CDATA[javascript framework]]></category><category><![CDATA[Beginner Developers]]></category><dc:creator><![CDATA[Ayush Pawar]]></dc:creator><pubDate>Thu, 05 Sep 2024 15:57:35 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1725551820673/2ece29e3-5cc2-4ac4-8709-05981d318c9a.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h1 id="heading-introduction">Introduction</h1>
<p>In the world of JavaScript, closures and lexical scoping are like two dancers in an intricate tango. They're distinct concepts, but they move together in such harmony that understanding one deeply enhances your grasp of the other. Let's dive into this fascinating relationship and see how it shapes the JavaScript landscape.</p>
<h2 id="heading-lexical-scoping-setting-the-stage">Lexical Scoping: Setting the Stage</h2>
<p>Before we can fully appreciate closures, we need to understand lexical scoping. In JavaScript, lexical scoping (also known as static scoping) means that the scope of a variable is determined by its location within the source code.</p>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">outer</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">const</span> message = <span class="hljs-string">"Hello, "</span>;

  <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">inner</span>(<span class="hljs-params">name</span>) </span>{
    <span class="hljs-built_in">console</span>.log(message + name);
  }

  <span class="hljs-keyword">return</span> inner;
}

<span class="hljs-keyword">const</span> greet = outer();
greet(<span class="hljs-string">"Alice"</span>); <span class="hljs-comment">// Outputs: "Hello, Alice"</span>
</code></pre>
<p>In this example, the <code>inner</code> function has access to the <code>message</code> variable from its outer scope. This is lexical scoping in action. The scope is determined at the time of function definition, not at the time of function execution.</p>
<h2 id="heading-enter-closures-the-dance-begins">Enter Closures: The Dance Begins</h2>
<p>A closure is created when a function is defined within another function, allowing the inner function to access variables from the outer function's scope. This is where the magic happens, and the relationship with lexical scoping becomes clear.</p>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">createCounter</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">let</span> count = <span class="hljs-number">0</span>;

  <span class="hljs-keyword">return</span> <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params"></span>) </span>{
    count++;
    <span class="hljs-built_in">console</span>.log(count);
  };
}

<span class="hljs-keyword">const</span> counter = createCounter();
counter(); <span class="hljs-comment">// Outputs: 1</span>
counter(); <span class="hljs-comment">// Outputs: 2</span>
</code></pre>
<p>In this example, the returned function forms a closure. It "closes over" the <code>count</code> variable, maintaining access to it even after <code>createCounter</code> has finished executing.</p>
<h2 id="heading-the-symbiosis-of-closures-and-lexical-scoping">The Symbiosis of Closures and Lexical Scoping</h2>
<p>The relationship between closures and lexical scoping can be understood through several key points:</p>
<ol>
<li><p><strong>Preservation of Scope</strong>: Lexical scoping determines what variables are accessible, while closures preserve that scope, allowing functions to maintain access to variables from their lexical scope even when executed in a different scope.</p>
</li>
<li><p><strong>Encapsulation</strong>: Closures leverage lexical scoping to create private state. Variables in the outer function are not directly accessible from outside, providing a form of data privacy.</p>
<pre><code class="lang-javascript"> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">createBank</span>(<span class="hljs-params"></span>) </span>{
   <span class="hljs-keyword">let</span> balance = <span class="hljs-number">0</span>;

   <span class="hljs-keyword">return</span> {
     <span class="hljs-attr">deposit</span>: <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">amount</span>) </span>{
       balance += amount;
     },
     <span class="hljs-attr">getBalance</span>: <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params"></span>) </span>{
       <span class="hljs-keyword">return</span> balance;
     }
   };
 }

 <span class="hljs-keyword">const</span> myAccount = createBank();
 myAccount.deposit(<span class="hljs-number">100</span>);
 <span class="hljs-built_in">console</span>.log(myAccount.getBalance()); <span class="hljs-comment">// 100</span>
 <span class="hljs-built_in">console</span>.log(myAccount.balance); <span class="hljs-comment">// undefined</span>
</code></pre>
</li>
<li><p><strong>Function Factories</strong>: The combination of lexical scoping and closures allows for powerful function factories, where functions can be created with customized behavior based on their creation context.</p>
<pre><code class="lang-javascript"> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">multiply</span>(<span class="hljs-params">x</span>) </span>{
   <span class="hljs-keyword">return</span> <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">y</span>) </span>{
     <span class="hljs-keyword">return</span> x * y;
   };
 }

 <span class="hljs-keyword">const</span> double = multiply(<span class="hljs-number">2</span>);
 <span class="hljs-built_in">console</span>.log(double(<span class="hljs-number">5</span>)); <span class="hljs-comment">// 10</span>
</code></pre>
</li>
<li><p><strong>Maintaining State</strong>: Closures can maintain state between function calls, thanks to lexical scoping. This is particularly useful for creating stateful functions without relying on global variables.</p>
<pre><code class="lang-javascript"> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">createLogger</span>(<span class="hljs-params">prefix</span>) </span>{
   <span class="hljs-keyword">let</span> logCount = <span class="hljs-number">0</span>;

   <span class="hljs-keyword">return</span> <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">message</span>) </span>{
     logCount++;
     <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`<span class="hljs-subst">${prefix}</span> (<span class="hljs-subst">${logCount}</span>): <span class="hljs-subst">${message}</span>`</span>);
   };
 }

 <span class="hljs-keyword">const</span> log = createLogger(<span class="hljs-string">"MyApp"</span>);
 log(<span class="hljs-string">"Started"</span>); <span class="hljs-comment">// MyApp (1): Started</span>
 log(<span class="hljs-string">"Running"</span>); <span class="hljs-comment">// MyApp (2): Running</span>
</code></pre>
</li>
<li><p><strong>Lexical</strong> <code>this</code>: Arrow functions in JavaScript use lexical scoping for the <code>this</code> keyword, which interplays with closures in interesting ways.</p>
<pre><code class="lang-javascript"> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">Person</span>(<span class="hljs-params">name</span>) </span>{
   <span class="hljs-built_in">this</span>.name = name;

   <span class="hljs-built_in">this</span>.greet = <span class="hljs-function">() =&gt;</span> {
     <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`Hello, I'm <span class="hljs-subst">${<span class="hljs-built_in">this</span>.name}</span>`</span>);
   };
 }

 <span class="hljs-keyword">const</span> alice = <span class="hljs-keyword">new</span> Person(<span class="hljs-string">"Alice"</span>);
 <span class="hljs-keyword">const</span> greet = alice.greet;
 greet(); <span class="hljs-comment">// Still outputs: "Hello, I'm Alice"</span>
</code></pre>
</li>
</ol>
<h2 id="heading-potential-pitfalls">Potential Pitfalls</h2>
<p>While the relationship between closures and lexical scoping is powerful, it can lead to some confusion:</p>
<ol>
<li><p><strong>Memory Leaks</strong>: Closures keep the entire lexical scope alive. If not managed properly, this can lead to unexpected memory consumption.</p>
</li>
<li><p><strong>Loop Variables in Closures</strong>: A common gotcha involves creating closures in loops.</p>
<pre><code class="lang-javascript"> <span class="hljs-keyword">for</span> (<span class="hljs-keyword">var</span> i = <span class="hljs-number">0</span>; i &lt; <span class="hljs-number">3</span>; i++) {
   <span class="hljs-built_in">setTimeout</span>(<span class="hljs-function">() =&gt;</span> <span class="hljs-built_in">console</span>.log(i), <span class="hljs-number">100</span>);
 }
 <span class="hljs-comment">// Outputs: 3, 3, 3 (not 0, 1, 2 as might be expected)</span>
</code></pre>
<p> This is because the closures all share the same lexical scope. Using <code>let</code> instead of <code>var</code> or creating a new scope for each iteration solves this issue.</p>
</li>
</ol>
<h2 id="heading-conclusion">Conclusion</h2>
<p>The relationship between closures and lexical scoping is at the heart of many JavaScript patterns and features. Lexical scoping provides the rules for variable accessibility, while closures leverage these rules to create powerful, flexible, and encapsulated code structures.</p>
<p>Understanding this relationship not only helps in writing more effective JavaScript code but also in appreciating the elegant design of the language itself. As you continue to explore JavaScript, you'll find that this dance between closures and lexical scoping underpins many advanced techniques and libraries in the ecosystem.</p>
<p>By mastering these concepts, you're not just learning language features – you're gaining insight into the fundamental principles that make JavaScript a uniquely powerful and flexible programming language.</p>
]]></content:encoded></item><item><title><![CDATA[Behind the Scenes Heroes: How Web Workers Supercharge Your JavaScript]]></title><description><![CDATA[Learn how Web Workers improve JavaScript performance, enabling multi-threading for seamless and efficient browser-based applications]]></description><link>https://cswithiyush.hashnode.dev/behind-the-scenes-heroes-how-web-workers-supercharge-your-javascript</link><guid isPermaLink="true">https://cswithiyush.hashnode.dev/behind-the-scenes-heroes-how-web-workers-supercharge-your-javascript</guid><category><![CDATA[JavaScript]]></category><category><![CDATA[Web Development]]></category><category><![CDATA[js]]></category><category><![CDATA[Beginner Developers]]></category><category><![CDATA[Tutorial]]></category><dc:creator><![CDATA[Ayush Pawar]]></dc:creator><pubDate>Wed, 14 Aug 2024 04:30:50 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1723567174682/7537b8e0-bd71-4e3b-9d2f-28ea39e6488c.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h1 id="heading-introduction">Introduction</h1>
<p>JavaScript has long been known as a single-threaded language, which can sometimes lead to performance bottlenecks, especially when dealing with CPU-intensive tasks. Enter Web Workers: a powerful yet often overlooked feature that brings multi-threading capabilities to JavaScript in the browser.</p>
<h2 id="heading-what-are-web-workers">What are Web Workers?</h2>
<p>Web Workers allow you to run scripts in background threads, separate from the main execution thread of a web application. This means you can perform heavy computations without freezing or slowing down the user interface.</p>
<h2 id="heading-types-of-web-workers">Types of Web Workers</h2>
<ol>
<li><p><strong>Dedicated Workers</strong>: The most common type, used by a single script.</p>
</li>
<li><p><strong>Shared Workers</strong>: Can be accessed by multiple scripts from different windows, iframes, etc.</p>
</li>
<li><p><strong>Service Workers</strong>: Act as proxy servers between web applications, the browser, and the network.</p>
</li>
</ol>
<p>In this post, we'll focus primarily on Dedicated Workers.</p>
<h2 id="heading-creating-a-web-worker">Creating a Web Worker</h2>
<p>Here's a simple example of how to create and use a Web Worker:</p>
<pre><code class="lang-javascript"><span class="hljs-comment">// main.js</span>
<span class="hljs-keyword">const</span> worker = <span class="hljs-keyword">new</span> Worker(<span class="hljs-string">'worker.js'</span>);

worker.postMessage(<span class="hljs-string">'Hello, Worker!'</span>);

worker.onmessage = <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">e</span>) </span>{
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'Message received from worker:'</span>, e.data);
};

<span class="hljs-comment">// worker.js</span>
self.onmessage = <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">e</span>) </span>{
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'Message received from main script:'</span>, e.data);
  self.postMessage(<span class="hljs-string">'Hello, Main script!'</span>);
};
</code></pre>
<p>In this example, we create a new worker that runs the script in <code>worker.js</code>. We can send messages to the worker using <code>postMessage()</code> and listen for messages from the worker using the <code>onmessage</code> event handler.</p>
<h2 id="heading-use-cases-for-web-workers">Use Cases for Web Workers</h2>
<ol>
<li><p><strong>Complex Calculations</strong>: Perform heavy mathematical operations without freezing the UI.</p>
</li>
<li><p><strong>Data Processing</strong>: Handle large datasets, sorting, or filtering operations.</p>
</li>
<li><p><strong>Image/Video Processing</strong>: Apply filters or effects to media without impacting page responsiveness.</p>
</li>
<li><p><strong>Real-time Data Analysis</strong>: Process streaming data in the background.</p>
</li>
</ol>
<p>Let's look at a more practical example. Suppose we want to calculate prime numbers up to a given limit:</p>
<pre><code class="lang-javascript"><span class="hljs-comment">// main.js</span>
<span class="hljs-keyword">const</span> worker = <span class="hljs-keyword">new</span> Worker(<span class="hljs-string">'primeWorker.js'</span>);

<span class="hljs-built_in">document</span>.getElementById(<span class="hljs-string">'calculateBtn'</span>).addEventListener(<span class="hljs-string">'click'</span>, <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">const</span> limit = <span class="hljs-built_in">document</span>.getElementById(<span class="hljs-string">'limit'</span>).value;
  worker.postMessage(<span class="hljs-built_in">parseInt</span>(limit));
});

worker.onmessage = <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">e</span>) </span>{
  <span class="hljs-built_in">document</span>.getElementById(<span class="hljs-string">'result'</span>).textContent = <span class="hljs-string">`Found <span class="hljs-subst">${e.data}</span> prime numbers`</span>;
};

<span class="hljs-comment">// primeWorker.js</span>
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">isPrime</span>(<span class="hljs-params">n</span>) </span>{
  <span class="hljs-keyword">for</span> (<span class="hljs-keyword">let</span> i = <span class="hljs-number">2</span>; i &lt;= <span class="hljs-built_in">Math</span>.sqrt(n); i++) {
    <span class="hljs-keyword">if</span> (n % i === <span class="hljs-number">0</span>) <span class="hljs-keyword">return</span> <span class="hljs-literal">false</span>;
  }
  <span class="hljs-keyword">return</span> n &gt; <span class="hljs-number">1</span>;
}

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">countPrimes</span>(<span class="hljs-params">limit</span>) </span>{
  <span class="hljs-keyword">let</span> count = <span class="hljs-number">0</span>;
  <span class="hljs-keyword">for</span> (<span class="hljs-keyword">let</span> i = <span class="hljs-number">2</span>; i &lt;= limit; i++) {
    <span class="hljs-keyword">if</span> (isPrime(i)) count++;
  }
  <span class="hljs-keyword">return</span> count;
}

self.onmessage = <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">e</span>) </span>{
  <span class="hljs-keyword">const</span> limit = e.data;
  <span class="hljs-keyword">const</span> primeCount = countPrimes(limit);
  self.postMessage(primeCount);
};
</code></pre>
<p>In this example, the potentially time-consuming task of counting prime numbers is offloaded to a Web Worker, ensuring that the main thread remains responsive.</p>
<h2 id="heading-limitations-of-web-workers">Limitations of Web Workers</h2>
<p>While powerful, Web Workers do have some limitations:</p>
<ol>
<li><p>No access to the DOM</p>
</li>
<li><p>Limited access to some Web APIs</p>
</li>
<li><p>No shared memory with the main thread (though <code>SharedArrayBuffer</code> offers some possibilities)</p>
</li>
<li><p>Additional overhead in creation and message passing</p>
</li>
</ol>
<h2 id="heading-best-practices">Best Practices</h2>
<ol>
<li><p>Use Workers for CPU-intensive tasks that don't require DOM access.</p>
</li>
<li><p>Keep message passing to a minimum to reduce overhead.</p>
</li>
<li><p>Consider using transferable objects for large data to avoid copying.</p>
</li>
<li><p>Terminate workers when they're no longer needed to free up resources.</p>
</li>
</ol>
<h2 id="heading-browser-support-and-fallbacks">Browser Support and Fallbacks</h2>
<p>Web Workers are supported in all modern browsers, but it's always good to check and provide fallbacks:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">if</span> (<span class="hljs-keyword">typeof</span>(Worker) !== <span class="hljs-string">"undefined"</span>) {
  <span class="hljs-comment">// Web Workers are supported</span>
  <span class="hljs-comment">// ... your worker code here ...</span>
} <span class="hljs-keyword">else</span> {
  <span class="hljs-comment">// Fallback to single-threaded execution</span>
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Web Workers are not supported in this browser"</span>);
}
</code></pre>
<h2 id="heading-conclusion">Conclusion</h2>
<p>Web Workers open up new possibilities for creating high-performance web applications by allowing true multi-threading in JavaScript. While they may not be necessary for every project, understanding and utilizing Web Workers can significantly enhance the user experience in complex, computation-heavy web applications.</p>
<p>As web applications continue to grow in complexity, Web Workers will likely play an increasingly important role in maintaining smooth, responsive user interfaces while handling intensive background tasks.</p>
<hr />
<h1 id="heading-catchy-title-suggestions">Catchy Title Suggestions</h1>
]]></content:encoded></item><item><title><![CDATA[Yield to the Future: Exploring JavaScript Generators and Iterators]]></title><description><![CDATA[Use JavaScript generators and iterators for complex data, infinite sequences, and async operations to boost code efficiency and readability]]></description><link>https://cswithiyush.hashnode.dev/yield-to-the-future-exploring-javascript-generators-and-iterators</link><guid isPermaLink="true">https://cswithiyush.hashnode.dev/yield-to-the-future-exploring-javascript-generators-and-iterators</guid><category><![CDATA[JavaScript]]></category><category><![CDATA[javascript framework]]></category><category><![CDATA[Web Development]]></category><category><![CDATA[Tutorial]]></category><category><![CDATA[Programming Blogs]]></category><dc:creator><![CDATA[Ayush Pawar]]></dc:creator><pubDate>Sun, 11 Aug 2024 04:30:33 GMT</pubDate><content:encoded><![CDATA[<h1 id="heading-introduction">Introduction</h1>
<p>In the vast landscape of JavaScript features, Generators and Iterators often fly under the radar. However, these powerful tools can significantly enhance your code's efficiency and readability, especially when dealing with complex data structures or asynchronous operations. Let's dive into this fascinating world!</p>
<h2 id="heading-what-are-iterators">What are Iterators?</h2>
<p>An iterator is an object that defines a <code>next()</code> method which returns an object with two properties: <code>value</code> (the next value in the sequence) and <code>done</code> (a boolean indicating if the sequence is finished).</p>
<p>Here's a simple example of a custom iterator:</p>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">numberIterator</span>(<span class="hljs-params">start = <span class="hljs-number">0</span>, end = Infinity, step = <span class="hljs-number">1</span></span>) </span>{
  <span class="hljs-keyword">let</span> nextIndex = start;
  <span class="hljs-keyword">let</span> iterationCount = <span class="hljs-number">0</span>;

  <span class="hljs-keyword">return</span> {
    <span class="hljs-attr">next</span>: <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params"></span>) </span>{
      <span class="hljs-keyword">if</span> (nextIndex &lt; end) {
        <span class="hljs-keyword">let</span> result = { <span class="hljs-attr">value</span>: nextIndex, <span class="hljs-attr">done</span>: <span class="hljs-literal">false</span> }
        nextIndex += step;
        iterationCount++;
        <span class="hljs-keyword">return</span> result;
      }
      <span class="hljs-keyword">return</span> { <span class="hljs-attr">value</span>: iterationCount, <span class="hljs-attr">done</span>: <span class="hljs-literal">true</span> }
    }
  };
}

<span class="hljs-keyword">const</span> it = numberIterator(<span class="hljs-number">1</span>, <span class="hljs-number">10</span>, <span class="hljs-number">2</span>);
<span class="hljs-built_in">console</span>.log(it.next()); <span class="hljs-comment">// { value: 1, done: false }</span>
<span class="hljs-built_in">console</span>.log(it.next()); <span class="hljs-comment">// { value: 3, done: false }</span>
<span class="hljs-built_in">console</span>.log(it.next()); <span class="hljs-comment">// { value: 5, done: false }</span>
<span class="hljs-built_in">console</span>.log(it.next()); <span class="hljs-comment">// { value: 7, done: false }</span>
<span class="hljs-built_in">console</span>.log(it.next()); <span class="hljs-comment">// { value: 9, done: false }</span>
<span class="hljs-built_in">console</span>.log(it.next()); <span class="hljs-comment">// { value: 5, done: true }</span>
</code></pre>
<p>In this example, <code>numberIterator</code> creates an iterator that yields numbers from <code>start</code> to <code>end</code> (exclusive) with a given <code>step</code>.</p>
<h2 id="heading-enter-generators">Enter Generators</h2>
<p>Generators provide a powerful alternative way to define iterators. They are special functions that can be paused and resumed, making it easier to define complex sequences.</p>
<p>Here's the same number sequence implemented as a generator:</p>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span>* <span class="hljs-title">numberGenerator</span>(<span class="hljs-params">start = <span class="hljs-number">0</span>, end = Infinity, step = <span class="hljs-number">1</span></span>) </span>{
  <span class="hljs-keyword">let</span> iterationCount = <span class="hljs-number">0</span>;
  <span class="hljs-keyword">for</span> (<span class="hljs-keyword">let</span> i = start; i &lt; end; i += step) {
    iterationCount++;
    <span class="hljs-keyword">yield</span> i;
  }
  <span class="hljs-keyword">return</span> iterationCount;
}

<span class="hljs-keyword">const</span> gen = numberGenerator(<span class="hljs-number">1</span>, <span class="hljs-number">10</span>, <span class="hljs-number">2</span>);
<span class="hljs-built_in">console</span>.log(gen.next()); <span class="hljs-comment">// { value: 1, done: false }</span>
<span class="hljs-built_in">console</span>.log(gen.next()); <span class="hljs-comment">// { value: 3, done: false }</span>
<span class="hljs-built_in">console</span>.log(gen.next()); <span class="hljs-comment">// { value: 5, done: false }</span>
<span class="hljs-built_in">console</span>.log(gen.next()); <span class="hljs-comment">// { value: 7, done: false }</span>
<span class="hljs-built_in">console</span>.log(gen.next()); <span class="hljs-comment">// { value: 9, done: false }</span>
<span class="hljs-built_in">console</span>.log(gen.next()); <span class="hljs-comment">// { value: 5, done: true }</span>
</code></pre>
<p>Note the <code>function*</code> syntax and the <code>yield</code> keyword. Each <code>yield</code> statement pauses the function and returns the yielded value.</p>
<h2 id="heading-why-use-generators">Why Use Generators?</h2>
<ol>
<li><p><strong>Memory Efficiency</strong>: Generators compute values on-demand, which can save memory when working with large datasets.</p>
</li>
<li><p><strong>Infinite Sequences</strong>: You can represent infinite sequences without running out of memory.</p>
</li>
<li><p><strong>Simplified Asynchronous Code</strong>: Generators can make asynchronous code look and behave like synchronous code.</p>
</li>
</ol>
<p>Let's look at a more complex example that demonstrates these benefits:</p>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span>* <span class="hljs-title">fibonacciGenerator</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">let</span> prev = <span class="hljs-number">0</span>, curr = <span class="hljs-number">1</span>;
  <span class="hljs-keyword">while</span> (<span class="hljs-literal">true</span>) {
    <span class="hljs-keyword">yield</span> curr;
    [prev, curr] = [curr, prev + curr];
  }
}

<span class="hljs-keyword">const</span> fib = fibonacciGenerator();
<span class="hljs-keyword">for</span> (<span class="hljs-keyword">let</span> i = <span class="hljs-number">0</span>; i &lt; <span class="hljs-number">10</span>; i++) {
  <span class="hljs-built_in">console</span>.log(fib.next().value);
}
</code></pre>
<p>This generator produces an infinite Fibonacci sequence without consuming infinite memory!</p>
<h2 id="heading-asynchronous-generators">Asynchronous Generators</h2>
<p>Generators really shine when dealing with asynchronous operations. Here's an example of an async generator that fetches data from an API:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">async</span> <span class="hljs-function"><span class="hljs-keyword">function</span>* <span class="hljs-title">fetchCommits</span>(<span class="hljs-params">repo</span>) </span>{
  <span class="hljs-keyword">let</span> url = <span class="hljs-string">`https://api.github.com/repos/<span class="hljs-subst">${repo}</span>/commits`</span>;
  <span class="hljs-keyword">while</span> (url) {
    <span class="hljs-keyword">const</span> response = <span class="hljs-keyword">await</span> fetch(url);
    <span class="hljs-keyword">const</span> body = <span class="hljs-keyword">await</span> response.json();
    <span class="hljs-keyword">yield</span>* body;
    url = getNextPage(response.headers.get(<span class="hljs-string">'Link'</span>));
  }
}

<span class="hljs-comment">// Helper function to parse 'Link' header and get the next page URL</span>
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">getNextPage</span>(<span class="hljs-params">link</span>) </span>{
  <span class="hljs-keyword">if</span> (!link) <span class="hljs-keyword">return</span> <span class="hljs-literal">null</span>;
  <span class="hljs-keyword">const</span> nextLink = link.split(<span class="hljs-string">','</span>).find(<span class="hljs-function"><span class="hljs-params">s</span> =&gt;</span> s.includes(<span class="hljs-string">'rel="next"'</span>));
  <span class="hljs-keyword">if</span> (!nextLink) <span class="hljs-keyword">return</span> <span class="hljs-literal">null</span>;
  <span class="hljs-keyword">return</span> nextLink.trim().split(<span class="hljs-string">';'</span>)[<span class="hljs-number">0</span>].slice(<span class="hljs-number">1</span>, <span class="hljs-number">-1</span>);
}

<span class="hljs-comment">// Usage</span>
(<span class="hljs-keyword">async</span> () =&gt; {
  <span class="hljs-keyword">const</span> commits = fetchCommits(<span class="hljs-string">'microsoft/typescript'</span>);
  <span class="hljs-keyword">for</span> <span class="hljs-keyword">await</span> (<span class="hljs-keyword">const</span> commit <span class="hljs-keyword">of</span> commits) {
    <span class="hljs-built_in">console</span>.log(commit.sha);
    <span class="hljs-keyword">if</span> (someCondition) <span class="hljs-keyword">break</span>;  <span class="hljs-comment">// We can exit early if needed</span>
  }
})();
</code></pre>
<p>This async generator fetches commits from a GitHub repository, automatically handling pagination. It yields each commit as it's fetched, allowing you to process commits one by one without waiting for all pages to load.</p>
<h2 id="heading-conclusion">Conclusion</h2>
<p>Generators and iterators are powerful tools in JavaScript that can help you write more efficient and expressive code. They're particularly useful for working with sequences (finite or infinite), implementing custom iterables, and simplifying asynchronous code.</p>
<p>While they might not be needed in every project, understanding generators and iterators can significantly expand your JavaScript toolkit. They're especially valuable when dealing with large datasets, complex sequences, or when you need fine-grained control over iteration and asynchronous operations.</p>
<p>As you continue to explore JavaScript, keep generators and iterators in mind. You might be surprised at how often they can provide elegant solutions to complex problems!</p>
]]></content:encoded></item><item><title><![CDATA[JavaScript BigInt: Handling Astronomical Numbers with Precision]]></title><description><![CDATA[Learn about JavaScript BigInt and how it provides precise handling of large integers for financial calculations, cryptography, and more]]></description><link>https://cswithiyush.hashnode.dev/javascript-bigint-handling-astronomical-numbers-with-precision</link><guid isPermaLink="true">https://cswithiyush.hashnode.dev/javascript-bigint-handling-astronomical-numbers-with-precision</guid><category><![CDATA[JavaScript]]></category><category><![CDATA[javascript framework]]></category><category><![CDATA[Beginner Developers]]></category><category><![CDATA[Programming Blogs]]></category><category><![CDATA[Web Development]]></category><dc:creator><![CDATA[Ayush Pawar]]></dc:creator><pubDate>Thu, 08 Aug 2024 04:30:56 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1723030858089/4d79959d-d755-4ba0-899e-1f581bb5f74a.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h2 id="heading-introduction">Introduction</h2>
<p>In the vast universe of JavaScript, there's a new star shining bright: BigInt. Introduced in ES2020, BigInt is a built-in object that allows you to work with integers of arbitrary precision. If you've ever hit the ceiling of <code>Number.MAX_SAFE_INTEGER</code> (9,007,199,254,740,991) or needed to perform calculations with astronomical figures, BigInt is here to save the day.</p>
<h2 id="heading-the-problem-bigint-solves">The Problem BigInt Solves</h2>
<p>Before we dive into BigInt, let's understand why it's needed. JavaScript traditionally uses the <code>Number</code> type to represent both integers and floating-point numbers. This type is based on the IEEE 754 double-precision floating-point format, which can precisely represent integers up to 2^53 - 1. Beyond this, you start to lose precision.</p>
<pre><code class="lang-javascript"><span class="hljs-built_in">console</span>.log(<span class="hljs-number">9007199254740991</span> + <span class="hljs-number">1</span>); <span class="hljs-comment">// 9007199254740992</span>
<span class="hljs-built_in">console</span>.log(<span class="hljs-number">9007199254740991</span> + <span class="hljs-number">2</span>); <span class="hljs-comment">// 9007199254740992 (Oops!)</span>
</code></pre>
<p>This limitation can be a significant problem in fields like finance, cryptography, or when working with very large datasets.</p>
<h2 id="heading-enter-bigint">Enter BigInt</h2>
<p>BigInt allows you to represent integers with arbitrary precision. Here's how you can create a BigInt:</p>
<pre><code class="lang-javascript"><span class="hljs-comment">// Using the BigInt() function</span>
<span class="hljs-keyword">let</span> bigInt = BigInt(<span class="hljs-number">9007199254740991</span>);

<span class="hljs-comment">// Or by appending 'n' to an integer literal</span>
<span class="hljs-keyword">let</span> anotherBigInt = <span class="hljs-number">9007199254740991n</span>;

<span class="hljs-built_in">console</span>.log(bigInt === anotherBigInt); <span class="hljs-comment">// true</span>
</code></pre>
<p>Now, let's see BigInt in action:</p>
<pre><code class="lang-javascript"><span class="hljs-built_in">console</span>.log(<span class="hljs-number">9007199254740991n</span> + <span class="hljs-number">1n</span>); <span class="hljs-comment">// 9007199254740992n</span>
<span class="hljs-built_in">console</span>.log(<span class="hljs-number">9007199254740991n</span> + <span class="hljs-number">2n</span>); <span class="hljs-comment">// 9007199254740993n (Correct!)</span>
</code></pre>
<h2 id="heading-working-with-bigint">Working with BigInt</h2>
<h3 id="heading-basic-operations">Basic Operations</h3>
<p>BigInt supports all the basic arithmetic operations:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> a = <span class="hljs-number">1234567890123456789n</span>;
<span class="hljs-keyword">let</span> b = <span class="hljs-number">9876543210987654321n</span>;

<span class="hljs-built_in">console</span>.log(a + b); <span class="hljs-comment">// 11111111111111111110n</span>
<span class="hljs-built_in">console</span>.log(a * b); <span class="hljs-comment">// 12193263111263526900438452720368555n</span>
<span class="hljs-built_in">console</span>.log(b - a); <span class="hljs-comment">// 8641975320864197532n</span>
<span class="hljs-built_in">console</span>.log(b / a); <span class="hljs-comment">// 8n (Integer division)</span>
<span class="hljs-built_in">console</span>.log(b % a); <span class="hljs-comment">// 1219326311126352690n</span>
</code></pre>
<p>Note that division with BigInt always results in an integer, truncating any decimal part.</p>
<h3 id="heading-comparison">Comparison</h3>
<p>BigInt values can be compared using the standard comparison operators:</p>
<pre><code class="lang-javascript"><span class="hljs-built_in">console</span>.log(<span class="hljs-number">10n</span> &gt; <span class="hljs-number">5n</span>); <span class="hljs-comment">// true</span>
<span class="hljs-built_in">console</span>.log(<span class="hljs-number">10n</span> &lt; <span class="hljs-number">5n</span>); <span class="hljs-comment">// false</span>
<span class="hljs-built_in">console</span>.log(<span class="hljs-number">10n</span> === <span class="hljs-number">10</span>); <span class="hljs-comment">// false (strict equality)</span>
<span class="hljs-built_in">console</span>.log(<span class="hljs-number">10n</span> == <span class="hljs-number">10</span>); <span class="hljs-comment">// true (loose equality)</span>
</code></pre>
<h3 id="heading-bitwise-operations">Bitwise Operations</h3>
<p>BigInt supports most bitwise operations:</p>
<pre><code class="lang-javascript"><span class="hljs-built_in">console</span>.log(<span class="hljs-number">17n</span> &amp; <span class="hljs-number">13n</span>); <span class="hljs-comment">// 1n</span>
<span class="hljs-built_in">console</span>.log(<span class="hljs-number">17n</span> | <span class="hljs-number">13n</span>); <span class="hljs-comment">// 29n</span>
<span class="hljs-built_in">console</span>.log(<span class="hljs-number">17n</span> ^ <span class="hljs-number">13n</span>); <span class="hljs-comment">// 28n</span>
<span class="hljs-built_in">console</span>.log(~<span class="hljs-number">17n</span>); <span class="hljs-comment">// -18n</span>
<span class="hljs-built_in">console</span>.log(<span class="hljs-number">17n</span> &lt;&lt; <span class="hljs-number">1n</span>); <span class="hljs-comment">// 34n</span>
<span class="hljs-built_in">console</span>.log(<span class="hljs-number">17n</span> &gt;&gt; <span class="hljs-number">1n</span>); <span class="hljs-comment">// 8n</span>
</code></pre>
<p>Note that there's no support for <code>&gt;&gt;&gt;</code> (zero-fill right shift) with BigInt.</p>
<h2 id="heading-practical-applications">Practical Applications</h2>
<h3 id="heading-financial-calculations">Financial Calculations</h3>
<p>BigInt is particularly useful for financial calculations where precision is crucial:</p>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">calculateCompoundInterest</span>(<span class="hljs-params">principal, rate, time, compound</span>) </span>{
  <span class="hljs-keyword">const</span> p = BigInt(<span class="hljs-built_in">Math</span>.round(principal * <span class="hljs-number">100</span>)); <span class="hljs-comment">// Convert to cents</span>
  <span class="hljs-keyword">const</span> r = BigInt(<span class="hljs-built_in">Math</span>.round(rate * <span class="hljs-number">100</span>));
  <span class="hljs-keyword">const</span> t = BigInt(time);
  <span class="hljs-keyword">const</span> n = BigInt(compound);

  <span class="hljs-keyword">const</span> amount = p * ((<span class="hljs-number">1n</span> + r / (<span class="hljs-number">100n</span> * n)) ** (n * t)) / (<span class="hljs-number">100n</span> ** t);

  <span class="hljs-keyword">return</span> <span class="hljs-built_in">Number</span>(amount) / <span class="hljs-number">100</span>; <span class="hljs-comment">// Convert back to dollars</span>
}

<span class="hljs-built_in">console</span>.log(calculateCompoundInterest(<span class="hljs-number">1000000</span>, <span class="hljs-number">5</span>, <span class="hljs-number">30</span>, <span class="hljs-number">12</span>));
<span class="hljs-comment">// 4321942.30 (precise to the cent)</span>
</code></pre>
<h3 id="heading-cryptography">Cryptography</h3>
<p>BigInt is also valuable in cryptography, where working with very large prime numbers is common:</p>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">modPow</span>(<span class="hljs-params">base, exponent, modulus</span>) </span>{
  <span class="hljs-keyword">if</span> (modulus === <span class="hljs-number">1n</span>) <span class="hljs-keyword">return</span> <span class="hljs-number">0n</span>;
  <span class="hljs-keyword">let</span> result = <span class="hljs-number">1n</span>;
  base = base % modulus;
  <span class="hljs-keyword">while</span> (exponent &gt; <span class="hljs-number">0n</span>) {
    <span class="hljs-keyword">if</span> (exponent % <span class="hljs-number">2n</span> === <span class="hljs-number">1n</span>) {
      result = (result * base) % modulus;
    }
    exponent = exponent / <span class="hljs-number">2n</span>;
    base = (base * base) % modulus;
  }
  <span class="hljs-keyword">return</span> result;
}

<span class="hljs-comment">// Example: Calculate 3^(2^100) mod 1000000007</span>
<span class="hljs-built_in">console</span>.log(modPow(<span class="hljs-number">3n</span>, <span class="hljs-number">2n</span> ** <span class="hljs-number">100n</span>, <span class="hljs-number">1000000007n</span>)); <span class="hljs-comment">// 598046965n</span>
</code></pre>
<p>This function implements the modular exponentiation algorithm, crucial in many cryptographic operations.</p>
<h2 id="heading-best-practices-and-considerations">Best Practices and Considerations</h2>
<p>While BigInt is powerful, it's important to use it judiciously:</p>
<ol>
<li><p><strong>Performance</strong>: Operations on BigInt are generally slower than on Number. Use BigInt only when necessary.</p>
</li>
<li><p><strong>Type Coercion</strong>: Be careful when mixing BigInt with other types. Explicit conversions are often necessary.</p>
</li>
<li><p><strong>JSON</strong>: BigInt values aren't serialized in JSON by default. You may need custom serialization/deserialization logic.</p>
</li>
<li><p><strong>Math Object</strong>: Many Math object methods don't support BigInt. You might need to implement your own mathematical functions for BigInt.</p>
</li>
<li><p><strong>Fractional BigInt</strong>: There's no such thing as a fractional BigInt. For calculations requiring fractional values, consider using a library like decimal.js.</p>
</li>
</ol>
<h2 id="heading-browser-support">Browser Support</h2>
<p>As of 2023, BigInt is supported in all modern browsers. However, for older browsers, you might need to use a polyfill or transpile your code.</p>
<h2 id="heading-conclusion">Conclusion</h2>
<p>BigInt opens up new possibilities in JavaScript, allowing us to work with integers of any size with precision. Whether you're dealing with financial calculations, cryptography, or any other domain requiring large integers, BigInt provides the tools you need.</p>
<p>As web applications become more complex and handle larger datasets, features like BigInt become increasingly important. By mastering BigInt, you're equipping yourself with a powerful tool in the JavaScript ecosystem.</p>
<p>Remember, with great power comes great responsibility. Use BigInt when you need it, but be mindful of its performance implications and interoperability considerations. Happy coding, and may your calculations always be precise!</p>
]]></content:encoded></item><item><title><![CDATA[WeakMap and WeakSet: JavaScript's Stealthy Memory Optimization Duo]]></title><description><![CDATA[Learn how WeakMap and WeakSet optimize memory, prevent leaks, and improve data management in JavaScript applications]]></description><link>https://cswithiyush.hashnode.dev/weakmap-and-weakset-javascripts-stealthy-memory-optimization-duo</link><guid isPermaLink="true">https://cswithiyush.hashnode.dev/weakmap-and-weakset-javascripts-stealthy-memory-optimization-duo</guid><category><![CDATA[JavaScript]]></category><category><![CDATA[javascript framework]]></category><category><![CDATA[Beginner Developers]]></category><category><![CDATA[Tutorial]]></category><category><![CDATA[Web Development]]></category><dc:creator><![CDATA[Ayush Pawar]]></dc:creator><pubDate>Sun, 04 Aug 2024 06:38:24 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1722752932999/3c925e11-e89e-4388-810b-7f05601f2578.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h1 id="heading-weakmap-and-weakset-javascripts-memory-efficient-secret-weapons">WeakMap and WeakSet: JavaScript's Memory-Efficient Secret Weapons</h1>
<p>Hey there, JavaScript enthusiasts! Today, we're diving into the world of WeakMap and WeakSet – two often-overlooked data structures that can be incredibly useful when it comes to managing memory in your applications. If you've ever worried about memory leaks or needed to associate data with objects without preventing garbage collection, then this post is for you!</p>
<h2 id="heading-what-are-weakmap-and-weakset">What are WeakMap and WeakSet?</h2>
<p>Before we dive in, let's quickly recap what Map and Set are in JavaScript:</p>
<ul>
<li><p>A Map is a collection of key-value pairs where both the keys and values can be of any type.</p>
</li>
<li><p>A Set is a collection of unique values of any type.</p>
</li>
</ul>
<p>Now, WeakMap and WeakSet are similar, but with a crucial difference: they hold "weak" references to their keys (for WeakMap) or values (for WeakSet). This means that if there are no other references to the key object, it can be garbage collected, even if it's in the WeakMap or WeakSet.</p>
<h2 id="heading-weakmap-the-memory-friendly-key-value-store">WeakMap: The Memory-Friendly Key-Value Store</h2>
<p>Let's start with WeakMap. Here's a basic example:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> weakMap = <span class="hljs-keyword">new</span> <span class="hljs-built_in">WeakMap</span>();
<span class="hljs-keyword">let</span> obj = {};

weakMap.set(obj, <span class="hljs-string">"I'm associated with obj"</span>);
<span class="hljs-built_in">console</span>.log(weakMap.get(obj)); <span class="hljs-comment">// Output: I'm associated with obj</span>

obj = <span class="hljs-literal">null</span>; <span class="hljs-comment">// The object is now eligible for garbage collection</span>
</code></pre>
<p>In this example, once <code>obj</code> is set to null, it becomes eligible for garbage collection, even though it's a key in the WeakMap. The WeakMap doesn't prevent this from happening.</p>
<h3 id="heading-use-case-private-data-storage">Use Case: Private Data Storage</h3>
<p>One common use case for WeakMap is to store private data associated with objects:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> privateData = <span class="hljs-keyword">new</span> <span class="hljs-built_in">WeakMap</span>();

<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">User</span> </span>{
  <span class="hljs-keyword">constructor</span>(name, age) {
    privateData.set(<span class="hljs-built_in">this</span>, { name, age });
  }

  getName() {
    <span class="hljs-keyword">return</span> privateData.get(<span class="hljs-built_in">this</span>).name;
  }

  getAge() {
    <span class="hljs-keyword">return</span> privateData.get(<span class="hljs-built_in">this</span>).age;
  }
}

<span class="hljs-keyword">let</span> user = <span class="hljs-keyword">new</span> User(<span class="hljs-string">"Alice"</span>, <span class="hljs-number">30</span>);
<span class="hljs-built_in">console</span>.log(user.getName()); <span class="hljs-comment">// Output: Alice</span>
<span class="hljs-built_in">console</span>.log(user.getAge());  <span class="hljs-comment">// Output: 30</span>

<span class="hljs-comment">// The private data is not accessible outside the class</span>
<span class="hljs-built_in">console</span>.log(privateData.get(user)); <span class="hljs-comment">// Output: {name: "Alice", age: 30}</span>

user = <span class="hljs-literal">null</span>; <span class="hljs-comment">// User object and its private data become eligible for garbage collection</span>
</code></pre>
<p>In this example, we use a WeakMap to store private data for each User instance. This data is not directly accessible from outside the class, providing a form of encapsulation.</p>
<h2 id="heading-weakset-the-set-that-lets-go">WeakSet: The Set That Lets Go</h2>
<p>WeakSet is similar to WeakMap, but it's a collection of objects only. Like WeakMap, it holds weak references to its values.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> weakSet = <span class="hljs-keyword">new</span> <span class="hljs-built_in">WeakSet</span>();
<span class="hljs-keyword">let</span> obj1 = {};
<span class="hljs-keyword">let</span> obj2 = {};

weakSet.add(obj1);
weakSet.add(obj2);

<span class="hljs-built_in">console</span>.log(weakSet.has(obj1)); <span class="hljs-comment">// Output: true</span>

obj1 = <span class="hljs-literal">null</span>; <span class="hljs-comment">// obj1 is now eligible for garbage collection</span>
</code></pre>
<h3 id="heading-use-case-marking-objects-as-visited">Use Case: Marking Objects as "Visited"</h3>
<p>WeakSet can be useful for marking objects as "visited" in algorithms without preventing them from being garbage collected:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> visited = <span class="hljs-keyword">new</span> <span class="hljs-built_in">WeakSet</span>();

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">process</span>(<span class="hljs-params">obj</span>) </span>{
  <span class="hljs-keyword">if</span> (visited.has(obj)) {
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Already processed this object"</span>);
    <span class="hljs-keyword">return</span>;
  }

  visited.add(obj);
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Processing object..."</span>);
  <span class="hljs-comment">// Process the object...</span>
}

<span class="hljs-keyword">let</span> obj = { <span class="hljs-attr">data</span>: <span class="hljs-string">"important"</span> };
process(obj); <span class="hljs-comment">// Output: Processing object...</span>
process(obj); <span class="hljs-comment">// Output: Already processed this object</span>

obj = <span class="hljs-literal">null</span>; <span class="hljs-comment">// The object can now be garbage collected</span>
</code></pre>
<p>In this example, we use a WeakSet to keep track of which objects have been processed. Once the object is no longer needed and there are no other references to it, it can be garbage collected along with its entry in the WeakSet.</p>
<h2 id="heading-key-differences-from-map-and-set">Key Differences from Map and Set</h2>
<ol>
<li><p><strong>Weak References</strong>: The most crucial difference is that WeakMap and WeakSet use weak references, allowing for automatic garbage collection.</p>
</li>
<li><p><strong>Key Types</strong>: WeakMap and WeakSet can only use objects as keys (WeakMap) or values (WeakSet). Primitive values are not allowed.</p>
</li>
<li><p><strong>No Iteration</strong>: You can't iterate over WeakMap or WeakSet. They also don't have a <code>size</code> property or <code>clear()</code> method.</p>
</li>
<li><p><strong>Use Cases</strong>: They're particularly useful for scenarios involving caches, additional data storage, or object marking without interfering with garbage collection.</p>
</li>
</ol>
<h2 id="heading-when-to-use-weakmap-and-weakset">When to Use WeakMap and WeakSet</h2>
<p>Consider using WeakMap or WeakSet when:</p>
<ol>
<li><p>You need to associate data with objects, but don't want to prevent those objects from being garbage collected.</p>
</li>
<li><p>You're implementing a cache where entries should be automatically removed when the key object is no longer in use.</p>
</li>
<li><p>You want to add properties or mark objects without modifying them directly or preventing their garbage collection.</p>
</li>
</ol>
<h2 id="heading-performance-considerations">Performance Considerations</h2>
<p>WeakMap and WeakSet come with some performance benefits:</p>
<ol>
<li><p><strong>Memory Efficiency</strong>: They allow the garbage collector to do its job, potentially reducing memory usage in long-running applications.</p>
</li>
<li><p><strong>No Need for Manual Cleanup</strong>: Unlike with regular Maps or Sets, you don't need to manually remove entries to prevent memory leaks.</p>
</li>
</ol>
<p>However, the lack of iteration methods and size property means they're not suitable for scenarios where you need to frequently check or iterate over all entries.</p>
<h2 id="heading-conclusion">Conclusion</h2>
<p>WeakMap and WeakSet are powerful tools in JavaScript that provide unique solutions to specific problems. They allow you to associate data with objects or mark objects as special in some way, all without interfering with garbage collection. This can lead to more memory-efficient applications, especially in scenarios involving caches or temporary object metadata.</p>
<p>While they may not be everyday tools for every JavaScript developer, understanding WeakMap and WeakSet can help you write more efficient code and solve certain problems more elegantly. So the next time you find yourself worried about memory leaks or needing to associate disposable data with objects, remember these memory-efficient secret weapons!</p>
<p>Happy coding, and may your memory always be efficiently managed!</p>
]]></content:encoded></item><item><title><![CDATA[Proxy Magic: How to Bend JavaScript Objects to Your Will]]></title><description><![CDATA[Use JavaScript Proxies to customize object operations with practical examples and real-world applications]]></description><link>https://cswithiyush.hashnode.dev/proxy-magic-how-to-bend-javascript-objects-to-your-will</link><guid isPermaLink="true">https://cswithiyush.hashnode.dev/proxy-magic-how-to-bend-javascript-objects-to-your-will</guid><category><![CDATA[JavaScript]]></category><category><![CDATA[javascript framework]]></category><category><![CDATA[Tutorial]]></category><category><![CDATA[beginner]]></category><category><![CDATA[Web Development]]></category><dc:creator><![CDATA[Ayush Pawar]]></dc:creator><pubDate>Sat, 03 Aug 2024 18:20:40 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1722709049433/d54866ae-c898-4e05-97a0-f8f7db6861ea.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h1 id="heading-unveiling-the-magic-of-javascript-proxies-a-deep-dive">Unveiling the Magic of JavaScript Proxies: A Deep Dive</h1>
<p>Hey there, JavaScript enthusiasts! Today, we're going to explore a powerful yet often overlooked feature of modern JavaScript: the Proxy object. If you've ever wished you could intercept and customize fundamental operations on JavaScript objects, then you're in for a treat. Buckle up as we dive into the world of Proxies!</p>
<h2 id="heading-what-is-a-proxy">What is a Proxy?</h2>
<p>In JavaScript, a Proxy is an object that wraps another object (called the target) and can intercept fundamental operations on that object, like getting or setting properties. It's like having a bodyguard for your object that can modify how it behaves without changing the object itself.</p>
<h2 id="heading-the-anatomy-of-a-proxy">The Anatomy of a Proxy</h2>
<p>A Proxy is created with two parameters:</p>
<ol>
<li><p>The target object</p>
</li>
<li><p>A handler object that defines the operations to intercept (called traps)</p>
</li>
</ol>
<p>Here's the basic syntax:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> proxy = <span class="hljs-keyword">new</span> <span class="hljs-built_in">Proxy</span>(target, handler);
</code></pre>
<h2 id="heading-your-first-proxy-logging-property-access">Your First Proxy: Logging Property Access</h2>
<p>Let's start with a simple example. We'll create a Proxy that logs every time a property is accessed:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> target = {
  <span class="hljs-attr">name</span>: <span class="hljs-string">"John Doe"</span>,
  <span class="hljs-attr">age</span>: <span class="hljs-number">30</span>
};

<span class="hljs-keyword">const</span> handler = {
  <span class="hljs-attr">get</span>: <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">obj, prop</span>) </span>{
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`Accessing property: <span class="hljs-subst">${prop}</span>`</span>);
    <span class="hljs-keyword">return</span> obj[prop];
  }
};

<span class="hljs-keyword">const</span> proxy = <span class="hljs-keyword">new</span> <span class="hljs-built_in">Proxy</span>(target, handler);

<span class="hljs-built_in">console</span>.log(proxy.name);  <span class="hljs-comment">// Logs: Accessing property: name</span>
                          <span class="hljs-comment">// Then logs: John Doe</span>
<span class="hljs-built_in">console</span>.log(proxy.age);   <span class="hljs-comment">// Logs: Accessing property: age</span>
                          <span class="hljs-comment">// Then logs: 30</span>
</code></pre>
<p>In this example, our Proxy intercepts all <code>get</code> operations on the target object and logs the property being accessed before returning its value.</p>
<h2 id="heading-validating-property-values-with-proxies">Validating Property Values with Proxies</h2>
<p>Proxies can be used to add validation to object properties. Let's create a Proxy that ensures age is always a positive number:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> person = {
  <span class="hljs-attr">name</span>: <span class="hljs-string">"Alice"</span>,
  <span class="hljs-attr">age</span>: <span class="hljs-number">25</span>
};

<span class="hljs-keyword">const</span> validator = {
  <span class="hljs-attr">set</span>: <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">obj, prop, value</span>) </span>{
    <span class="hljs-keyword">if</span> (prop === <span class="hljs-string">'age'</span>) {
      <span class="hljs-keyword">if</span> (<span class="hljs-keyword">typeof</span> value !== <span class="hljs-string">'number'</span>) {
        <span class="hljs-keyword">throw</span> <span class="hljs-keyword">new</span> <span class="hljs-built_in">TypeError</span>(<span class="hljs-string">'Age must be a number'</span>);
      }
      <span class="hljs-keyword">if</span> (value &lt; <span class="hljs-number">0</span>) {
        <span class="hljs-keyword">throw</span> <span class="hljs-keyword">new</span> <span class="hljs-built_in">RangeError</span>(<span class="hljs-string">'Age must be a positive number'</span>);
      }
    }
    obj[prop] = value;
    <span class="hljs-keyword">return</span> <span class="hljs-literal">true</span>;
  }
};

<span class="hljs-keyword">const</span> validatedPerson = <span class="hljs-keyword">new</span> <span class="hljs-built_in">Proxy</span>(person, validator);

validatedPerson.age = <span class="hljs-number">30</span>;  <span class="hljs-comment">// Works fine</span>
validatedPerson.age = <span class="hljs-number">-5</span>;  <span class="hljs-comment">// Throws: RangeError: Age must be a positive number</span>
validatedPerson.age = <span class="hljs-string">"30"</span>;  <span class="hljs-comment">// Throws: TypeError: Age must be a number</span>
</code></pre>
<p>This Proxy intercepts all <code>set</code> operations and applies validation rules when the 'age' property is being set.</p>
<h2 id="heading-creating-private-properties-with-proxies">Creating "Private" Properties with Proxies</h2>
<p>JavaScript doesn't have built-in private properties, but we can simulate them using Proxies:</p>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">createObjectWithPrivates</span>(<span class="hljs-params">publicProps, privateProps</span>) </span>{
  <span class="hljs-keyword">return</span> <span class="hljs-keyword">new</span> <span class="hljs-built_in">Proxy</span>(publicProps, {
    get(target, prop) {
      <span class="hljs-keyword">if</span> (prop <span class="hljs-keyword">in</span> target) {
        <span class="hljs-keyword">return</span> target[prop];
      }
      <span class="hljs-keyword">throw</span> <span class="hljs-keyword">new</span> <span class="hljs-built_in">Error</span>(<span class="hljs-string">`Access to private property "<span class="hljs-subst">${prop}</span>" is not allowed`</span>);
    },
    set(target, prop, value) {
      <span class="hljs-keyword">if</span> (prop <span class="hljs-keyword">in</span> target) {
        target[prop] = value;
        <span class="hljs-keyword">return</span> <span class="hljs-literal">true</span>;
      }
      <span class="hljs-keyword">throw</span> <span class="hljs-keyword">new</span> <span class="hljs-built_in">Error</span>(<span class="hljs-string">`Setting private property "<span class="hljs-subst">${prop}</span>" is not allowed`</span>);
    },
    has(target, prop) {
      <span class="hljs-keyword">return</span> prop <span class="hljs-keyword">in</span> target;
    }
  });
}

<span class="hljs-keyword">const</span> obj = createObjectWithPrivates(
  { <span class="hljs-attr">publicProp</span>: <span class="hljs-string">"I'm public"</span> },
  { <span class="hljs-attr">privateProp</span>: <span class="hljs-string">"I'm private"</span> }
);

<span class="hljs-built_in">console</span>.log(obj.publicProp);  <span class="hljs-comment">// "I'm public"</span>
<span class="hljs-built_in">console</span>.log(obj.privateProp);  <span class="hljs-comment">// Throws: Error: Access to private property "privateProp" is not allowed</span>
</code></pre>
<p>This Proxy intercepts <code>get</code>, <code>set</code>, and <code>has</code> operations to prevent access to properties not explicitly defined in the public object.</p>
<h2 id="heading-revocable-proxies-the-self-destructing-wrappers">Revocable Proxies: The Self-Destructing Wrappers</h2>
<p>JavaScript also provides revocable Proxies, which can be "turned off" when needed:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> target = { <span class="hljs-attr">secret</span>: <span class="hljs-string">"I'm a secret"</span> };
<span class="hljs-keyword">const</span> { proxy, revoke } = <span class="hljs-built_in">Proxy</span>.revocable(target, {
  get(target, prop) {
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`Accessing property: <span class="hljs-subst">${prop}</span>`</span>);
    <span class="hljs-keyword">return</span> target[prop];
  }
});

<span class="hljs-built_in">console</span>.log(proxy.secret);  <span class="hljs-comment">// Logs: Accessing property: secret</span>
                            <span class="hljs-comment">// Then logs: I'm a secret</span>

revoke();  <span class="hljs-comment">// Revoke the Proxy</span>

<span class="hljs-built_in">console</span>.log(proxy.secret);  <span class="hljs-comment">// Throws: TypeError: Cannot perform 'get' on a proxy that has been revoked</span>
</code></pre>
<p>Revocable Proxies are useful in scenarios where you need to provide temporary access to an object and then completely cut off that access later.</p>
<h2 id="heading-performance-considerations">Performance Considerations</h2>
<p>While Proxies are powerful, they do come with a performance overhead. Each operation that goes through the Proxy is slightly slower than performing the same operation directly on the target object. For most applications, this difference is negligible, but it's something to keep in mind for performance-critical code.</p>
<h2 id="heading-real-world-use-cases">Real-World Use Cases</h2>
<p>Proxies can implement lazy loading of properties, which is useful for optimizing resource-intensive operations:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> heavyResource = <span class="hljs-keyword">new</span> <span class="hljs-built_in">Proxy</span>({}, {
  <span class="hljs-attr">get</span>: <span class="hljs-function">(<span class="hljs-params">target, property</span>) =&gt;</span> {
    <span class="hljs-keyword">if</span> (!(property <span class="hljs-keyword">in</span> target)) {
      <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`Loading <span class="hljs-subst">${property}</span>...`</span>);
      target[property] = loadExpensiveResource(property);
    }
    <span class="hljs-keyword">return</span> target[property];
  }
});

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">loadExpensiveResource</span>(<span class="hljs-params">key</span>) </span>{
  <span class="hljs-comment">// Simulate an expensive operation</span>
  <span class="hljs-keyword">return</span> <span class="hljs-string">`Data for <span class="hljs-subst">${key}</span>`</span>;
}

<span class="hljs-built_in">console</span>.log(heavyResource.user);  <span class="hljs-comment">// Logs: Loading user... \n Data for user</span>
<span class="hljs-built_in">console</span>.log(heavyResource.user);  <span class="hljs-comment">// Logs: Data for user (already loaded)</span>
</code></pre>
<p>Proxies are perfect for implementing access control in objects, useful in creating secure or restricted environments:</p>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">createSecureObject</span>(<span class="hljs-params">obj, allowedRoles</span>) </span>{
  <span class="hljs-keyword">return</span> <span class="hljs-keyword">new</span> <span class="hljs-built_in">Proxy</span>(obj, {
    <span class="hljs-attr">get</span>: <span class="hljs-function">(<span class="hljs-params">target, prop</span>) =&gt;</span> {
      <span class="hljs-keyword">if</span> (currentUserRole &amp;&amp; allowedRoles.includes(currentUserRole)) {
        <span class="hljs-keyword">return</span> target[prop];
      }
      <span class="hljs-keyword">throw</span> <span class="hljs-keyword">new</span> <span class="hljs-built_in">Error</span>(<span class="hljs-string">"Access denied"</span>);
    }
  });
}

<span class="hljs-keyword">let</span> currentUserRole = <span class="hljs-string">'User'</span>;
<span class="hljs-keyword">const</span> secureData = createSecureObject({ <span class="hljs-attr">secretKey</span>: <span class="hljs-string">'1234'</span> }, [<span class="hljs-string">'Admin'</span>]);

<span class="hljs-keyword">try</span> {
  <span class="hljs-built_in">console</span>.log(secureData.secretKey);
} <span class="hljs-keyword">catch</span> (e) {
  <span class="hljs-built_in">console</span>.log(e.message);  <span class="hljs-comment">// Outputs: Access denied</span>
}

currentUserRole = <span class="hljs-string">'Admin'</span>;
<span class="hljs-built_in">console</span>.log(secureData.secretKey);  <span class="hljs-comment">// Outputs: 1234</span>
</code></pre>
<h2 id="heading-conclusion">Conclusion</h2>
<p>As we've seen, JavaScript Proxies offer a powerful way to intercept and customize operations on objects. Their real-world applications are vast, ranging from data binding and lazy loading to security features like input sanitization and access control.</p>
<p>By leveraging Proxies, you can create more robust, efficient, and secure applications. They allow you to add sophisticated behavior to objects without cluttering your codebase with repetitive logic.</p>
<p>Remember, while Proxies are powerful, they should be used judiciously. Always consider the performance implications and the potential for increased complexity in your code.</p>
<p>Now that you're armed with both the knowledge of how Proxies work and ideas for practical applications, why not try incorporating them into your next project? Happy coding, and may your objects always be well-guarded and highly functional!</p>
]]></content:encoded></item><item><title><![CDATA[Introduction to Git: A Step-by-Step Story]]></title><description><![CDATA[A no-nonsense way to learn Git. Master daily life git commands by learning through real world examples.]]></description><link>https://cswithiyush.hashnode.dev/introduction-to-git-a-step-by-step-story</link><guid isPermaLink="true">https://cswithiyush.hashnode.dev/introduction-to-git-a-step-by-step-story</guid><category><![CDATA[Beginner Developers]]></category><category><![CDATA[GitHub]]></category><category><![CDATA[coding]]></category><category><![CDATA[Programming Blogs]]></category><category><![CDATA[Tutorial]]></category><dc:creator><![CDATA[Ayush Pawar]]></dc:creator><pubDate>Thu, 18 Jul 2024 16:42:38 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1721320712171/2970bf4b-7160-4a09-8a87-49a50b56d45a.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h1 id="heading-introduction">Introduction</h1>
<p>Git is a powerful version control system that enables developers to manage their codebase efficiently, track changes, collaborate with others, and maintain project history. Whether you're new to programming or looking to understand Git basics, this guide will walk you through the fundamental concepts, essential commands, and tips to master Git as an engineer.</p>
<h2 id="heading-what-is-git">What is Git?</h2>
<p>Git is a distributed version control system designed to handle everything from small to very large projects with speed and efficiency. It allows multiple developers to work on the same codebase simultaneously without conflicts, tracks changes made to files over time, and enables easy collaboration.</p>
<h2 id="heading-git-installation">Git Installation</h2>
<p>Installing Git is pretty simple. If you are on Linux machine, just type this command</p>
<p><code>sudo dnf install git-all</code></p>
<p>There are a few ways to install Git on Windows. The most official build is available for download on the Git website. Just go to <a target="_blank" href="https://git-scm.com/download/win">https://git-scm.com/download/win and the download will start aut</a>omatically. Note that this is a project called Git for Windows, which is separate from Git itself; for more information on it, go to <a target="_blank" href="https://gitforwindows.org">https://gitforwindows.org</a><a target="_blank" href="https://gitforwindows.org/">.</a></p>
<p><a target="_blank" href="https://gitforwindows.org/">To get an automated in</a>stallation you can use the <a target="_blank" href="https://community.chocolatey.org/packages/git">Git Chocolatey package. Note that the Choc</a>olatey package is community maintained.</p>
<p>For macOS, There are several ways to install Git on macOS. The easiest is probably to install the Xcode Command Line Tools. On Mavericks (10.9) or above you can do this simply by trying to run <code>git</code> from the Terminal the very first time.</p>
<pre><code class="lang-console">$ git --version
</code></pre>
<p>If you don’t have it installed already, it will prompt you to install it.</p>
<p>With git installed, Let's focus on understanding what git is and what are the most commonly used features of git. For simplicity, I have broken down the article into two parts.</p>
<ol>
<li><p>Level 1</p>
</li>
<li><p>Level 2</p>
</li>
</ol>
<p>In level 1, you will learn about <mark>clone , fork, add, commit, push, pull.</mark></p>
<p>In level 2, you will learn about <mark>branches, merge, merge conflicts, and stash.</mark></p>
<h1 id="heading-level-1">Level 1</h1>
<p>Let's first understand the two <a target="_blank" href="https://git-scm.com/download/win">most basic concepts of Git.</a></p>
<ol>
<li><p><a target="_blank" href="https://git-scm.com/download/win">C</a>lone</p>
</li>
<li><p>Fork.</p>
</li>
</ol>
<h2 id="heading-what-is-clone">What is Clone?</h2>
<p>Let's say your friend and you are working on a project for a hackathon. Your friend has created a github repository which con<a target="_blank" href="https://gitforwindows.org/">sists of initial code. No</a>w you want to access code. How do you do it? Yo<a target="_blank" href="https://community.chocolatey.org/packages/git">u guessed it right. <strong>CL</strong></a><strong>ONING</strong>!</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1721152245751/15d4e979-0bab-48f4-9351-32668c0ec393.png" alt class="image--center mx-auto" /></p>
<p>Cloning is creating a local copy of the repository. Cloning is simple. Go to any repository on Github. Press the green Code button, click the copy icon, go to your terminal, and paste the below command.</p>
<pre><code class="lang-bash">git <span class="hljs-built_in">clone</span> https://github.com/Spyyy004/anidex.git
</code></pre>
<p>This simple command creates a local copy of the remote repository. So now there are two repositories.</p>
<ol>
<li><p>The main repo that exists on Github servers.</p>
</li>
<li><p>The cloned repo that exists on your local system.</p>
</li>
</ol>
<p>Your cloned repository is where you can do anything with your code. It is your playground. Whatever changes you make will be on your local computer unless you <em>commit and push the code</em></p>
<p>What is commiting and pushing? We will see it later.</p>
<h2 id="heading-what-is-fork">What is Fork?</h2>
<p>Imagine this, you want to add a new function to the string method of python codebase. Python's code is open source. There are 2 ways to do this.</p>
<ol>
<li><p>Find the repository's maintainer. Give him your code, hope he will add your code in the repo and you will get to use it.</p>
</li>
<li><p>Create a copy of python's codebase.(<strong>Forking</strong>!) Add the new function to your forked repository. Use it as much as you want!</p>
</li>
</ol>
<p>Forking is simpler than cloning. Go to any repository and just click the Fork button. A new page will open up which would ask by what name do you want your fork repo to be created and do you want to keep it public or private.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1721152741073/80cc1e1b-bb5c-416a-b9ee-ee65949ca620.png" alt class="image--center mx-auto" /></p>
<p>Forking creates a remote repository which you can treat as a personal playground. <strong><mark>Making changes in the forked repository will not affect the main repository</mark></strong><mark>.</mark></p>
<p>Once you have forked, you clone the forked repository, add your new function to string and voila.</p>
<p>So now there are 3 repositories.</p>
<ol>
<li><p>The main repository.</p>
</li>
<li><p>The forked repository that exists on your Github account.</p>
</li>
<li><p>The cloned repository that exists on your local machine.</p>
</li>
</ol>
<p><img src="https://www.earthdatascience.org/images/earth-analytics/git-version-control/git-fork-emphasis.png" alt="How to fork a repo in GitHub | Earth Data Science - Earth Lab" /></p>
<h3 id="heading-how-does-forking-help">How does forking help?</h3>
<p>See, python is a huge open source project used my millions of developers. Open source means anyone can contribute to Python. Just like how you had a thought of creating a function for strings, a lot of other developers have 100s of thoughts. It might happen that a lot of people didn't like your proposed new function (for valid reasons) and don't want it in Python but you are adamant of using it as it makes your life easier.</p>
<p>This is where forking helps. You create a fork and just create the function for yourself in your forked repository. No one else gets that function. It is a win win for everyone. If your function is really good and people see its value, you raise a PR (Pull request) and it gets merged to the main repository. Yay! You made an open-source contribution.</p>
<p>Don't know what is a PR? We will get to that later.</p>
<h2 id="heading-fork-or-no-fork">Fork or No Fork</h2>
<p>So the industry is divided in two parts.</p>
<ol>
<li><p>Fork the main repository, clone the forked repository, and clone the forked repository.</p>
</li>
<li><p>Clone the main repository directly without forking.</p>
</li>
</ol>
<p>Both these methods have its advantages and disadvantages.</p>
<p>Open Source projects usually follow the first approach. Organizations follow both. Some orgs use the first approach and some the second.</p>
<h2 id="heading-real-life-example">Real Life Example</h2>
<p>In this section, we will understand the concept of <mark>pull , add, commit, and push.</mark> All this with a real example. Let's break down the example in 2 scenarios</p>
<h3 id="heading-scenario-1">Scenario 1</h3>
<p>Let's go back to the project which you and your friend were building.</p>
<p>Remember you cloned the repository? Awesome. Now you decided to add an api endpoint to get user profile. You coded the functionality, now you want to transfer this code to your friend. How do you do that?</p>
<p>Remember I told that there is a local repository that exists on your machine? Whenever you make changes to the code in VS Code or any code editor, your local repository needs to know what changes you are making. Let's say you made changes to <code>route.js</code>. So in order to let your local repository know, you do</p>
<pre><code class="lang-bash">git add route.js
</code></pre>
<p>The term which is used for files that is not known by local repository is <code>untracked files</code> When you do a <code>git add &lt;filename&gt;</code> , you are now tracking those files. Now your files are called <code>staged files</code>.</p>
<p>What if you made changes to 20 files in one go and want to add all the files together? Simple, just type the below command.</p>
<pre><code class="lang-bash">git add .
</code></pre>
<p>It is advised to not do <code>git add .</code> because it is not a good practice. You must always review all the files individually and add them one by one.</p>
<p>With <code>git add</code> you have created a temporary space where all your code changes are present. In order to let your local repository know about this changes, you simply do</p>
<pre><code class="lang-bash">git commit -m <span class="hljs-string">"my first commit"</span>
</code></pre>
<p>With the above command, your local repository has all your changed code. You can replace "my first commit" with anything. It is just a message. Awesome! Next step is update your remote repository with code in your local repository.</p>
<p>You do it simply by typing</p>
<pre><code class="lang-bash">git push
</code></pre>
<p>That's it. So simple right! Your code is now on the remote repository present on Github.</p>
<h3 id="heading-scenario-2">Scenario 2</h3>
<p>In the first scenario, you learned about add , commit, and push. In this scenario, you will learn about pull and merge.</p>
<p>Let's say your friend has coded a brand new landing page and he has pushed the code to remote repository on Github. How do you get that code on your system?</p>
<p>Simple. you do</p>
<pre><code class="lang-bash">git pull
</code></pre>
<p>This one command will sync your local repository with the remote repository and you will have the latest code.</p>
<h1 id="heading-level-2">Level 2</h1>
<p>Great job reaching this far. You have a decent knowledge of git now. You can easily work on a repository which has a single branch. But in real world projects, there is rarely a codebase with just one branch.</p>
<p>Let's see what branches are and how do you work with them.</p>
<h3 id="heading-branches">Branches</h3>
<p>Imagine your code base as a huge tree with just one branch i.e the main branch. As the tree grows, new smaller branches pop out from the main branch. Similarly as the codebase grows, new branches pops out from the main branch.</p>
<p><img src="https://www.nobledesktop.com/image/gitresources/git-branches-merge.png" alt="Git Branches: List, Create, Switch to, Merge, Push, &amp; Delete" /></p>
<p>The tree thing happens naturally but the git thing is in your hands. Usually, in real world, there will be countless branches in a codebase. There are several benefits of branches.</p>
<ol>
<li><p>Branches are created whenever you want to work on a new feature. Rule of thumb : Whenever working on a new feature, cut a branch from main.</p>
</li>
<li><p>Once your feature is developed and tested thoroughly, the branch is merged with the main branch. This ensures that the main branch doesn't get buggy and messy code.</p>
</li>
<li><p>The main branch is the one whose code runs in the real world. Rest all the branches are used for development.</p>
</li>
</ol>
<p>If you are working in an organization, there will usually be 2 branches from where the code is deployed</p>
<ol>
<li><p>Main</p>
</li>
<li><p>Staging</p>
</li>
</ol>
<p>Main branch is where code runs for the real-world. Staging branch is where code runs for the team for internal testing.</p>
<p>Staging branch is usually a mess and land of experimentation. So the process goes like this</p>
<ol>
<li><p>Cut a branch from main</p>
</li>
<li><p>Code in your branch. Test it on your local server on your branch</p>
</li>
<li><p>Merge your code with the staging branch. Deploy your code on the staging server. Test your code on the staging server.</p>
</li>
<li><p>Once everything is tested and working properly, raise a Pull Request for the main branch or merge it directly if you have access.</p>
</li>
</ol>
<p>Creating a branch is simple. Let's say you are on main branch and want to create a new branch. You simply type</p>
<pre><code class="lang-bash">git checkout -b <span class="hljs-string">"your_new_branch"</span>
</code></pre>
<p>Let's say you are working on two different features on two different branches. How do you navigate between them? Simple</p>
<pre><code class="lang-bash">git checkout &lt;branch_name&gt;

Eg : git checkout feature001
</code></pre>
<p>With branches now in play, your commands like push and pull now become more powerful. You can do something like <code>git pull origin &lt;branch_name&gt;</code>. This means you want to pull code from a particular branch in your current branch. Don't worry about the origin keyword, we will cover it in later sections.</p>
<p>Similarly you can do <code>git push origin &lt;branch_name&gt;</code> to push code in some other branch from the branch you are working on.</p>
<h2 id="heading-merging-code">Merging Code.</h2>
<p>We read in the previous section about merging code. But what is merging? It is exactly what the word means. To merge.</p>
<p>Merging is quite similar to pull. If you do git pull, you get all the code present in the remote repository in your local repository.</p>
<p>When you do <code>git merge a</code>, all the code present in the branch <code>a</code> of your <strong><mark>local repository</mark></strong></p>
<p>Remember how you cut a new branch to work on something? Once you are done working, you just merge the branch to the main branch. (if you have access) If you don't have merging access, you raise a Pull request for the main branch.</p>
<p>But how do you raise pull request? It is pretty simple. Once you are done with</p>
<pre><code class="lang-bash">git add .
git commit -m <span class="hljs-string">"my new code"</span>
git push origin my_feature_branch
</code></pre>
<p>You go to github. Then select pull requests from the panel</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1721320266459/1e03b409-88ed-4868-bf03-1fd7f9c0c85a.png" alt class="image--center mx-auto" /></p>
<p>On the pull requests page, you tap on New pull request.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1721320326855/4f63a340-702a-4f00-9a87-70701aa7cd3b.png" alt class="image--center mx-auto" /></p>
<p>Next, a page opens up where it asks you to select a branch, you select your branch and then you give a proper title and description for your request and press on create pull request.</p>
<p>The pull request then gets reviewed by your seniors and if everything is correct, the code is merged.</p>
<h2 id="heading-struggles-of-merge-conflict">Struggles of Merge Conflict</h2>
<p>You must have heard people banging their heads over something called as "Merge Conflicts". If you have not, then you will one day.</p>
<p>Merge conflicts occurs when git is confused while merging two pieces of code, but how can this situation even arise?</p>
<p>Let's understand with an example</p>
<p>Imagine you and your friend are working on a project. Let's say your friend and you working on a file called <code>routes.js</code>. He/She adds a function on line number 35 and pushes the code to the remote repository.</p>
<p>You also start coding in the same file because you want to add a new api route. Since the updated code is in the remote repository, there is nothing on line 35 for you. Your local repository is out of sync. So you code your new function and you also commit and push the code.</p>
<p>The moment you push the code, git will first ask you to pull code from the remote repository because local repository must be in sync before pushing to remote repository from your end.</p>
<p>The moment you do <code>git pull</code>, git will throw an error saying it has encountered a merge conflict. This happened because the remote repository's code in route.js contained the function written by your friend but in your local repository, the code contained function written by you.</p>
<p>So git is now confused on what to do. There is only one way to solve this and it is to resolve the conflicts manually. VS Code has a decent interface where you will get to see the current code and the incoming code. It will ask if you want to keep your code, the incoming code, or both the code.</p>
<p><img src="https://user-images.githubusercontent.com/802805/44273570-6e11da00-a205-11e8-88e7-cc81c8e7d71e.png" alt="δημόσιο κακεντρεχής πλάκα git merge conflict use mine περίφραξη το  διαδίκτυο χιόνι" /></p>
<p>Resolving merge conflicts must be done very carefully because important code might get lost. Imagine the scale of code that might get conflicted in big organizations.</p>
<p>Hence the rule of thumb is: <mark>Always take pull from origin before coding anything on your local machine.</mark></p>
<h3 id="heading-difference-between-origin-and-remote">Difference between origin and remote</h3>
<p>This is simple. Let's say you have forked a repository and cloned the fork repository then your <code>upstream</code> repository is the original one and <code>origin</code> is the forked one.</p>
<p>Git automatically knows the origin repository because you have cloned from it but it doesn't know which repository is the upstream. So you have to set the upstream by the following command <code>git set upstream &lt;repository_url&gt;</code></p>
<p>Now when you will do <code>git pull origin main</code> you will get code from forked repository and <code>git pull upstream main</code> you will get code from the original repository.</p>
<h2 id="heading-stashing-code">Stashing Code</h2>
<p>Congratulations on making this far. You have a lot of patience i might say. Now let's talk about a command which is very useful and i might say underrated as well.</p>
<p>It solves a very trivial problem that you will definetly face while coding in a company.</p>
<p>Let's say you are working on a feature x on branch <code>feature x</code>. Suddenly your senior comes up and gives you a prod bug to solve. Now, you have to create a new branch and make the fix. But what about all the code of feature x branch?</p>
<p>If you try to do a <code>git checkout new_branch</code> git will ask you to either commit your code or stash it. You will get a message like this</p>
<pre><code class="lang-bash">error: Your <span class="hljs-built_in">local</span> changes to the following files would be overwritten by checkout:
        &lt;code_file_name&gt;
Please commit your changes or stash them before you switch branches.
</code></pre>
<p>As you can see, it is asking you to either commit or stash. By commiting the code, your code will be safe in the local repository but you don't want to commit half worked code. There might be 100s of logs and unpolished code that you don't want to commit.</p>
<p>This is where stash comes in to save the day. You can easily do <code>git stash</code> and all your code will be saved in a temporary place by git. After stashing you can easily switch and work on the new feature or bug.</p>
<h2 id="heading-unstashing-code">Unstashing Code</h2>
<p>Once you are back to your current branch, you can simply do <code>git stash pop</code> to get your stashed code back.</p>
<p>The best part of stash is that you can stash multiple times. So it is like a stack of code blocks.</p>
<p>You can see all the stashed code by <code>git stash list</code></p>
<p>And you can pop specific stash by doing <code>git stash pop &lt;stash_id&gt;</code></p>
<h1 id="heading-next-steps">Next Steps</h1>
<p>You have learnt quite a lot about git in today's article. This is probably 80% of the commands that you will use in everyday code.</p>
<p>What you don't know yet is <code>rebase</code>, <code>reset</code>, and <code>cherry pick</code>. I am thinking of writing another blog covering these 3 in detail because they are a bit advanced commands.</p>
<p>You can also google and learn about them though.</p>
<h2 id="heading-conclusion">Conclusion</h2>
<p>Well that's it. I hope you learnt something new today. Understanding Git is essential for every developer and I tried to cover all the day-to-day commands. Please drop in your feedback in the comments.</p>
]]></content:encoded></item><item><title><![CDATA[Anidex: A Step-by-Step Journey to Building an Animal Pokedex]]></title><description><![CDATA[Discover Anidex, the ultimate Pokedex for real-world animals, with identification, chatting, offline features, and more for nature enthusiasts]]></description><link>https://cswithiyush.hashnode.dev/anidex-a-step-by-step-journey-to-building-an-animal-pokedex</link><guid isPermaLink="true">https://cswithiyush.hashnode.dev/anidex-a-step-by-step-journey-to-building-an-animal-pokedex</guid><category><![CDATA[AI]]></category><category><![CDATA[Flutter]]></category><category><![CDATA[Hashnode]]></category><category><![CDATA[Frontend Development]]></category><category><![CDATA[AIForTomorrow]]></category><dc:creator><![CDATA[Ayush Pawar]]></dc:creator><pubDate>Fri, 12 Jul 2024 17:36:57 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1720805715903/cb681bfd-2cd4-4940-b375-4fbac5aac664.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h1 id="heading-introduction">Introduction</h1>
<p>This is my official entry to the <strong>#AIForTomorrow</strong> hackathon organized by Hashnode. It has been a long time since I built a project, and this AI hackathon came at the perfect time for me.</p>
<p>The project that I have built is Anidex. <strong>Anidex is your Pokedex but for real-world animals and birds.</strong></p>
<p>GitHub Repo Link: <a target="_blank" href="https://github.com/Spyyy004/anidex/tree/main">https://github.com/Spyyy004/anidex/</a></p>
<p>App Download Link: <a target="_blank" href="https://github.com/Spyyy004/anidex/releases/download/1.0.0/anidex.apk">https://github.com/Spyyy004/anidex/releases/download/1.0.0/anidex.apk</a>  </p>
<p>Website Link : <a target="_blank" href="https://anidex.tech/">https://anidex.tech/</a></p>
<p>Let's see how I got the idea for the project, how I actually built it, the features it possesses, and what my future plans are.</p>
<h1 id="heading-inspiration">Inspiration</h1>
<p>Recently, I went on a one-day hike with my friends and saw a bird I had never seen before. I thought of using Google Lens to identify it, but poor connectivity prevented me from getting any information. I captured an image and later used Lens to search for the bird. While I did find some basic information, I had to visit multiple websites to learn more about it. This tedious process made me realize the need for a more comprehensive solution.</p>
<p>That's when I thought of creating an app that not only identifies animals but also provides detailed information about their habitats, behaviors, and conservation status—all in one place. And if the information seems too dry, users can actually engage with the animal through a fun chat interface.</p>
<p>I envisioned a tool that combines the educational aspects of a traditional field guide with the interactive experience of a chat feature. Imagine being able to point your phone at a bird in your backyard and instantly learn about its species, migration patterns, and even have a conversation with it, just like a Pokémon trainer! This vision led to the creation of Anidex, your digital Pokedex for real-world animals and birds.</p>
<h1 id="heading-features">Features</h1>
<p>Anidex is feature packed. Here is a list of features the app possesses.</p>
<h3 id="heading-scan-and-identify-animals">Scan and Identify Animals</h3>
<p>Imagine being in a park, surrounded by nature's wonders. You whip out your phone, open Anidex, and aim your camera at a beautiful bird perched on a tree branch. With a quick scan, Anidex identifies the bird as a Blue Jay, providing detailed information about its habitat, diet, and distinctive features. The seamless real-time scanning capability powered by Gemini's AI instantly enriches your outdoor experience, turning every hike into a learning adventure.</p>
<h3 id="heading-talk-to-animals">Talk to Animals</h3>
<p>Curiosity piqued? After scanning the Blue Jay, you decide to engage further. With a tap of a button, you enter the "Talk to Blue Jay" feature. The screen lights up with a chat interface where you can ask questions like, "What's your favorite food?" or "Tell me about your nest." Powered by Gemini's AI, the Blue Jay responds with fascinating insights, enhancing your understanding of its lifestyle in a uniquely interactive way.</p>
<h3 id="heading-offline-scanning">Offline Scanning</h3>
<p>Picture this: you're on a remote trail, far from cell service. No worries—Anidex has you covered with its offline scanning feature. Even without an internet connection, you can continue scanning and identifying animals. The app stores essential data locally, ensuring seamless access to information without interruption. Once you're back online, simply sync your scans to update your collection effortlessly.</p>
<h3 id="heading-save-scans">Save Scans</h3>
<p>Back at home, you review your collection of scanned animals. Each entry holds memories of your outdoor adventures and discoveries. With Anidex, saving scans is easy and intuitive. You can revisit details about any animal at any time, whether it's the majestic eagle you spotted last week or the curious fox you encountered yesterday.</p>
<h3 id="heading-favourite-animals">Favourite Animals</h3>
<p>Some animals leave a lasting impression. With Anidex, you can mark them as favourites with a simple tap. Whether it's the rarest species or a personal favourite, keeping track is effortless. Your favourites list becomes a curated gallery of the wildlife you cherish, ready to inspire and delight whenever you revisit it.</p>
<h3 id="heading-leaderboard-and-badges">Leaderboard and Badges</h3>
<p>Feeling competitive? Anidex adds a fun twist with its leaderboard and badges. Every scan contributes to your ranking, earning you badges for milestones like "Explorer" or "Wildlife Enthusiast." See how you stack up against other users, fostering a sense of community and achievement in your wildlife discoveries.</p>
<h3 id="heading-explore">Explore</h3>
<p>Embark on a journey through the Anidex community's collective knowledge. The Explore feature offers a treasure trove of scanned animals contributed by users worldwide. Whether you're researching a specific species or simply browsing, the categorized and searchable database ensures you find what you're looking for with ease.</p>
<h1 id="heading-building-the-app">Building the App</h1>
<p>From the outset, Anidex was designed with one goal: to deliver the ultimate user experience in wildlife exploration. By placing the Scan Page front and center upon installation, users dive right into the app's core functionality without barriers. No sign-in required means immediate access to scanning and exploring animals, fostering a seamless and engaging experience from the very first interaction.</p>
<p>Each feature, from scanning and chatting with animals to saving and exploring wildlife, is crafted to inspire curiosity and connect users with the natural world effortlessly. Anidex isn't just an app—it's a gateway to discovery, empowering users to appreciate and learn about wildlife in ways that are intuitive, immersive, and above all, enjoyable.</p>
<p>The app is built with Flutter and Firebase. The AI features are powered by Gemini 1.5 Pro. It has a total of 10 screens. Since I have a decent hands on experience in Flutter and Firebase, It didn't take much time for me to code the UI and connect it to the DB.</p>
<p>Talking in depth about the database. I am using NoSQL database. I have users, scans, leaderboard, and badges collection.</p>
<p>This is my user schema</p>
<pre><code class="lang-json">{
  <span class="hljs-attr">"badges"</span>: [<span class="hljs-string">"string"</span>],
  <span class="hljs-attr">"favorites"</span>: [<span class="hljs-string">"string"</span>],
  <span class="hljs-attr">"firstName"</span>: <span class="hljs-string">"string"</span>,
  <span class="hljs-attr">"lastName"</span>: <span class="hljs-string">"string"</span>,
  <span class="hljs-attr">"phoneNumber"</span>: <span class="hljs-string">"string"</span>,
  <span class="hljs-attr">"profilePic"</span>: <span class="hljs-string">"string"</span>,
  <span class="hljs-attr">"scans"</span>: [<span class="hljs-string">"string"</span>],
  <span class="hljs-attr">"createdAt"</span>: <span class="hljs-string">"timestamp"</span>,
  <span class="hljs-attr">"userId"</span>: <span class="hljs-string">"string"</span>,
}
</code></pre>
<p>This is my Scan schema</p>
<pre><code class="lang-json">{
  <span class="hljs-attr">"imagePath"</span>: <span class="hljs-string">"string"</span>,
   <span class="hljs-attr">"scanId"</span>: <span class="hljs-string">"string"</span>,
  <span class="hljs-attr">"scanData"</span>: {
    <span class="hljs-attr">"animalIdentification"</span>: <span class="hljs-string">"string"</span>,
    <span class="hljs-attr">"basicInformation"</span>: {
      <span class="hljs-attr">"behavior"</span>: <span class="hljs-string">"string"</span>,
      <span class="hljs-attr">"classification"</span>: {
        <span class="hljs-attr">"class"</span>: <span class="hljs-string">"string"</span>,
        <span class="hljs-attr">"family"</span>: <span class="hljs-string">"string"</span>,
        <span class="hljs-attr">"genus"</span>: <span class="hljs-string">"string"</span>,
        <span class="hljs-attr">"kingdom"</span>: <span class="hljs-string">"string"</span>,
        <span class="hljs-attr">"order"</span>: <span class="hljs-string">"string"</span>,
        <span class="hljs-attr">"phylum"</span>: <span class="hljs-string">"string"</span>,
        <span class="hljs-attr">"species"</span>: <span class="hljs-string">"string"</span>
      },
      <span class="hljs-attr">"commonName"</span>: <span class="hljs-string">"string"</span>,
      <span class="hljs-attr">"conservationStatus"</span>: <span class="hljs-string">"string"</span>,
      <span class="hljs-attr">"diet"</span>: <span class="hljs-string">"string"</span>,
      <span class="hljs-attr">"geographicDistribution"</span>: [
        <span class="hljs-string">"string"</span>
      ],
      <span class="hljs-attr">"habitat"</span>: <span class="hljs-string">"string"</span>,
      <span class="hljs-attr">"interestingFacts"</span>: [
        <span class="hljs-string">"string"</span>
      ],
      <span class="hljs-attr">"physicalDescription"</span>: <span class="hljs-string">"string"</span>,
      <span class="hljs-attr">"rarity"</span>: <span class="hljs-string">"number"</span>,
      <span class="hljs-attr">"scientificName"</span>: <span class="hljs-string">"string"</span>,
      <span class="hljs-attr">"type"</span>: <span class="hljs-string">"string"</span>
    },
    <span class="hljs-attr">"timestamp"</span>: <span class="hljs-string">"timestamp"</span>,
    <span class="hljs-attr">"userId"</span>: <span class="hljs-string">"string"</span>
  }
}
</code></pre>
<p>I've implemented robust error handling mechanisms to ensure smooth performance across various user interactions. Additionally, I've optimized data fetching and storage processes to maintain app responsiveness even under heavy user traffic. By adhering to these best practices from the outset, Anidex is poised to deliver a reliable and seamless experience for all users.</p>
<h2 id="heading-challenges">Challenges</h2>
<p>The biggest challenge was to make Gemini give me data in the format I wanted. I experimented around with various prompts to get data in the perfect format.</p>
<p>Another big challenge was offline scans and syncing data. I used the path_provider and connectivity package to get access to local storage and save images when the user is not connected to the internet. Here is the code for storing and retriving images from local storage.</p>
<pre><code class="lang-plaintext">  Future&lt;void&gt; _loadLocalScans() async {
    try {
      final directory = await getApplicationDocumentsDirectory();
      if (!await Directory(directory.path).exists()) {
        print('Directory does not exist: ${directory.path}');
        return;
      }
      List&lt;LocalScanItem&gt; scans = await fetchLocalScans(directory.path);
      setState(() {
        localScans = scans;
      });
    } catch (e) {
      print('Error loading local scans: $e');
    }
  }

  Future&lt;String?&gt; saveImageLocally(XFile imageFile) async {
    try {
      // Get the local app directory path using path_provider
      final directory = await getApplicationDocumentsDirectory();
      final imagePath = '${directory.path}/${DateTime.now().millisecondsSinceEpoch}.jpg';

      // Ensure directory exists
      await Directory(directory.path).create(recursive: true);

      // Read the file as bytes
      final bytes = await imageFile.readAsBytes();

      // Write the bytes to a new file
      final file = File(imagePath);
      await file.writeAsBytes(bytes);

      return imagePath;
    } catch (e) {
      print('Error saving image locally: $e');
      return null;
    }
  }
</code></pre>
<p>I also restricted access to sections like My Scans, Favourites, and My Profile when disconnected because all this data is fetched in realtime from the Firebase DB for now.</p>
<p>I am not a good designer and I always struggle building good designs. Thankfully, the pinterest community helped me this time. I found some decent design inspirations for a pokedex style info card.</p>
<p>The app has a plain and minimalistic design. The typography is based on poppins and consistent throughout the app. Here are a few screenshots of the current app.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1720798457795/5f0ccf87-f817-4569-aefc-16c276be8619.png" alt class="image--center mx-auto" /></p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1720798486067/cf1057f6-c950-4de1-8bf5-607f87a48909.png" alt class="image--center mx-auto" /></p>
<h1 id="heading-impact">Impact</h1>
<p>Anidex aims to transform wildlife exploration by making it easy and immediate to identify animals through innovative technology.</p>
<p>By removing the need for a sign-in page, the app ensures that learning about wildlife is accessible to everyone from the start. This approach encourages users to engage with nature effortlessly, fostering a deeper connection and appreciation for biodiversity.</p>
<p>With features like real-time animal chats and access to scan animals without internet, Anidex enhances learning opportunities and promotes conservation awareness in a user-friendly way.</p>
<p>Whether users are exploring local habitats or encountering wildlife in remote areas, the app inspires curiosity and encourages environmental stewardship. Anidex is designed not just as an app, but as a tool that empowers individuals to explore, learn, and contribute to the conservation of our natural world.</p>
<h1 id="heading-future-plans">Future Plans</h1>
<p>As Anidex continues to evolve, I have exciting plans to enrich its features and expand its impact:</p>
<p><strong>1. Enhanced Filtering and Exploration</strong></p>
<ul>
<li>Currently, Anidex offers a search bar for quick access to species information. In the pipeline are advanced filtering options, allowing users to sort scans and explore wildlife by various categories such as habitat, rarity, and region. These enhancements will empower users to tailor their wildlife discoveries to specific interests and deepen their learning experiences.</li>
</ul>
<p><strong>2. Diverse Leaderboards</strong></p>
<ul>
<li>While the current leaderboard celebrates total scans, upcoming updates will introduce specialized leaderboards. These will highlight achievements based on animal rarity, geographic location, and user contributions. By gamifying exploration through different metrics, Anidex will foster friendly competition and community engagement among wildlife enthusiasts worldwide.</li>
</ul>
<p><strong>3. AI-Powered Quizlet</strong></p>
<ul>
<li>Imagine starting your day with a fun and informative challenge—Anidex will soon feature a daily AI-powered quizlet. Each quiz question will offer insights into animal behaviors, habitats, and conservation efforts. Participants can earn points and compete on a dedicated leaderboard, encouraging regular engagement while expanding their wildlife knowledge.</li>
</ul>
<p><strong>4. iOS Development</strong></p>
<ul>
<li>Bringing Anidex to iOS devices is a top priority. While integrating camera and storage features poses unique challenges on iOS, I'm committed to delivering a seamless experience across platforms. Stay tuned as we navigate the app store guidelines and ensure Anidex reaches a broader audience passionate about wildlife exploration.</li>
</ul>
<p>These future updates reflect Anidex's ongoing commitment to enhancing user experience, fostering community engagement, and promoting wildlife conservation through innovative technology. I look forward to sharing these developments with you as we continue to grow and refine Anidex.</p>
<h1 id="heading-conclusion">Conclusion</h1>
<p>Creating Anidex has been a long-awaited project for me, driven by my love for wildlife and technology. It's become one of my favorite side projects because it serves a practical purpose and offers fun for everyone.</p>
<p>Anidex isn't just an app—it's a tool that helps you discover and learn about wildlife effortlessly. Whether you're identifying birds in your backyard or exploring animals on a hike, Anidex makes it easy and enjoyable.</p>
<p>Looking ahead, we're working on adding more features like filters and daily quizzes, and we're excited to bring Anidex to iOS soon. Our goal remains to make wildlife exploration accessible and engaging for everyone.</p>
<p>Join me on this journey with Anidex as we continue to grow and make learning about wildlife a part of everyday fun.</p>
]]></content:encoded></item><item><title><![CDATA[Key Challenges Faced by Every College Graduate]]></title><description><![CDATA[Tips for college graduates on landing jobs, building projects, and navigating the tech industry successfully amid challenges]]></description><link>https://cswithiyush.hashnode.dev/key-challenges-faced-by-every-college-graduate</link><guid isPermaLink="true">https://cswithiyush.hashnode.dev/key-challenges-faced-by-every-college-graduate</guid><category><![CDATA[engineering]]></category><category><![CDATA[General Advice]]></category><category><![CDATA[Blogging]]></category><category><![CDATA[Flutter]]></category><dc:creator><![CDATA[Ayush Pawar]]></dc:creator><pubDate>Sun, 12 May 2024 15:27:14 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/stock/unsplash/gXUEQEtpjMs/upload/cff4fa041621da6b8cb86eed731c61f6.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h1 id="heading-introduction">Introduction</h1>
<p>In today’s world, the competition for grabbing a fresher job in the software industry is as hard as grabbing a good seat after JEE. Folks are confused as hell about what to do and what not to do. The everlasting debate of DSA vs Dev confuses young folks even more.</p>
<p>Today, I will share what I did, what I ignored, and what you can do to get the best possible outcome from your current situation. Keep in mind that I am only considering folks who have no hopes from their college for a good placement.</p>
<h1 id="heading-my-journey">My Journey.</h1>
<p>I began my <a target="_blank" href="http://B.Tech">B.Tech</a> journey in 2019, interrupted by COVID. Explored various tech areas, and settled on Flutter app development. Invested in Flutter course, landed Google STEP intern OA but lacked DSA skills. Started learning DSA, realized its endless nature, and focused on earning money through internships and hackathons. Eventually dedicated 7 months to DSA, succeeded in securing multiple job offers, and chose on-campus placement for better pay.</p>
<p>As you can see, I did everything I could. My fuel was money but I enjoyed coding too. That’s why I had good projects and I landed internships in the first place. Anyway, let’s move on to what <strong>you guys can do</strong>.</p>
<h1 id="heading-scenario-1">Scenario 1</h1>
<p>So, I will divide this into 2 scenarios. Scenario 1 is you have just entered college or are in your second year. If you are reading this now, Congrats! you have potentially saved yourself. You have a lot of time ahead. You have time to experiment and fail. That’s the benefit of starting early. I started with game dev, AR/VR and I failed. Whatever might be the reason, I quit it and picked up something else.</p>
<p>The same goes for you. Pick a thing. AI/ML, Web Dev, Blockchain, App-Dev etc. Pick anything and just start. The content available today is much better than the one available 4 years ago. If you don’t like one, do something else. You will land on one thing and then just keep doing it. Keep getting better by learning advanced topics. You will be internship-ready before you know it. I got my first Flutter internship and I only knew how to make API calls and connect the app to DB. I didn’t know advanced shit like dependency injection, offline storage management, advanced state management, MVVM, MVC, lazy loading etc etc.</p>
<p>If you don’t find anything interesting, start with DSA. You might enjoy competitive programming. If you don’t like that too, then sorry buddy computer science isn’t for you. Maybe explore UI/UX.</p>
<p>Once you enter the second term of your third year, start with DSA. Striver has the best DSA content to get good enough to land a job. I followed his 180 questions sheet initially and then after that, I just did questions on my own.</p>
<p>Make use of platforms like Unstop, Internshala, remoteok, and Twitter to get internships. For off-campus, getting a job by converting an intern to full-time is one of the easiest ways.</p>
<h1 id="heading-scenario-2">Scenario 2</h1>
<p>Scenario 2 is for folks who are in their 3rd year or 4th year. This is a tricky scenario because you don’t have time to do both. I mean if you can parallelly handle both that is great but the problem with that is you will have two half-filled jugs rather than one filled jug. If you started earlier, you could have filled one jug completely and then started filling the other one. </p>
<p>Now, you have to make a choice. One good way to tackle this is to look at what your friends are doing. By friends I mean the ones who have already got an internship or won hackathons. If you don’t have such friends, then make one. Ask them how they got the internship, what the company asked them, DSA or development. You can move forward from there. If it is DSA that you want to do, then just do a 180-question sheet and you will be decent enough to crack jobs. If you want to do development, then go with an online YouTube tutorial video and build a clone. Building a clone is not bad if you understand what is happening and how are things working. Once you have built it, try building something else without a tutorial help. Just use Google and official docs. No copy-pasting code from Chat GPT as well.</p>
<p>You must understand that time is against you and you have to put in extra effort. You will have to do things parallel if needed.</p>
<h1 id="heading-additional-tips">Additional Tips</h1>
<p>Here are a few more tips to land more interviews or make better decisions</p>
<ol>
<li><p><strong>Have a good resume</strong>. If you don’t know what good is, ask someone to review it for you. ( A senior, a recruiter on LinkedIn). You can even approach me if you feel I am worthy to do that.</p>
</li>
<li><p><strong>Have at least 3 working projects on GitHub</strong>. You don’t need to have a fancy profile. Just have 3 self-made projects. You must be confident with those projects. I can ask you anything about it and you must be ready to answer.</p>
</li>
<li><p><strong>Engage with early-stage company founders/CTOs on Twitter/Linkedin</strong>. Early-stage founders are always looking for talent. They will be happy to entertain you if you approach them online. It just saves their time in for searching talent. Even if you don’t land a job/internship, you will make a connection</p>
</li>
<li><p><strong>Think a lot before buying courses.</strong>  I am not saying don’t buy, but just think. Think if this content (same quality) is freely available, and think if the creator is credible enough or not. Think twice before spending your or your parents’ hard-earned money.</p>
</li>
</ol>
<h1 id="heading-open-source">Open Source?</h1>
<p>This term has taken the Indian student community by storm. Open-source this open source that. First of all, open source is not easy. I mean it is easy to find scammy projects and increase your PR count but it is not easy to make actual contributions.</p>
<p>Only actual contributions lead to job opportunities. No one is offering you a job if you make a readme change. Not saying making readme change is bad, but don’t expect to land a job by doing that. You will have to make consistent meaningful contributions to complex projects before hearing back.</p>
<p>To make contributions of this level, you must have good knowledge of the tech stack. So don’t jump onto open source straightaway. It will just break you. First, go and learn. Build your projects and then go take the challenge of open-source.</p>
<p>I can write a whole article about open-source and how to approach it.</p>
<h1 id="heading-yes-luck-matters-and-you-cant-do-anything-about-it">Yes, Luck Matters and you can’t do anything about it.</h1>
<p>No matter how hard you work, luck will always come into play. You might get a grumpy interviewer, your internet might be unstable, and you might forget the implementation of a code that you have done 10 times before. Anything can happen on the interview day. It can be for good or for bad but just remember one thing. <strong>You only need 1 one acceptance.</strong> </p>
<p>No point in crying about diversity hiring, cheating, and luck. Also, no point in blaming DSA. Whether you enjoy it or not, you have to do it now. Because companies judge you by that. It is what it is. You can cry about it on social media but this is how the world works.</p>
<p>Some companies won’t ask you DSA in the interviews but when you start the job, you will need basic logic to write good code. You can’t write shitty code in good product companies. Your PR will be rejected straightaway without any comments and believe me it will hurt.</p>
<p>So keep your development ego aside and learn basic DSA and logic building. Will help you throughout your life.</p>
<h1 id="heading-ideal-salary">Ideal Salary?</h1>
<p>The current tech market for freshers is fucked up. Long gone are the days where freshers where being paid 30LPA base salary happily by companies.</p>
<p>The market is correcting itself and salaries are becoming realistic for freshers. The ideal salary to start would be 8-12LPA for a fresher. You must be more than happy if you get this in the current market. If you get more, just take and run away. If you get less, try to negotiate.</p>
<p>Obviously service based companies are not gonnna pay this much so I am talking about product companies. Not very early stage though.</p>
<h1 id="heading-conclusion">Conclusion</h1>
<p>Well, that was a huge rant. Anyway, I have said what I think about the current scenario and what you guys can do. I am attaching important websites where you can look for hackathons, resume builders, and internship/full-time sites.</p>
<h1 id="heading-resources">Resources</h1>
<p>Internships &amp; Jobs:</p>
<ol>
<li><p><a target="_blank" href="https://internshala.com/">Internshala</a></p>
</li>
<li><p><a target="_blank" href="https://www.ycombinator.com/jobs">Ycombinator</a></p>
</li>
<li><p><a target="_blank" href="https://remoteok.com/?location=IN">RemoteOK</a></p>
</li>
</ol>
<p>Hackathons</p>
<ol>
<li><p><a target="_blank" href="https://devpost.com/">Devpost</a></p>
</li>
<li><p><a target="_blank" href="https://devfolio.co/">Devfolio</a></p>
</li>
<li><p><a target="_blank" href="https://mlh.io/seasons/2024/events">MLH Hackathons</a></p>
</li>
</ol>
<p>Resume Builders</p>
<ol>
<li><p><a target="_blank" href="https://www.overleaf.com/">Overleaf</a></p>
</li>
<li><p><a target="_blank" href="https://rxresu.me/">Reactive Resume</a></p>
</li>
<li><p><a target="_blank" href="http://creddle.io/">Creddle</a></p>
</li>
</ol>
]]></content:encoded></item><item><title><![CDATA[User Registeration : Secure Authentication Service]]></title><description><![CDATA[Learn how to implement user registration in your custom authentication service. This step-by-step guide covers the essentials of building a secure…]]></description><link>https://cswithiyush.hashnode.dev/user-registeration-secure-authentication-service</link><guid isPermaLink="true">https://cswithiyush.hashnode.dev/user-registeration-secure-authentication-service</guid><category><![CDATA[backend]]></category><category><![CDATA[Beginner Developers]]></category><category><![CDATA[Programming Blogs]]></category><category><![CDATA[coding]]></category><category><![CDATA[Tutorial]]></category><dc:creator><![CDATA[Ayush Pawar]]></dc:creator><pubDate>Sun, 29 Oct 2023 09:56:12 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1698573289328/8593871d-3e3c-4541-b3ef-3b56582b1688.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h1 id="heading-introduction">Introduction</h1>
<p>In today's article, we will continue building our secure authentication service. Today's topic of concern is register and log in API.</p>
<p>We will see how we can register a user with an email id password and then log him/her in by providing him/her an auth token. We will also use rate-limiting and mongoose to store the user's details. So let's get started.bac</p>
<h1 id="heading-user-schema">User Schema</h1>
<p>Before making our api, we must decide how our user schema should be. It is very important to clearly define our schema.</p>
<p>For our app, the user schema would look something like this</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> userSchema = <span class="hljs-keyword">new</span> Schema ({
    <span class="hljs-attr">email</span>: {<span class="hljs-attr">type</span> : <span class="hljs-built_in">String</span>},
    <span class="hljs-attr">password</span>: {<span class="hljs-attr">type</span> : <span class="hljs-built_in">String</span>},
    <span class="hljs-attr">userName</span>: {<span class="hljs-attr">type</span> : <span class="hljs-built_in">String</span>},
    <span class="hljs-attr">phoneNumber</span>: {<span class="hljs-attr">type</span> : <span class="hljs-built_in">String</span>}
})
</code></pre>
<p>We will have email, password, username, and phone number fields. We can make some of these fields required by adding the <code>required: true</code> beside the <code>type</code> key. I don't need anything to be required because we are supporting 2 types of sign-up. One is via email password and the other is via mobile and OTP.</p>
<p>Usually in real-world apps, the user schema is vast and it varies from app to app. Some apps would keep other things like profile picture, default address, default payment method, etc in the user schema as well.</p>
<h1 id="heading-ideation">Ideation</h1>
<p>Now that we have defined our schema, let's have a look at the flow chart of how a registration request should happen</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1698562454983/c6fa3bb2-571b-4725-aa8a-10b58425afd8.png" alt class="image--center mx-auto" /></p>
<p>Pretty simple right?</p>
<p>Let's execute this flow chart one box at a time.</p>
<h1 id="heading-execution">Execution</h1>
<h2 id="heading-step-1">Step 1</h2>
<p>Since the client is sending a request, we have to catch the request somehow. Also, where is the client sending the request to? Who decides that? We do.</p>
<p>We create a unique endpoint where all the clients will send the request if they want to register a user. In all the URLs the base url is common. For example amazon.com is the base URL and amazon.com/orders or amazon.com/wishlist are unique endpoints. /orders and /wishlist is the endpoint.</p>
<p>A structured app has very well-defined endpoints. There are a lot of do's and don't while creating your endpoints. There are tons of blogs/videos out there explaining the dos and don'ts of endpoint creation.</p>
<p>Since we are creating an auth service and we are currently using our localhost, all our endpoints would fall under this category `<a target="_blank" href="http://localhost:3000/auth">http://localhost:3000/auth</a>`.</p>
<p>So our register endpoint would be `<a target="_blank" href="http://localhost:3000/auth">http://localhost:3000/auth</a>/register`. Similarly, we will have endpoints for login, otp , get-users etc.</p>
<h2 id="heading-step-2">Step 2</h2>
<p>Now that we have decided on our endpoint, let's catch the request and validate it. Check out the code below for the same.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> validateRegisterRequest = <span class="hljs-function">(<span class="hljs-params">req,res,next</span>) =&gt;</span> {

  <span class="hljs-keyword">const</span> {body} = req

  <span class="hljs-keyword">if</span>(!body || !body.email  || !body.password) {
    <span class="hljs-keyword">return</span> sendErrorResponse(res,consts.STATUS_CODES.FOUR_HUNDERD, strings.ERROR_MESSAGES.NO_BODY_FOUND)
  }

  <span class="hljs-keyword">if</span>(!isValidEmail(body.email)){
    <span class="hljs-keyword">return</span> sendErrorResponse(res,consts.STATUS_CODES.FOUR_HUNDERD, strings.ERROR_MESSAGES.VALID_EMAIL)
  }

  <span class="hljs-keyword">if</span>(!isValidPassword(body.password)) { 
    <span class="hljs-keyword">return</span> sendErrorResponse(res,consts.STATUS_CODES.FOUR_HUNDERD, strings.ERROR_MESSAGES.VALID_PASSWORD)
  }

  next()

}
</code></pre>
<p>So what's happening here? For now, let's assume, somehow the <code>validateRegisterRequest()</code> function gets triggered when a client sends a request to the register endpoint. The register API would be a POST API. If you don't know what is POST, GET, PUT, and DELETE or what is REST in general, I would recommend you give this <a target="_blank" href="https://medium.com/@9cv9official/what-are-get-post-put-patch-delete-a-walkthrough-with-javascripts-fetch-api-17be31755d28">article a quick read</a>.</p>
<p>Every POST request has a body. We will extract the body from our req parameter. We will check if the body, email, and password exist or not. If not, we will call our generic <code>sendErrorResponse</code> function and pass it our response object, the status code we want to send, and the error message.</p>
<p>But where is this <code>sendErrorReponse()</code> present ? There is no correct answer to this. You can either create it in utils, or you can create a whole new error service. For now, I am showing all the stuff that is present in my error service.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> generalErrorMessage = {
    <span class="hljs-attr">error</span>: <span class="hljs-string">""</span>,
    <span class="hljs-attr">message</span>: <span class="hljs-string">""</span>
}

<span class="hljs-keyword">const</span> statusCodeToErrorTitle = {
    <span class="hljs-number">400</span>: <span class="hljs-string">"Bad Request Error"</span>,
    <span class="hljs-number">401</span>: <span class="hljs-string">"Unauthorized"</span>,
    <span class="hljs-number">403</span>: <span class="hljs-string">"Forbidden"</span>,
    <span class="hljs-number">404</span>: <span class="hljs-string">"Not Found"</span>,
    <span class="hljs-number">405</span>: <span class="hljs-string">"Method Not Allowed"</span>,
    <span class="hljs-number">500</span>: <span class="hljs-string">"Internal Server Error"</span>,
    <span class="hljs-number">502</span>: <span class="hljs-string">"Bad Gateway"</span>,
    <span class="hljs-comment">// Add more status codes and titles as needed</span>
}


<span class="hljs-keyword">const</span> sendErrorResponse = <span class="hljs-function">(<span class="hljs-params">res, status, errorMessage</span>) =&gt;</span> {
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Error me aagaya"</span>)
    setErrorMessage(errorMessage,status)
    <span class="hljs-keyword">return</span> res.status(status).json(generalErrorMessage);
  };

<span class="hljs-keyword">const</span> setErrorMessage = <span class="hljs-function">(<span class="hljs-params">errorMessage,status</span>) =&gt;</span> {
    generalErrorMessage.message = errorMessage
    generalErrorMessage.error = statusCodeToErrorTitle[status]
}
</code></pre>
<p><code>return res.status(status).json(generalErrorMessage);</code> This line will return a JSON to our client with the status code <code>status</code> which we pass as an argument.</p>
<p>If everything is validated and there are no error responses sent. We call a <code>next()</code>. What is this next? Where is this coming from?</p>
<p>In simple terms, <code>next()</code> says, "I'm done with my part; let's move on to the next task in handling this request." It's like passing the baton in a relay race, where each runner (middleware/controller) does their part and then passes the baton (control) to the next runner (middleware/controller) until the race (request processing) is completed.</p>
<h2 id="heading-step-3">Step 3</h2>
<p>In the next step, we will check if our user already exists or not. To do that, we will need to query our database. Before that, we will need to create our schema and create a new model based on that schema. We will then run our queries on that model.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> mongoose = <span class="hljs-built_in">require</span>(<span class="hljs-string">'mongoose'</span>)
<span class="hljs-built_in">require</span>(<span class="hljs-string">'dotenv'</span>).config()

<span class="hljs-keyword">const</span> Schema = mongoose.Schema

<span class="hljs-keyword">const</span> userSchema = <span class="hljs-keyword">new</span> Schema ({
    <span class="hljs-attr">email</span>: {<span class="hljs-attr">type</span> : <span class="hljs-built_in">String</span>},
    <span class="hljs-attr">password</span>: {<span class="hljs-attr">type</span> : <span class="hljs-built_in">String</span>},
    <span class="hljs-attr">userName</span>: {<span class="hljs-attr">type</span> : <span class="hljs-built_in">String</span>},
    <span class="hljs-attr">phoneNumber</span>: {<span class="hljs-attr">type</span> : <span class="hljs-built_in">String</span>}
})

<span class="hljs-keyword">const</span> userModel = mongoose.model(<span class="hljs-string">'User'</span>,userSchema)
</code></pre>
<p>Create a new file called db.js and write the above code in it.</p>
<p>Remember the <code>connectToDb()</code> from the last article? We will write it's execution in this file. We will need that function to connect to our db and then only we can run queries and create schemas.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">async</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">connectDB</span>(<span class="hljs-params"></span>) </span>{
    <span class="hljs-keyword">try</span> {
        <span class="hljs-keyword">await</span> mongoose.connect(process.env.MONGO_URI, {
            <span class="hljs-attr">useNewUrlParser</span>: <span class="hljs-literal">true</span>,
            <span class="hljs-attr">useUnifiedTopology</span>: <span class="hljs-literal">true</span>,
        });
        <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'Connected to the database'</span>);
    } <span class="hljs-keyword">catch</span> (error) {
        <span class="hljs-built_in">console</span>.error(<span class="hljs-string">'Error connecting to the database:'</span>, error);
    }
</code></pre>
<p>If you read the last article, you would remember that we created an env file and stored our secret keys and constants there. So Mongo URI is also a secret url that we dont want to share with anyone because it contains credentials of our Mongo account.</p>
<p>You will have to create your mongo uri by following these steps.</p>
<ol>
<li><p>Go to MongoDB's official website. On the dashboard, there will be a connect button, press it. Then, select the Atlas option and then the official docs will guide you.</p>
</li>
<li><p>You can <a target="_blank" href="https://www.mongodb.com/docs/drivers/node/current/quick-start/connect-to-mongodb/">follow this article</a> as well if you get stuck somewhere.</p>
</li>
</ol>
<p>Once you are done creating the connection string, put it in your env file and use it like how I have used it in the above code.</p>
<p>Now, let's focus on our main part, checking if a user exists or not. For that, we will create a function called <code>registerUser</code> and call our database service function to find the user in the db.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> dbServices = <span class="hljs-built_in">require</span>(<span class="hljs-string">'../helpers/db'</span>)

<span class="hljs-keyword">const</span> registerUser = <span class="hljs-keyword">async</span> (req,res,next) =&gt; {
  <span class="hljs-keyword">const</span> { body } = req

  <span class="hljs-keyword">const</span> doesUserExist = <span class="hljs-keyword">await</span> dbServices.findUser(body.email)
  <span class="hljs-keyword">if</span>(doesUserExist){
    <span class="hljs-keyword">return</span> sendErrorResponse(res, consts.STATUS_CODES.FOUR_HUNDERD, <span class="hljs-string">"User exists with the same email"</span>)
  }
}
</code></pre>
<p>Remember the <code>next()</code> in the validation function? This is the function that the next triggers. How it does that, I will tell you soon. For now, let's see what's happening above.</p>
<ol>
<li><p>We extract the body from the request. We make a call to our <code>dbServices.findUser()</code> and pass the email.</p>
</li>
<li><p><code>dbServices</code> contains a lot of functions that we have written in db.js and <code>findUser</code> is one of them. We will slowly discover all the functions present in this service as our auth service progresses.</p>
</li>
</ol>
<p>Let's have a look at our <code>findUser()</code> in db.js</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">async</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">findUser</span>(<span class="hljs-params">userEmail</span>) </span>{
    <span class="hljs-keyword">const</span> user = <span class="hljs-keyword">await</span> userModel.findOne({<span class="hljs-attr">email</span>:userEmail})
    <span class="hljs-keyword">return</span> !!user <span class="hljs-comment">// !! converts falsy values like null, undefined to false</span>
}
</code></pre>
<p>Just a two-line function. We run a findOne query on our user model. What it does is it goes through all the documents present in the user collection and searches for a user who has the email as <code>userEmail</code>.</p>
<p>If it doesn't find any user, it returns undefined.</p>
<p>Back in our <code>registerUser()</code>we check if the user exists or not. If yes, we send back an error response to our client. If no, we then register our user in the db.</p>
<h2 id="heading-step-4">Step 4</h2>
<p>Before registering the user, we have to hash the password of the user. For that, we will use bcrypt library's hashing password function.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> hashPassword = <span class="hljs-keyword">async</span> (password) =&gt; {
<span class="hljs-keyword">return</span> <span class="hljs-keyword">new</span> <span class="hljs-built_in">Promise</span>(<span class="hljs-function">(<span class="hljs-params">resolve, reject</span>) =&gt;</span> {
  bcrypt.hash(password, <span class="hljs-number">10</span>, <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">err, hash</span>) </span>{
    <span class="hljs-keyword">if</span>(err){
      reject(err)
    }
    <span class="hljs-keyword">else</span> {
      resolve(hash)
    }
  });
})
}
</code></pre>
<p>Since the hash function is asynchronous, we will have to wrap it in a promise and return the result we get. It will either resolve or reject. If it resolves, we will return the hash to the previous function, or we will return the error and it will be handled in the catch block.</p>
<p>The hash function takes 2 parameters, the string to hash, and the level of salt. The higher the level, the more encrypted it is but the more time it takes to create the hash.</p>
<p>Here is a comparison of how much time it takes.</p>
<pre><code class="lang-javascript"><span class="hljs-number">1</span>/<span class="hljs-number">23</span>/<span class="hljs-number">2014</span>  Intel Core i7<span class="hljs-number">-2700</span>K CPU @ <span class="hljs-number">3.50</span> GHz

| Salt | Iterations        |    Duration |
|------|-------------------|-------------|
|  <span class="hljs-number">8</span>   |    <span class="hljs-number">256</span> iterations |     <span class="hljs-number">38.2</span> ms | &lt;-- minimum allowed by BCrypt
|  9   |    512 iterations |     74.8 ms |
| 10   |  1,024 iterations |    152.4 ms | &lt;-- current default (BCRYPT_COST=10)
| 11   |  2,048 iterations |    296.6 ms |
| 12   |  4,096 iterations |    594.3 ms |
| 13   |  8,192 iterations |  1,169.5 ms |
| 14   | 16,384 iterations |  2,338.8 ms |
| 15   | 32,768 iterations |  4,656.0 ms |
| 16   | 65,536 iterations |  9,302.2 ms |
</code></pre>
<p>Going back to our <code>registerUser</code> function</p>
<pre><code class="lang-javascript"> <span class="hljs-keyword">const</span> registerUser = <span class="hljs-keyword">async</span> (req,res,next) =&gt; {
  <span class="hljs-keyword">const</span> { body } = req

  <span class="hljs-keyword">const</span> doesUserExist = <span class="hljs-keyword">await</span> dbServices.findUser(body.email)
  <span class="hljs-keyword">if</span>(doesUserExist){
    <span class="hljs-keyword">return</span> sendErrorResponse(res, consts.STATUS_CODES.FOUR_HUNDERD, <span class="hljs-string">"User exists with the same email"</span>)
  }

  <span class="hljs-keyword">try</span> {
    body.password = <span class="hljs-keyword">await</span> hashPassword(body.password)

  }
  <span class="hljs-keyword">catch</span>(e) {
    <span class="hljs-keyword">return</span> sendErrorResponse(res, consts.STATUS_CODES.FIVE_HUNDERD, <span class="hljs-string">"User registeration failed"</span>)
  }

}
</code></pre>
<h2 id="heading-step-5">Step 5</h2>
<p>Now only one step remains, that is to finally register our user.</p>
<p>For that, we will write another function in our <code>dbServices</code>.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">async</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">registerUser</span>(<span class="hljs-params">body</span>) </span>{
    <span class="hljs-keyword">try</span> {
        <span class="hljs-keyword">const</span> user = <span class="hljs-keyword">new</span> userModel({<span class="hljs-attr">email</span>:body.email,<span class="hljs-attr">password</span>:body.password , <span class="hljs-attr">phoneNumber</span> : <span class="hljs-string">""</span>})
        <span class="hljs-keyword">await</span> user.save()
        <span class="hljs-keyword">return</span> user
    }
    <span class="hljs-keyword">catch</span>(e) {
        <span class="hljs-keyword">throw</span> ErrorEvent
    }
}
</code></pre>
<p>This is a very simple function. It creates a new user model instance and then calls the save method on it which creates a new document in our User table.</p>
<p>We then return our user and if there is any error in the process, we throw the error which will be caught by the catch block in our <code>registerUser</code> function.</p>
<p>Our <code>registerUser</code> function will look like this now.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> registerUser = <span class="hljs-keyword">async</span> (req,res,next) =&gt; {
  <span class="hljs-keyword">const</span> { body } = req
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Aagaya register"</span>)
  <span class="hljs-keyword">const</span> doesUserExist = <span class="hljs-keyword">await</span> dbServices.findUser(body.email)
  <span class="hljs-keyword">if</span>(doesUserExist){
    <span class="hljs-keyword">return</span> sendErrorResponse(res, consts.STATUS_CODES.FOUR_HUNDERD, <span class="hljs-string">"User exists with the same email"</span>)
  }


  <span class="hljs-keyword">try</span> {
    body.password = <span class="hljs-keyword">await</span> hashPassword(body.password)
    <span class="hljs-keyword">await</span> dbServices.registerUser(body)
    <span class="hljs-keyword">return</span> res.status(consts.STATUS_CODES.TWO_HUNDRED_ONE).json({
      <span class="hljs-string">"message"</span> : <span class="hljs-string">"User registered successfully"</span>
    })
  }
  <span class="hljs-keyword">catch</span>(e) {
    <span class="hljs-keyword">return</span> sendErrorResponse(res, consts.STATUS_CODES.FIVE_HUNDERD, <span class="hljs-string">"User registeration failed"</span>)
  }

}
</code></pre>
<p>That's it. We have successfully followed all the steps in registering the user. But wait? how does all this get triggered in the first place? Let's find out</p>
<h1 id="heading-routes-amp-final-touch">Routes &amp; Final Touch</h1>
<p>To understand how this works, think of the endpoint as a route. A route has multiple checkpoints. <code>validateRequest</code> and <code>registerUser</code> were our two checkpoints. Different routes can have different checkpoints.</p>
<p>Some might need 10 checkpoints and some might need only 1. Some of the checkpoints are common and can be used in multiple routes. So to make things easy, we put all those checkpoints in a folder called <strong>middlewares.</strong></p>
<p>So if you think, validating an incoming request should be in our middleware because every request needs to be validated before processing it and working with it. You can create a common request validation function or you can create specific validation functions. All of them are usually present in the middleware.</p>
<p>The checkpoints where we write the logic related to our endpoint are present in <strong>controllers.</strong></p>
<p>Registering a user is a core logical part of this endpoint so we put it in our controllers folder.</p>
<p>Now there is something called routes as well. The routes folder is where you define all the routes of your service.</p>
<pre><code class="lang-javascript">
<span class="hljs-keyword">const</span> express = <span class="hljs-built_in">require</span>(<span class="hljs-string">'express'</span>);
<span class="hljs-keyword">const</span> router = express.Router();
<span class="hljs-keyword">const</span> authMiddleware = <span class="hljs-built_in">require</span>(<span class="hljs-string">'../middlewares/auth'</span>);
<span class="hljs-keyword">const</span> authController = <span class="hljs-built_in">require</span>(<span class="hljs-string">'../controllers/auth'</span>); <span class="hljs-comment">// Import the controller</span>


router.post(<span class="hljs-string">'/register'</span>, [authMiddleware.validateRegisterRequest], authController.registerUser);


<span class="hljs-built_in">module</span>.exports = router;
</code></pre>
<p>router is an in-built entity of the express framework. It lets us create multiple routes which makes our service/backend very organized.</p>
<p><code>router.post</code> defines that the /register request is a POST endpoint. This function takes 3 parameters.</p>
<ol>
<li><p>Endpoint</p>
</li>
<li><p>List of middleware functions</p>
</li>
<li><p>List of controller functions</p>
</li>
</ol>
<p>As you can see, the first function present in the arguments is the <code>validateRegisterRequest</code> function. That's why it is the first function that gets triggered when the client sends a request to the /register endpoint.</p>
<p>Remember the <code>next()</code> in our validation function. It passes the baton to the next function in the list of arguements which is our <code>registeruser</code> function. Now it all makes sense right?</p>
<h1 id="heading-final-piece-of-puzzle">Final Piece of Puzzle</h1>
<p>Remember our endpoint was `<a target="_blank" href="http://localhost:3000/auth">http://localhost:3000/auth</a>/register`. We have figured out how the <code>/register</code> will work and we also know that our server will run on http://localhost:3000.</p>
<p>Now we will see how we add the /auth in the middle and why do we need it.</p>
<p>Imagine a list of folders like documents, downloads, movies, games etc and all the documents in documents folder and so on.</p>
<p>Similarly auth is like a folder. All the endpoints related to an authentication will lie inside the auth route. In our app.js we will make use of the express framework's inbuilt method called as <code>use()</code></p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> express = <span class="hljs-built_in">require</span>(<span class="hljs-string">'express'</span>);
<span class="hljs-keyword">const</span> authRouter = <span class="hljs-built_in">require</span>(<span class="hljs-string">'./routes/auth'</span>)
<span class="hljs-keyword">const</span> authMiddleware = <span class="hljs-built_in">require</span>(<span class="hljs-string">'./middlewares/auth'</span>)

<span class="hljs-keyword">const</span> app = express()

app.use(express.json());
app.use(express.urlencoded({ <span class="hljs-attr">extended</span>: <span class="hljs-literal">true</span> }));


app.use(<span class="hljs-string">'/auth'</span>,authRouter)


<span class="hljs-built_in">module</span>.exports = app
</code></pre>
<p><code>.use()</code> has multiple use cases. It can be used to add middleware to your service. It can also be used to associate a custom middleware, <code>authRouter</code>, with a specific path, in this case, <code>/auth</code>. This means that any incoming requests starting with <code>/auth</code> will be directed to the routing logic defined within <code>authRouter</code>.</p>
<p>This approach is a fundamental part of route organization in Express, allowing you to apply specific routing logic to a particular path, making your application more modular and maintainable."</p>
<p>Now it all makes sense. We have finally connected our jigsaw and created our first successful API endpoint.</p>
<p>Run the following command. Open Postman add a new post request with some email and password in the body and hit the send button. If everything goes well, you will see that your user is registered successfully and you will get a successful response.</p>
<p>If not, then debug your code fix all the errors and make that API hit a success!</p>
<pre><code class="lang-javascript">npx nodemon server.js
</code></pre>
<h1 id="heading-conclusion">Conclusion</h1>
<p>So this sums up article number two of our authentication service. In the next article, we will see how we can log in as a registered user.</p>
<p>We will learn about JWT tokens, rate-limiting and much more. Happy coding!</p>
]]></content:encoded></item><item><title><![CDATA[Introduction: Building a Secure Authentication Service]]></title><description><![CDATA[Learn to build a robust authentication service from scratch using Node.js, MongoDB, and Twilio. Follow our step-by-step guide for beginners to create…]]></description><link>https://cswithiyush.hashnode.dev/introduction-building-a-secure-authentication-service</link><guid isPermaLink="true">https://cswithiyush.hashnode.dev/introduction-building-a-secure-authentication-service</guid><category><![CDATA[backend]]></category><category><![CDATA[Node.js]]></category><category><![CDATA[System Design]]></category><category><![CDATA[Mobile Development]]></category><category><![CDATA[Beginner Developers]]></category><dc:creator><![CDATA[Ayush Pawar]]></dc:creator><pubDate>Sun, 22 Oct 2023 07:42:05 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1697960458744/9490f822-a199-4525-8ec6-78b30ccb62f4.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h1 id="heading-introduction">Introduction</h1>
<p>This is the beginning of a 5 article series where I will take you through a detailed guide on how to build a beginner-friendly but solid Authentication service.</p>
<p>If you are stuck in tutorial hell or want to build something to test/ improve your backend skills, this might be the perfect series for you. If you are an experienced backend developer this might not be the correct article for you.</p>
<p>So without wasting any time, let's get started.</p>
<h1 id="heading-features">Features</h1>
<p>Our Auth Service will have a lot of features. It will have 6 endpoints</p>
<ol>
<li><p>Register via Email Password</p>
</li>
<li><p>Register via Mobile Number &amp; OTP</p>
</li>
<li><p>Send OTP</p>
</li>
<li><p>Verify OTP</p>
</li>
<li><p>Get Profile</p>
</li>
<li><p>Validate JWT Token</p>
</li>
</ol>
<p>I will do a separate article for all 6 endpoints.</p>
<h1 id="heading-tech-stack">Tech-Stack</h1>
<p>We will be using node js as our framework, MongoDB and Redis for database &amp; caching, and Twilio for OTP sending services.</p>
<p>I have also created a fully functional UI in SwiftUI for the same but that is not our concern for now. That will be a completely different article series.</p>
<h1 id="heading-project-structure">Project Structure</h1>
<p>Aim to be as organized as possible from the start. It will help you in the future when the number of files increases. For our current project, I have created 6 main folders.</p>
<p>1) Models</p>
<p>2) Controllers</p>
<p>3) Routes</p>
<p>4) Helpers</p>
<p>5) Middlewares</p>
<p>6) Constants</p>
<p>Apart from these 6, we have our .env file, app.js and server.js which will be present in the root directory.</p>
<p>For today's article, we will have a look at how to set up the .env, app.js, &amp; server.js files.</p>
<h1 id="heading-setup">Setup</h1>
<p>.env file is used to store all the secret keys and config. We do not push this file to GitHub by keeping it in .gitignore file.</p>
<p>Here is an example of a .env file for our project</p>
<pre><code class="lang-javascript">PORT = <span class="hljs-number">3000</span>
TOKEN_KEY = dummytokenkey
TWILIO_ACCOUNT_SID = dummyaccountkey
TWILIO_AUTH_TOKEN = dummyauthtoken
MONGO_URI = dummymongouri
</code></pre>
<p>Before moving onto app and server.js we will add dependencies to our project. We will need these external packages/libraries as this will make our lives easier. We will use 8 packages namely express, mongoose, Twilio, redis, bcrypt, JSON web token, express-rate-limit, and dotenv.</p>
<p>I will explain the use of all these packages when the time comes. For now, just do</p>
<pre><code class="lang-javascript">yarn add express mongoose twilio redis bcrypt jsonwebtoken express-rate-limit dotenv
</code></pre>
<h1 id="heading-appjs-amp-serverjs">App.JS &amp; Server.JS</h1>
<h2 id="heading-appjs">app.js</h2>
<p>Our app.js file will include details of middleware and other important declarations related to our app.</p>
<p>First of all, we will import express and create an instance of the express class.</p>
<p>Here is a short definition of express: <strong>Express is a node js web application framework that provides broad features for building web and mobile applications. It is used to build a single page, multipage, and hybrid web application. It's a layer built on the top of the Node js that helps manage servers and routes.</strong></p>
<p>After that, we will add two middlewares to our app.</p>
<ol>
<li><p>express.json(): The <strong>express.json()</strong> function is a built-in middleware function in Express. It parses incoming requests with JSON payloads and is based on a <strong>body parser</strong>. </p>
</li>
<li><p><strong>express.urlencoded()</strong> : Just like express.json() converts request body to JSON, it also carries out some other functionalities like converting form-data to JSON etc.</p>
</li>
</ol>
<p>For more detailed info on these 2 middlewares, you can r<a target="_blank" href="https://stackoverflow.com/questions/23259168/what-are-express-json-and-express-urlencoded">ead this stackoverflow post</a></p>
<p>We will then export our app so that other files can use it whenever needed.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> express = <span class="hljs-built_in">require</span>(<span class="hljs-string">'express'</span>);

<span class="hljs-keyword">const</span> app = express()

app.use(express.json());
app.use(express.urlencoded({ <span class="hljs-attr">extended</span>: <span class="hljs-literal">true</span> }));

<span class="hljs-built_in">module</span>.exports = app
</code></pre>
<h2 id="heading-serverjs">server.js</h2>
<p>First of all, we will import all the required files. We will need the app we created just now, we will also need our dbservices and redis service which we have just exported from their respective files.</p>
<p>We will try to connect to our db and then we will try to connect to our Redis server. If both are a success, we will tell our app to listen to a port on our local host.</p>
<p>connectDB() &amp; connectRedis() functions are written by us. We will cover it in future articles. For now, you can just ignore that code and create only server.js and import our app in it.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> app = <span class="hljs-built_in">require</span>(<span class="hljs-string">'./app'</span>)
<span class="hljs-keyword">const</span> dbServices = <span class="hljs-built_in">require</span>(<span class="hljs-string">'./helpers/db'</span>)
<span class="hljs-keyword">const</span> redisService = <span class="hljs-built_in">require</span>(<span class="hljs-string">'./helpers/redis'</span>)

dbServices.connectDB().then(<span class="hljs-function">()=&gt;</span>{
        redisService.connectRedis().then(<span class="hljs-function">()=&gt;</span>{
            app.listen(PORT, <span class="hljs-function">() =&gt;</span> {
                <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`Service running on <span class="hljs-subst">${PORT}</span>`</span>)
            })
        }).catch(<span class="hljs-function">(<span class="hljs-params">e</span>) =&gt;</span> {
            <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Redis error occured "</span>)
        })

}).catch(<span class="hljs-function">(<span class="hljs-params">e</span>)=&gt;</span>{
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Mongoose Error Occured"</span>)
})
</code></pre>
<h1 id="heading-conclusion">Conclusion</h1>
<p>So that's it for today's article. To give a quick recap, here is what we did today</p>
<ol>
<li><p>Learned how to break our project into various folders</p>
</li>
<li><p>Created a .env file to store our secrets in it.</p>
</li>
<li><p>Installed all the required dependencies using yarn</p>
</li>
<li><p>Created an app file, and registered two important middlewares for our service.</p>
</li>
</ol>
<p>In the next article, we will connect our Mongoose and Redis databases, and write our first endpoint.</p>
<p>I hope that you learned something new today. You can appreciate and support my blogs via.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1646372265341/O0KkM6E-0.png?auto=compress,format&amp;format=webp" alt="https://cdn.hashnode.com/res/hashnode/image/upload/v1646372265341/O0KkM6E-0.png" /></p>
<p>Also, let's connect on <a target="_blank" href="https://twitter.com/Iyush004"><strong>Twitter</strong></a>. Follow CSwithIyush for more amazing tutorials, tips/tricks on Flutter &amp; DSA.</p>
]]></content:encoded></item><item><title><![CDATA[Imposter Syndrome in Tech: A Junior Developer's Perspective]]></title><description><![CDATA[Discover strategies to beat Imposter Syndrome as a new tech professional.]]></description><link>https://cswithiyush.hashnode.dev/imposter-syndrome-in-tech-a-junior-developers-perspective</link><guid isPermaLink="true">https://cswithiyush.hashnode.dev/imposter-syndrome-in-tech-a-junior-developers-perspective</guid><category><![CDATA[technology]]></category><category><![CDATA[Beginner Developers]]></category><category><![CDATA[Mobile Development]]></category><category><![CDATA[General Advice]]></category><category><![CDATA[General Programming]]></category><dc:creator><![CDATA[Ayush Pawar]]></dc:creator><pubDate>Sat, 14 Oct 2023 16:55:05 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1697356432753/10ef7776-00fc-463c-b388-ef7b720e5ade.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h1 id="heading-introduction">Introduction</h1>
<p>I am Ayush. A fresh graduate who is ready to rock the world of software development with my leetcode and app development skills. This is what I thought 8 months back when I started my first full-time job as a software developer (SDE). Little did I know that my skills were as good as nothing.</p>
<p>Today, I will discuss how I faced the imposter syndrome in my first job and what things I did to overcome it.</p>
<p><img src="https://media.istockphoto.com/id/1352597036/vector/imposter-syndrome-man-standing-for-her-present-profile-with-fear-shadow-behind-anxiety-and.jpg?s=612x612&amp;w=0&amp;k=20&amp;c=GhRE-MFr36b0qbNtif7ROM5A2FTZo759gYacrycgSRg=" alt="8,600+ Imposter Syndrome Stock Photos, Pictures &amp; Royalty-Free Images -  iStock | Imposter syndrome woman, Imposter syndrome mirror, Imposter  syndrome concept" /></p>
<h1 id="heading-what-is-imposter-syndrome"><strong>What is Imposter Syndrome?</strong></h1>
<p>Imposter Syndrome, often referred to as the Impostor Phenomenon, is a psychological pattern in which individuals doubt their accomplishments and have a persistent fear of being exposed as frauds, despite evidence of their competence and success.</p>
<p>This phenomenon is not limited to the tech industry. It's everywhere out there. A lot of people face it and some people do not.</p>
<h1 id="heading-the-initial-days">The Initial Days</h1>
<p>The initial days were for training. I was learning a new language and building projects in it. I was put on the mobile team. It was fun and challenging. Fun because I was getting paid to learn new things and improve my skills. Challenging because every project was reviewed by the engineering manager and the expectation of the level of code was very high.</p>
<p>It was a really good 30 days. On day 31, I got access to the codebase and reality hit me. I was lost, the codebase was so vast I couldn't imagine. I never worked on a codebase this huge. For your context, there are 4 repositories for a single app. Each repository has hundreds of files. We have 2 apps. The manager gave me 3 days to go through the code and understand all the important things like</p>
<ol>
<li><p>Fetching data via APIs</p>
</li>
<li><p>How navigation worked in the app</p>
</li>
<li><p>State management in the app</p>
</li>
<li><p>Whatever I think that is important which the manager forgot.</p>
</li>
</ol>
<p>Well, 3 days felt like a lot to me because I had experience in mobile as all I did was Flutter during my engineering days. Soon I realized how little I knew about app architecture and the application of OOPS.</p>
<p><img src="https://res.cloudinary.com/practicaldev/image/fetch/s--qnZl50oB--/c_imagga_scale,f_auto,fl_progressive,h_900,q_auto,w_1600/https://dev-to-uploads.s3.amazonaws.com/i/10z2m9xvuegu09fbacbn.jpg" alt="5 Tips On Navigating A New Codebase - DEV Community" /></p>
<p>I was lost. It took me 1.5 days to figure out how data was being fetched from the API or local database (cache) and rendered on the screen. It took me another day to figure out the navigation stack.  </p>
<p>This was enough to lower my confidence. I thought winning 4 hackathons and doing 2 freelancing projects made me a pro developer haha. <strong>The Imposter Syndrome kicked in.</strong></p>
<h1 id="heading-kicking-out-the-imposter-syndrome">Kicking out the Imposter Syndrome</h1>
<p>The initial tasks that I got were very simple like fixing logical bugs or making some UI changes. The challenge for me was not to fix the bug but it was to find the file. It was very frustrating. Things that should have taken 10 minutes were taking 30 minutes because I was not able to figure out where the hell is the code for the text which is being rendered on the screen.</p>
<p>I figured out that if I wanted to boost my confidence and get out of this hole, I must ask questions. Questions like,</p>
<ol>
<li><p>What are the things I should focus on while doing my tasks?</p>
</li>
<li><p>Are there some keywords that we use to find the most used files?</p>
</li>
<li><p>What are the most used component wrappers?</p>
</li>
<li><p>Is there any documentation for specific modules? (Unfortunately there wasn't)</p>
</li>
</ol>
<p>The more questions I asked, the better I got. This is the biggest tip and probably the fastest way to get out of that imposter syndrome hole.</p>
<p>The second thing I did that helped to kick out the imposter syndrome was to study like a student. Whenever I encountered a new concept I quickly used ChatGPT to learn about it.</p>
<p>I was not just copying and pasting views and using already written functions, I tried to understand why the function was written like this, and what are the benefits. In this process, I found some major flaws and fixed them. This improved the performance of the app.</p>
<p>There were two main places where I improved the performance or the user experience</p>
<ol>
<li><p>Some flatlists were not being used to their full potential as there were no props used like initialNumToRender, windowSize, maxRenderPerBatch which could improve performance.</p>
</li>
<li><p>A laggy transition from portrait to landscape during navigation from one screen to another was fixed by moving things from interaction manager to setTimeout.</p>
</li>
</ol>
<p>I made more small changes here and there to improve stuff. I also learned a lot of new concepts along the way which boosted my confidence to another level.</p>
<p>This was all that I needed to climb up and regain my confidence. Soon I was delivering modules and new features on my own under a tight deadline. Now, I am one of the core developers who are working on migrating our existing app to Swift.</p>
<p><img src="https://img.huffingtonpost.com/asset/5d01b3cb250000ae13e0dd33.jpeg?ops=scalefit_720_noupscale" alt="A Wellbeing Psychologist Reveals The Secrets To A Happy Baby | HuffPost UK  Parents" /></p>
<h1 id="heading-key-takeaways-andamp-conclusion">Key Takeaways &amp; Conclusion</h1>
<p>To summarise, there were two things that I did</p>
<ol>
<li><p>Ask relevant questions to seniors</p>
</li>
<li><p>Study the code like there is no tomorrow.</p>
</li>
</ol>
<p>The codebase might seem small to you because you might be working at a much bigger organization but my point is that every new company you join, you will have that nerves in the initial few days. The above 2 stratergies will help you quickly adapt to that system and thrive there.</p>
<p>What do you think about the imposter syndrome ? How did you tackle it? I would love to read your comments about the same.</p>
]]></content:encoded></item><item><title><![CDATA[Expert Insights into Database Sharding: An In-Depth Overview]]></title><description><![CDATA[In today's world, data is king, and managing large amounts of data can be a challenge for businesses. Database sharding is a popular solution to this...]]></description><link>https://cswithiyush.hashnode.dev/expert-insights-into-database-sharding-an-in-depth-overview</link><guid isPermaLink="true">https://cswithiyush.hashnode.dev/expert-insights-into-database-sharding-an-in-depth-overview</guid><category><![CDATA[software development]]></category><category><![CDATA[System Architecture]]></category><category><![CDATA[System Design]]></category><category><![CDATA[education]]></category><category><![CDATA[Tutorial]]></category><dc:creator><![CDATA[Ayush Pawar]]></dc:creator><pubDate>Mon, 27 Mar 2023 16:07:05 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1679933146800/58aac2f8-8fc0-4917-bf3b-813d5d67649c.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h1 id="heading-introduction">Introduction</h1>
<p>In today's world, data is king, and managing large amounts of data can be a challenge for businesses. Database sharding is a popular solution to this problem. Sharding is the process of horizontally partitioning a database to optimize its performance. In this blog post, we will discuss what database sharding is, its advantages and disadvantages, and real-life examples of sharding.</p>
<h1 id="heading-what-is-database-sharding">What is Database Sharding?</h1>
<p>Database sharding is a concept where a database is partitioned horizontally to make queries faster and optimize performance. This process involves breaking down the database into smaller pieces called shards. Each shard contains a subset of the data, and this partitioning helps distribute the load across multiple servers. Sharding is used to make queries faster and improve performance.</p>
<h1 id="heading-real-life-example-of-sharding">Real-Life Example of Sharding</h1>
<p>Suppose you are running a shoe store, and you receive a lot of requests for different shoe sizes. Even after indexing, your database queries are taking time, so you decide to shard your database based on shoe size. You can partition your database into nine pieces/shards for sizes 4-13, and each shard will contain information about shoes of a particular size only. This results in faster queries because now you just have to read a single shard and not do any conditional checks in the database.</p>
<h1 id="heading-advantages-of-database-sharding">Advantages of Database Sharding</h1>
<p>One major advantage of sharding is that it improves query performance. With a properly sharded database, queries become faster and more efficient. Another advantage is that sharding provides scalability. By breaking the database into smaller pieces, you can add more shards as needed to accommodate additional data. This makes sharding an ideal solution for businesses that expect rapid data growth.</p>
<h1 id="heading-disadvantages-of-database-sharding">Disadvantages of Database Sharding</h1>
<p>One disadvantage of sharding is that the number of shards is not dynamic. This means that it can be difficult to add or remove shards as needed. However, this problem can be addressed by creating more dynamic shards in a single shard.</p>
<p>Another disadvantage is that sharding can be complex to set up and manage. Additionally, sharding can result in increased complexity and cost when it comes to backups and disaster recovery.</p>
<h1 id="heading-conclusion">Conclusion</h1>
<p>Database sharding is a powerful technique that can improve the performance and scalability of databases. However, it comes with its own set of challenges, such as increased complexity and cost. Sharding should be used as a last resort after considering other options like indexing and using NoSQL. In conclusion, sharding is an excellent solution for businesses with rapidly growing data and complex queries, but it should be approached with caution and careful consideration.</p>
]]></content:encoded></item><item><title><![CDATA[Stay Informed with DevBytes: The Top News App for Professionals]]></title><description><![CDATA[In this article, I will discuss an innovative app that I have been using for the past few weeks and found to be incredibly useful. Although this discussion]]></description><link>https://cswithiyush.hashnode.dev/stay-informed-with-devbytes-the-top-news-app-for-professionals</link><guid isPermaLink="true">https://cswithiyush.hashnode.dev/stay-informed-with-devbytes-the-top-news-app-for-professionals</guid><category><![CDATA[news]]></category><category><![CDATA[General Programming]]></category><category><![CDATA[Blogging]]></category><category><![CDATA[General Advice]]></category><dc:creator><![CDATA[Ayush Pawar]]></dc:creator><pubDate>Wed, 22 Mar 2023 05:14:10 GMT</pubDate><content:encoded><![CDATA[<h2 id="heading-introduction">Introduction</h2>
<p>In this article, I will discuss an innovative app that I have been using for the past few weeks and found to be incredibly useful. Although this discussion is not related to Flutter, it is pertinent to the tech industry. The app, DevBytes, is designed for busy developers, product managers, and engineering managers who want to keep themselves updated on the latest technological developments but cannot devote much time to reading lengthy articles.</p>
<p>DevBytes provides a concise and comprehensive format for all the coding news you require without any fluff or filler, keeping you informed and ahead of the game. The app is frequently updated with the latest news, ensuring that you never fall behind.</p>
<p><img src="https://lh6.googleusercontent.com/BKv4Z2nPPSuH9L48fmVAYijUumGckJZEsRUUaH6j4jttGfpxGNAHFmR7pJFSQcpUmWos77KSTjct_iDBOuYfoe3A_uUFZovDQm3MIDe1vOghXnaO98FiTKFvi9i_J1_tIR-6Hg59DGKfsSV2V6vhVYQ" alt /></p>
<h2 id="heading-ia"> </h2>
<p>Overview</p>
<p>Once you download the DevBytes app, you will be asked to fill in your preferences and interests. You will then be asked to sign in via Google or Twitter. That's all it takes to onboard the app. Your home screen will display news articles promptly, one after the other, like a carousel. If you wish to read more about a news item, you can tap on the article and the app will redirect you to the source of the article.</p>
<p>DevBytes has two sections: "All News" and "My Feed." All News contains top and trending news items, while My Feed contains news customized to your preferences based on the role and interests you provided at the start.</p>
<p><img src="https://lh5.googleusercontent.com/qcOqAmyhFaWIorIBaZigmuu74taqmmLCKualbKElnXQY_s5XL0QAmnUhV_xIbhUF312s2NJg-dNYdpGfKuoHVkFVisNcMOsvAFM6xJrOd53xwsu_HTNior6ggMbV43uuci7Kn3MA4z8jGJ0RNNz8MoY" alt /></p>
<h2 id="heading-there-is-more">There is more!</h2>
<p>In addition to short and crisp tech news, DevBytes has a section called "CryptoWatch," which serves as a crypto index watcher, displaying the current prices of all major cryptocurrencies. There is also a "Deals" section where you can access great deals on specific brands by completing particular tasks.</p>
<h2 id="heading-ia-1"> </h2>
<p>Key Features</p>
<p>While Google, Twitter, and LinkedIn also offer news items, DevBytes has a unique advantage. On platforms like LinkedIn and Twitter, news items can be quickly overshadowed by memes and other distractions, leading to a lack of consistency. DevBytes, on the other hand, is dedicated solely to news, providing you with the most relevant and up-to-date information.</p>
<p><img src="https://lh3.googleusercontent.com/L1hkSVspDneQJs_N1i7JUNsZHrxQzWu9UFmNka9IT3gUmlv1pLcOFJ3j2AYnQpKRul9PdPWMuDKnzR7S2XPRvSqWswEwBodw_De327aFvsa_MQ3LUOixUFKsYD3aTX6Q9Sc-49sg0_PZ8knJqIyeFk0" alt /></p>
<p>DevBytes also has a fantastic feature that allows you to schedule notifications for news articles at regular intervals, ensuring that you are always up-to-date on the latest happenings. I use DevBytes personally to stay informed about current events, and I find the following features particularly useful</p>
<p>I utilize DevBytes to remain up-to-date with the latest developments in the tech industry due to its exceptional features. DevBytes is characterized by:</p>
<p>Expediency: As indicated earlier, the application presents coding news succinctly and concisely, enabling one to stay abreast of current events without investing significant time in reading lengthy articles.</p>
<p>Relevance: DevBytes is specifically crafted for developers, product managers, and engineering managers, providing news and information that is highly pertinent to one's profession.</p>
<p>Efficiency: By furnishing only the most vital and applicable news, DevBytes assists you in optimizing your time and facilitating your professional growth.</p>
<h2 id="heading-conclusion">Conclusion</h2>
<p>In conclusion, given the fast-paced nature of the technology industry, it is essential to keep oneself abreast of the latest developments. DevBytes provides the necessary information to stay ahead of the curve. Therefore, do not hesitate to download the application and remain at the forefront of the technology world.</p>
<p>You can download the DevBytes Android app from the following link: <a target="_blank" href="https://bit.ly/3IsN0Qh">https://bit.ly/3IsN0Qh</a>.</p>
]]></content:encoded></item><item><title><![CDATA["Breaking Down the Pros and Cons of Microservices vs Monoliths"]]></title><description><![CDATA[In software development, a monolith is a type of application architecture where all the different components and features of the application are tightly]]></description><link>https://cswithiyush.hashnode.dev/breaking-down-the-pros-and-cons-of-microservices-vs-monoliths</link><guid isPermaLink="true">https://cswithiyush.hashnode.dev/breaking-down-the-pros-and-cons-of-microservices-vs-monoliths</guid><category><![CDATA[System Design]]></category><category><![CDATA[System Architecture]]></category><category><![CDATA[education]]></category><category><![CDATA[Tutorial]]></category><category><![CDATA[General Programming]]></category><dc:creator><![CDATA[Ayush Pawar]]></dc:creator><pubDate>Sat, 18 Mar 2023 12:34:45 GMT</pubDate><content:encoded><![CDATA[<h1 id="heading-introduction">Introduction</h1>
<p>In today's blog, we will dive deep into what are microservices and monoliths. The pros and cons of both and when to use what. In the last article, we studied Message Queues. So let's get started.</p>
<h1 id="heading-what-is-a-monolith">What is a Monolith?</h1>
<p>In software development, a monolith is a type of application architecture where all the different components and features of the application are tightly coupled together into a single, large codebase.</p>
<p>Imagine a building made up of one solid piece of stone. A monolithic application is similar in that all the code that makes up the application is tightly integrated and interconnected, rather than being split up into smaller, more modular pieces.</p>
<p><img src="https://miro.medium.com/v2/resize:fit:714/1*F6y9GeBZwaOzNYnToahfQw.png" alt="Monolithic &amp; Microservices Architecture | by Henrique Siebert Domareski |  Medium" /></p>
<h1 id="heading-what-is-a-microservice">What is a Microservice?</h1>
<p>In software development, a microservice is a type of application architecture where an application is built as a collection of small, independent services that can run their processes and communicate with each other via APIs.</p>
<p>Imagine a city where each neighbourhood has its services like schools, hospitals, and stores. Microservice architecture is similar in that each service can operate independently and has its specific purpose, but they all work together to form a larger, cohesive application.</p>
<p><img src="https://images.contentstack.io/v3/assets/blt189c1df68c6b48d7/blt900fee914052507b/62a5f052e75cbf5ab676839d/abc_Microservices-2.png" alt="Microservices in eCommerce Explained | Vue Storefront" /></p>
<h1 id="heading-microservice-inside-a-monolith">Microservice inside a Monolith</h1>
<p>The core definition of microservice is that the services need to be physically separated.</p>
<p>Example: A backend application for e-commerce where the payment service and inventory service are written on the same server but in different classes isn't a microservice. It is a kind of microservice as we are separating the business logic in the code but overall it is still a monolith.</p>
<p>In a true microservice architecture, each service would be running in its process or container, communicating with each other through APIs. This allows for more flexibility and scalability, as each service can be developed, deployed, and scaled independently.</p>
<p>So while the separation of classes is a step in the right direction towards a microservice architecture, it is still not a fully decoupled, independent system.</p>
<h1 id="heading-advantages-amp-disadvantages-of-a-monolith">Advantages &amp; Disadvantages of a Monolith.</h1>
<h3 id="heading-advantages">Advantages</h3>
<ol>
<li><p>It is faster than Microservices because services interact with each other via function calls and inter-process communication.</p>
</li>
<li><p>When a new developer joins the team, it is easy to onboard as everything is present in a single place.</p>
</li>
<li><p>Developing a monolithic architecture is typically less expensive than building a distributed system as it requires fewer resources to develop and maintain.</p>
</li>
</ol>
<h3 id="heading-disadvantages">Disadvantages</h3>
<ol>
<li><p>In a monolithic architecture, all the components of the application are tightly coupled together. This can make it difficult to add new features or make changes to existing ones without affecting the entire application.</p>
</li>
<li><p>While it can be easier to scale a monolithic application on a single server, it can become more difficult and costly to scale it horizontally across multiple servers or clusters.</p>
</li>
<li><p>Monolithic applications are often built using a single technology stack, which can limit the ability to incorporate newer technologies and tools.</p>
</li>
</ol>
<h1 id="heading-advantages-amp-disadvantages-of-a-microservice">Advantages &amp; Disadvantages of a Microservice.</h1>
<h3 id="heading-advantages-1">Advantages</h3>
<ol>
<li><p>We can use different tech-stack for different services making it much more flexible.</p>
</li>
<li><p>Deployments are faster because testing/deployment needs to be done only on the services changed. The system is loosely coupled and change in one system doesn't affect another.</p>
</li>
<li><p>Even if a single service fails, the system won't fail as a whole. No single point of failure.</p>
</li>
</ol>
<h3 id="heading-disadvantages-1">Disadvantages</h3>
<ol>
<li><p>Microservices can be more complex to develop, deploy, test, and manage due to their distributed nature, which can require additional infrastructure, tools, and expertise.</p>
</li>
<li><p>With microservices, managing data consistency across multiple services can be challenging, especially when dealing with transactions that span multiple services.</p>
</li>
<li><p>Microservices can be more expensive to develop and maintain than monolithic applications due to the additional infrastructure and development costs.</p>
</li>
</ol>
<p><img src="https://www.openlegacy.com/hubfs/Picture1.webp" alt="The Pros and Cons of a Monolithic Application Vs. Microservices" /></p>
<h1 id="heading-conclusion">Conclusion</h1>
<p>In conclusion, both monolithic and microservices architectures have their advantages and disadvantages, and the choice between them depends on the specific needs of the application. Monolithic architecture can offer simplicity, performance, easier debugging, lower development cost, and easier scaling, making it a good choice for small to medium-sized applications with simpler requirements.</p>
<p>On the other hand, microservices architecture offers scalability, flexibility, fault tolerance, and better technology choices, making it a good choice for larger and more complex applications that require high scalability and flexibility. However, microservices can also come with increased complexity, overhead, and cost, which should be carefully considered when deciding on an architecture for a given application.</p>
<p>Ultimately, the choice between these architectures should be made based on the specific requirements of the application, the expertise of the development team, and the available resources.</p>
]]></content:encoded></item><item><title><![CDATA[Message Queues Made Easy: A Beginner's Guide to Application Communication]]></title><description><![CDATA[Today in the system design series, we will learn about message queues. Message queues are one of the most important parts of a highly scaled-and]]></description><link>https://cswithiyush.hashnode.dev/message-queues-made-easy-a-beginners-guide-to-application-communication</link><guid isPermaLink="true">https://cswithiyush.hashnode.dev/message-queues-made-easy-a-beginners-guide-to-application-communication</guid><category><![CDATA[System Architecture]]></category><category><![CDATA[System Design]]></category><category><![CDATA[Beginner Developers]]></category><category><![CDATA[General Programming]]></category><category><![CDATA[Tutorial]]></category><dc:creator><![CDATA[Ayush Pawar]]></dc:creator><pubDate>Sat, 11 Mar 2023 05:09:08 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1678511277719/f839ba23-d00f-4261-b1f8-c427264bcd54.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h1 id="heading-introduction">Introduction</h1>
<p>Welcome back! Today in the system design series, we will learn about message queues. Message queues are one of the most important parts of a highly scaled-and successful system. So let's explore what is a message queue, how is it implemented, where is it implemented, and one real-life example of the same.</p>
<h1 id="heading-what-is-a-message-queue">What is a message queue?</h1>
<p>In simple terms, a message queue is used to achieve asynchronous communication between multiple systems or different instances of a single system.</p>
<p>For example, if machine A needs to send a request to machine B, the request will first land on the message queue and sit on it. Machine B must retrieve this request from the message queue, execute the request and then send back the response to machine A. Once this is done, the request is then popped from the message queue.</p>
<p>Apache Kafka, Rabbit MQ, and Amazon Simple Queue service are some of the major message queue services.</p>
<p><img src="https://better.engineering/static/2772f41f7aaff4e240def8ce7ed29f44/31493/message_queue.png" alt="A comparison of popular message queues | Better Engineering Blog" /></p>
<h1 id="heading-in-memory-or-databases">In-memory or databases?</h1>
<p>A message queue can be implemented in memory or databases as well. There are pros and cons to both and it depends on the use case.</p>
<p>In-memory message queues are typically faster than database-backed message queues because they don't require disk I/O operations. This can make them a good choice for applications that need to process messages very quickly or handle high message volumes.</p>
<p>In-memory message queues are also often simpler to set up and manage, as they don't require an external data store. However, they are less durable, as messages are not in a persistent space. If the server crashes, then everything in the message queue is gone.</p>
<p>On the other hand, database-backed message queues are typically slower than in-memory message queues due to disk I/O operations. However, they are more durable, as messages are stored in a persistent data store and can be retrieved even if the application or server crashes. This makes them a good choice for applications that require high message durability, or that handle sensitive data.</p>
<p>Which one is more scalable? The database one. Why? THINK.</p>
<h1 id="heading-real-life-example">Real-Life Example</h1>
<p>Let's say you have an e-commerce website that sells products to customers. When a customer makes a purchase, you need to process their order and update your inventory system to reflect the fact that you've sold one of your products.</p>
<p>To handle this scenario, you might use message queues in the following way:</p>
<ol>
<li><p>When a customer makes a purchase, your website's order processing application sends a message to a message queue that contains the order details.</p>
</li>
<li><p>The message queue then stores the order message until it can be processed.</p>
</li>
<li><p>Your inventory management application pulls messages from the message queue one at a time and updates your inventory system to reflect the fact that a product has been sold.</p>
</li>
<li><p>Once the message has been processed, it's removed from the message queue.</p>
</li>
</ol>
<p>By using a message queue in this scenario, you're decoupling the order processing and inventory management systems, which makes them more scalable and reliable. If one of the systems fails, the messages will still be stored in the message queue until the system is back up and running, ensuring that no orders or inventory updates are lost.</p>
<p><img src="https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcSedwTnEPM_P3aS6ClTExnTI2w23UoI2TNlpg&amp;usqp=CAU" alt="Microservice Architecture Best Practices: Messaging Queues - DZone" /></p>
<h1 id="heading-pros-amp-cons-of-a-message-queue">Pros &amp; Cons of a Message Queue</h1>
<h3 id="heading-pros">Pros</h3>
<ol>
<li><p>Scalability: Message queues allow you to build scalable applications by decoupling the components of your application. This means you can add more consumers to process messages as your application grows.</p>
</li>
<li><p>Reliability: Message queues provide a reliable way to communicate between components of your application. Messages are stored in the queue until they can be processed, which means they won't be lost if a component of your application fails.</p>
</li>
<li><p>Asynchrony: Message queues enable asynchronous communication between components of your application. This means that components can communicate with each other without having to wait for a response, which can improve the overall performance of your application.</p>
</li>
</ol>
<p>Cons</p>
<ol>
<li><p>Increased complexity: Using a message queue can add complexity to your application, as it introduces an additional layer of abstraction that must be managed and monitored.</p>
</li>
<li><p>Higher latency: While message queues can improve system scalability and reliability, they can also introduce additional latency to message processing. This is because messages must be written to the queue and then read and processed by a consumer, which can take time.</p>
</li>
</ol>
<h1 id="heading-conclusion">Conclusion</h1>
<p>So that was it. A message queue is a great tool that can be added to your system which will help you in scaling your system and handling a lot of asynchronous tasks efficiently. By using best practices and carefully considering the pros and cons of message queues, you can build a robust and reliable messaging architecture for your distributed application.</p>
<p>I hope you learned something new today! Follow CSWithIyush for more such articles on various topics that I keep on learning.</p>
]]></content:encoded></item></channel></rss>