<?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[AI & System Design]]></title><description><![CDATA[Exploring AI, scalable systems, and modern engineering design.
Insights on building intelligent and scalable systems.
Deep dives into AI and system architecture]]></description><link>https://blog.ratishfolio.com</link><image><url>https://cdn.hashnode.com/uploads/logos/639ca8d6052fc36d4a8f42ec/9b025d45-4b52-4c90-bd45-a613aabde1fe.png</url><title>AI &amp; System Design</title><link>https://blog.ratishfolio.com</link></image><generator>RSS for Node</generator><lastBuildDate>Thu, 30 Apr 2026 14:09:03 GMT</lastBuildDate><atom:link href="https://blog.ratishfolio.com/rss.xml" rel="self" type="application/rss+xml"/><language><![CDATA[en]]></language><ttl>60</ttl><item><title><![CDATA[Implement Api Rate Limiting with Upstash Redis in your Next.js project]]></title><description><![CDATA[What is Rate Limiting?
Suppose you have a application where a user can post his picture, for this action you are calling an api endpoint running on a server and the endpoint stores the post in the database.
Now lets say the user posting the picture s...]]></description><link>https://blog.ratishfolio.com/implement-api-rate-limiting-with-upstash-redis-in-your-nextjs-project</link><guid isPermaLink="true">https://blog.ratishfolio.com/implement-api-rate-limiting-with-upstash-redis-in-your-nextjs-project</guid><category><![CDATA[ratelimit]]></category><category><![CDATA[Redis]]></category><category><![CDATA[Upstash]]></category><category><![CDATA[Next.js]]></category><category><![CDATA[Server side rendering]]></category><category><![CDATA[server]]></category><category><![CDATA[coding]]></category><category><![CDATA[development]]></category><dc:creator><![CDATA[Ratish Jain]]></dc:creator><pubDate>Sun, 28 Jul 2024 03:30:47 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1722108427757/5867839e-20ce-4cf8-a3aa-6e1528c30761.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1722103968241/f8424f71-ed55-4a2e-8574-96784015727f.jpeg" alt class="image--center mx-auto" /></p>
<h2 id="heading-what-is-rate-limiting">What is Rate Limiting?</h2>
<p>Suppose you have a application where a user can post his picture, for this action you are calling an api endpoint running on a server and the endpoint stores the post in the database.</p>
<p>Now lets say the user posting the picture spams the post button and the server recieves thousands of requests per second, potentially overwhelming the server and causing it to crash or become unresponsive for other users.</p>
<p>To avoid the above scenario Rate Limiting is used!!</p>
<h2 id="heading-setup">Setup</h2>
<p>Create a boilerplate Next.js project using:</p>
<pre><code class="lang-bash">npx create-next-app@latest
</code></pre>
<p>Install @<strong>upstash/redis</strong> and @<strong>upstash/ratelimit</strong> using:</p>
<pre><code class="lang-bash">npm i @upstash/redis @upstash/ratelimit
</code></pre>
<p>docs - <a target="_blank" href="https://upstash.com/blog/upstash-ratelimit">https://upstash.com/blog/upstash-ratelimit</a></p>
<h2 id="heading-implementation-of-rate-limiting">Implementation of rate limiting</h2>
<p>Since we are using nextjs the demonstration of implementation will be using server actions.</p>
<p>so, go ahead create a folder of actions and creates a server action which posts a picture or content to the database(Highly suggest prisma or drizzle for this).</p>
<p>After creating the server action follow the following steps:</p>
<ul>
<li><p>create a config folder and inside it create upstash.ts file with the following code</p>
<pre><code class="lang-typescript">  <span class="hljs-keyword">import</span> { Redis } <span class="hljs-keyword">from</span> <span class="hljs-string">"@upstash/redis"</span>

  <span class="hljs-keyword">export</span> <span class="hljs-keyword">const</span> redis = <span class="hljs-keyword">new</span> Redis({
      <span class="hljs-comment">// get these credentials by creating account on upstash</span>
      url: <span class="hljs-string">`enter your upstash db url here`</span> 
      token: <span class="hljs-string">`enter you db token here`</span>
  });
</code></pre>
</li>
<li><p>Now inside your server actions file, where the action for posting is created we'll use upstash/ratelimit by doing the following:</p>
<pre><code class="lang-typescript">  <span class="hljs-string">"use server"</span>;
  <span class="hljs-keyword">import</span> { Ratelimit } <span class="hljs-keyword">from</span> <span class="hljs-string">'@upstash/ratelimit'</span>;
  <span class="hljs-keyword">import</span> { redis } <span class="hljs-keyword">from</span> <span class="hljs-string">'./upstash'</span>; <span class="hljs-comment">// the file that you created above</span>
  <span class="hljs-keyword">import</span> { headers } <span class="hljs-keyword">from</span> <span class="hljs-string">'next/headers'</span>;

  <span class="hljs-keyword">const</span> ratelimit = <span class="hljs-keyword">new</span> Ratelimit({
      redis,
      limiter: Ratelimit.slidingWindow(<span class="hljs-number">5</span>,<span class="hljs-string">"120s"</span>); 
      <span class="hljs-comment">//this means 5 requests is allowed per 120 seconds</span>
  });

  <span class="hljs-keyword">export</span> <span class="hljs-keyword">const</span> addPost = <span class="hljs-keyword">async</span> () =&gt; { <span class="hljs-comment">// your server action</span>
      <span class="hljs-keyword">const</span> ip = headers().get(<span class="hljs-string">'x-forwarded-for'</span>); <span class="hljs-comment">//getting user's ip </span>
      <span class="hljs-keyword">const</span> {remaining, limit, success} = <span class="hljs-keyword">await</span> ratelimit.limit(ip!);
      <span class="hljs-built_in">console</span>.log(limit) <span class="hljs-comment">// shows max limit</span>
      <span class="hljs-built_in">console</span>.log(remaining) <span class="hljs-comment">// shows remaining requests in the window</span>
      <span class="hljs-built_in">console</span>.log(success) <span class="hljs-comment">// returns if able to process the request</span>

      <span class="hljs-comment">// so to implement rate limit we need to use simple if condition</span>
      <span class="hljs-keyword">if</span>(!success){
          <span class="hljs-keyword">return</span> <span class="hljs-string">"unable to process the request, limit reached wait for 2 minutes"</span>;
      }

      <span class="hljs-comment">//rest of the addPost logic should be here dealing with the database</span>
  }
</code></pre>
</li>
</ul>
<p>Note: Here we are using rate limiting which uses sliding window technique and there are many more types of rate limiting to know about them check out the following link:</p>
<p>types of rate limiting: <a target="_blank" href="https://www.imperva.com/learn/application-security/rate-limiting/">https://www.imperva.com/learn/application-security/rate-limiting/</a></p>
<p>There you go!! now you know how to implement rate limiting in your large scale projects very easily without any headache.</p>
]]></content:encoded></item><item><title><![CDATA[Mastering API Development with the FastAPI Framework]]></title><description><![CDATA[Let's Lean How to setup FastAPI

Install Python: If you don't have Python installed on your system, you can download it from the official Python website (https://www.python.org/downloads/).

Create a Virtual Environment: It's recommended to create a ...]]></description><link>https://blog.ratishfolio.com/mastering-api-development-with-the-fastapi-framework</link><guid isPermaLink="true">https://blog.ratishfolio.com/mastering-api-development-with-the-fastapi-framework</guid><category><![CDATA[APIs]]></category><category><![CDATA[FastAPI]]></category><category><![CDATA[Beginner Developers]]></category><category><![CDATA[server]]></category><category><![CDATA[client]]></category><dc:creator><![CDATA[Ratish Jain]]></dc:creator><pubDate>Sun, 07 Apr 2024 09:41:35 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1712482713948/6001d710-bd16-428d-a0ee-43ff41b8a475.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h3 id="heading-lets-lean-how-to-setup-fastapi">Let's Lean How to setup FastAPI</h3>
<ul>
<li><p><strong>Install Python</strong>: If you don't have Python installed on your system, you can download it from the official Python website (<a target="_blank" href="https://www.python.org/downloads/">https://www.python.org/downloads/</a>).</p>
</li>
<li><p><strong>Create a Virtual Environment</strong>: It's recommended to create a virtual environment for your FastAPI project to keep your dependencies isolated. You can use the built-in <code>venv</code> module in Python to create a virtual environment</p>
<pre><code class="lang-bash">  python -m venv myenv
</code></pre>
</li>
<li><p><strong>Install FastAPI</strong>: With the virtual environment activated, install FastAPI and its dependencies using pip:</p>
<pre><code class="lang-bash">  pip install fastapi uvicorn
</code></pre>
</li>
<li><p><strong>Create a FastAPI Application</strong>: Create a new Python file (e.g., <a target="_blank" href="http://main.py"><code>main.py</code></a>) and add the following code:</p>
<pre><code class="lang-python">  <span class="hljs-keyword">from</span> fastapi <span class="hljs-keyword">import</span> FastAPI
  <span class="hljs-keyword">import</span> uvicorn
  app = FastAPI()

<span class="hljs-meta">  @app.get("/")</span>
  <span class="hljs-keyword">async</span> <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">root</span>():</span>
      <span class="hljs-keyword">return</span> {<span class="hljs-string">"message"</span>: <span class="hljs-string">"Hello World"</span>}

  <span class="hljs-keyword">if</span> __name__ == <span class="hljs-string">"__main__"</span>:
      uvicorn.run(app, host=<span class="hljs-string">"0.0.0.0"</span>, port=<span class="hljs-number">8000</span>
</code></pre>
</li>
<li><p>Uvicorn is an ASGI web server implementation for Python to run FastApi app on local host</p>
</li>
</ul>
<h3 id="heading-lets-create-an-api-endpoint-using-fastapi">Let's create an api endpoint using FastApi</h3>
<pre><code class="lang-python"><span class="hljs-keyword">from</span> fastapi <span class="hljs-keyword">import</span> FastAPI
<span class="hljs-keyword">from</span> pydantic <span class="hljs-keyword">import</span> BaseModel

app = FastAPI()

<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Product</span>(<span class="hljs-params">BaseModel</span>):</span>
    id: int
    name: str
    description: str
    price: float

<span class="hljs-meta">@app.get("/") #endpoint</span>
<span class="hljs-keyword">async</span> <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">root</span>():</span>
    <span class="hljs-keyword">return</span> {<span class="hljs-string">"message"</span>: <span class="hljs-string">"Welcome to the E-commerce API!"</span>}


<span class="hljs-comment"># example of dynamic url</span>
<span class="hljs-meta">@app.get("/products/{product_id}", response_model=Product) </span>
<span class="hljs-keyword">async</span> <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">get_product</span>(<span class="hljs-params">product_id: int</span>):</span>
    <span class="hljs-comment"># Fetch the product data from a database or external service</span>
    product = {
        <span class="hljs-string">"id"</span>: product_id,
        <span class="hljs-string">"name"</span>: <span class="hljs-string">"Product Name"</span>,
        <span class="hljs-string">"description"</span>: <span class="hljs-string">"Product Description"</span>,
        <span class="hljs-string">"price"</span>: <span class="hljs-number">19.99</span>
    }
    <span class="hljs-keyword">return</span> product
</code></pre>
<ul>
<li><p>To run the FastApi app use <strong>uvicorn main:app --reload</strong> command</p>
<pre><code class="lang-bash">  uvicorn main:app --reload
</code></pre>
</li>
</ul>
<p>The api endpoint <strong>/product/{product_id}</strong> will return product based on the product_id provided in the params making it a dynamic url</p>
<p>Pydantic is data validation and parsing library generally used for data modelling of data that the user passes while hitting the api endpoint or when the user recieves the data when hitting the api endpoint.</p>
<p><strong>HTTP</strong> methods used to create endpoints are <strong>GET,POST,PUT,DELETE</strong></p>
<p>In the above example we have created get request api.</p>
<p>This way you can created api <strong>endpoints</strong> quickly and easily with the help of FastAPI</p>
<p>FastAPI also helps to document your api and you can access this docs using <strong>/docs</strong> endpoint of the FastAPI app.</p>
]]></content:encoded></item><item><title><![CDATA[Mastering React Testing Library and Jest: A Comprehensive Guide]]></title><description><![CDATA[Definitions
Testing
Testing is the process of evaluating a software application or system to identify defects, ensure its functionality meets the desired requirements, and verify that it performs as intended. It helps in maintaining software reliabil...]]></description><link>https://blog.ratishfolio.com/mastering-react-testing-library-and-jest-a-comprehensive-guide</link><guid isPermaLink="true">https://blog.ratishfolio.com/mastering-react-testing-library-and-jest-a-comprehensive-guide</guid><category><![CDATA[Testing]]></category><category><![CDATA[react testing library]]></category><category><![CDATA[JavaScript]]></category><category><![CDATA[Jest]]></category><category><![CDATA[development]]></category><dc:creator><![CDATA[Ratish Jain]]></dc:creator><pubDate>Fri, 27 Oct 2023 15:00:47 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1698418685688/56cd7bcb-e542-4950-9cfe-2b7eb4c8da56.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h2 id="heading-definitions">Definitions</h2>
<p><strong>Testing</strong></p>
<p>Testing is the process of evaluating a software application or system to identify defects, ensure its functionality meets the desired requirements, and verify that it performs as intended. It helps in maintaining software reliability and usability.</p>
<p>There are two types of testing in general</p>
<ul>
<li><p><strong>Unit Testing</strong></p>
</li>
<li><p><strong>Integration Testing</strong></p>
</li>
</ul>
<p><strong>Unit Testing</strong></p>
<p>Unit testing is a level of software testing where individual components or units of a software application are tested in isolation. A "unit" typically refers to the smallest testable part of a program, such as a function, method, or class.</p>
<p><strong>Integration Testing</strong></p>
<p>Integration testing is a level of software testing that focuses on the interactions and interfaces between various units or components of a software system. The primary goal of integration testing is to ensure that these individual units when combined, work together as intended and that the interactions between them do not lead to defects or unexpected behavior.</p>
<h2 id="heading-react-testing-library-amp-jest">React Testing Library &amp; Jest</h2>
<p><strong>React Testing Library</strong> and <strong>Jest</strong> are two of the most popular tools used for testing React applications.</p>
<p><strong>Setup</strong></p>
<p>Firstly Install the react testing library package in your project using the following command</p>
<pre><code class="lang-bash">npm install --save-dev @testing-library/react
</code></pre>
<ul>
<li><p>You might also need to set up a configuration file for Jest, such as <code>jest.config.js</code> or <code>package.json</code> settings.</p>
</li>
<li><p>Create the react components that you want to test.</p>
</li>
</ul>
<p>In this blog, we are gonna see how to write a simple test for a component and run the tests.</p>
<p>Firstly, create a test file for your component the naming convention generally followed is <strong>ComponentName.test.js</strong></p>
<p>Now, inside your test file import the required functions such as <code>render</code> and <code>screen</code> from the react testing library as well as the component that you want to test.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">import</span> React <span class="hljs-keyword">from</span> <span class="hljs-string">'react'</span>;
<span class="hljs-keyword">import</span> { render, screen } <span class="hljs-keyword">from</span> <span class="hljs-string">'@testing-library/react'</span>;
<span class="hljs-keyword">import</span> MyComponent <span class="hljs-keyword">from</span> <span class="hljs-string">'./MyComponent'</span>;
</code></pre>
<p>Now let's understand how the <code>react testing library</code> and <code>jest</code> work!!</p>
<p><strong>Structure of a test block</strong></p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1698417376854/9fa2191b-1060-4796-ae1c-71a81483d22e.png" alt class="image--center mx-auto" /></p>
<ul>
<li><p>Render a component you want to test</p>
</li>
<li><p>Search for the element you want to interact with</p>
</li>
<li><p>After that assert/check the results to see whether they are working as desired</p>
</li>
</ul>
<p>The code below shows how a test block is written</p>
<pre><code class="lang-javascript">test(<span class="hljs-string">'MyComponent renders correctly'</span>, <span class="hljs-function">() =&gt;</span> { <span class="hljs-comment">// test block</span>
  render(<span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">MyComponent</span> /&gt;</span></span>);
  <span class="hljs-keyword">const</span> element = screen.getByText(<span class="hljs-string">'Hello, World!'</span>);
  expect(element).toBeInTheDocument();
});
</code></pre>
<p>The above test checks whether the element having the text <code>Hello, World!</code> is rendering properly on the screen or not.</p>
<p>We use <code>render</code> function to render the component we are supposed to test on.</p>
<p>The <code>screen</code> object is an essential utility that provides methods for querying and interacting with the rendered components.</p>
<p><strong>To understand these methods refer to the below chart</strong></p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1698417917957/329cae68-5476-4ae3-8087-dfac99810b6a.png" alt class="image--center mx-auto" /></p>
<p>The chart shows what each function returns in the case of No Match, 1 Match, 1+ Match and async calls.</p>
<p><strong>A Little bit about Jest</strong></p>
<p>Jest is a JavaScript testing framework maintained by Facebook. It's a powerful and developer-friendly tool for testing JavaScript code, including React applications.</p>
<p>It provides features like test runners, assertion libraries, mocking, and code coverage out of the box.</p>
<p>Use <code>Jest's test runner to execute your tests</code>. You can do this through the command line with <code>npm test</code> or <code>yarn test</code> (if configured).</p>
<p><strong>To learn more in-depth on testing refer to the following resources</strong></p>
<div class="embed-wrapper"><div class="embed-loading"><div class="loadingRow"></div><div class="loadingRow"></div></div><a class="embed-card" href="https://youtube.com/playlist?list=PL4cUxeGkcC9gm4_-5UsNmLqMosM-dzuvQ&amp;si=-4PECEXjOuEzqQYt">https://youtube.com/playlist?list=PL4cUxeGkcC9gm4_-5UsNmLqMosM-dzuvQ&amp;si=-4PECEXjOuEzqQYt</a></div>
<p> </p>
<p>Checkout <code>React testing library documentation</code> here <a target="_blank" href="https://testing-library.com/docs/react-testing-library/intro/">Docs</a></p>
<p>📚 <strong>Stay In the Know! Follow Our Blog</strong></p>
<p>Discover a world of knowledge, inspiration, and insights right at your fingertips. Our blog is a treasure trove of valuable content that you won't want to miss. 🌟</p>
<p>Don't miss out! Click that "Follow" button now, and let the learning journey begin.</p>
<p>📖✨</p>
]]></content:encoded></item><item><title><![CDATA[Server Side Rendering vs Client Side Rendering]]></title><description><![CDATA[Server-side rendering (SSR) and client-side rendering (CSR) are two different approaches to rendering web content, and they have distinct implications for how web applications are built and how they perform.
Server-Side Rendering (SSR):
Definition: I...]]></description><link>https://blog.ratishfolio.com/server-side-rendering-vs-client-side-rendering</link><guid isPermaLink="true">https://blog.ratishfolio.com/server-side-rendering-vs-client-side-rendering</guid><category><![CDATA[Next.js]]></category><category><![CDATA[React]]></category><category><![CDATA[Client-side rendering]]></category><category><![CDATA[Server side rendering]]></category><category><![CDATA[Web Development]]></category><dc:creator><![CDATA[Ratish Jain]]></dc:creator><pubDate>Wed, 18 Oct 2023 08:59:35 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1697619289031/08e9d8b0-edda-43ca-9cb7-82712abf237e.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Server-side rendering (SSR) and client-side rendering (CSR) are two different approaches to rendering web content, and they have distinct implications for how web applications are built and how they perform.</p>
<h2 id="heading-server-side-rendering-ssr"><strong>Server-Side Rendering (SSR):</strong></h2>
<p><strong>Definition:</strong> In SSR, the server generates the HTML for a web page and sends it to the client (usually a web browser) as a fully rendered page. This means that the initial page load includes all the content and is ready to be displayed immediately.</p>
<h3 id="heading-static-server-side-rendering-static-ssr"><strong>Static Server-Side Rendering (Static SSR):</strong></h3>
<ol>
<li><p><strong>Definition:</strong> In Static SSR, the server pre-generates HTML pages at build time or when content changes. Each page is pre-rendered into a static HTML file and stored on the server. These pre-rendered pages are then served to clients upon request.</p>
</li>
<li><p><strong>Key Characteristics:</strong></p>
<ul>
<li><p>Pre-Generated Pages: All the pages are generated in advance, typically during the build process. This means that content does not change on the server at runtime.</p>
</li>
<li><p>Fast and Scalable: Since the HTML pages are pre-rendered, they can be served very quickly to clients. This approach is highly scalable as it doesn't require much server-side computation for each request.</p>
</li>
<li><p>Ideal for Content-Heavy Sites: Static SSR is well-suited for websites with mostly static content, like blogs, news sites, or e-commerce platforms with infrequent product updates.</p>
</li>
</ul>
</li>
<li><p><strong>Use Cases:</strong></p>
<ul>
<li><p>Static Websites: Websites with content that doesn't change frequently, like company homepages or personal blogs, can benefit from Static SSR to achieve fast page loads.</p>
</li>
<li><p>Jamstack Architecture: Static site generators like Gatsby, Next.js (with static site generation), or Hugo often use Static SSR to create efficient and performant websites.</p>
</li>
</ul>
</li>
</ol>
<h3 id="heading-dynamic-server-side-rendering-dynamic-ssr"><strong>Dynamic Server-Side Rendering (Dynamic SSR):</strong></h3>
<ol>
<li><p><strong>Definition:</strong> In Dynamic SSR, the server generates HTML pages for each request, and the content may change based on user interactions or data from external sources (e.g., a database). Unlike Static SSR, pages are created or modified at runtime.</p>
</li>
<li><p><strong>Key Characteristics:</strong></p>
<ul>
<li><p>On-Demand Rendering: Each page is generated on the server when a user requests it, allowing for dynamic content and personalization.</p>
</li>
<li><p>Real-Time Updates: Dynamic SSR can provide real-time or near-real-time updates because it can fetch and render the latest data on each request.</p>
</li>
<li><p>Suitable for Content that Changes Frequently: Applications where content is frequently updated or personalized, such as social media feeds or e-commerce product listings, benefit from Dynamic SSR.</p>
</li>
</ul>
</li>
<li><p><strong>Use Cases:</strong></p>
<ul>
<li><p>Content-Intensive Applications: Dynamic SSR is suitable for applications with frequently changing content, such as news websites, forums, or social media platforms.</p>
</li>
<li><p>Personalized User Experiences: Websites that require user-specific content, like personalized recommendations or user profiles, can use Dynamic SSR to tailor content for each user.</p>
</li>
</ul>
</li>
</ol>
<p>    <img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1697619160877/28920bc1-fe9b-4cd6-9874-04765dca3da6.png" alt class="image--center mx-auto" /></p>
<h2 id="heading-client-side-rendering-csr"><strong>Client-Side Rendering (CSR):</strong></h2>
<ol>
<li><p><strong>Definition:</strong> In CSR, the server sends a minimal HTML shell to the client, which includes JavaScript. The JavaScript code is responsible for fetching data from an API and rendering the content in the browser. The page is constructed dynamically on the client-side.</p>
</li>
<li><p><strong>Key Characteristics:</strong></p>
<ul>
<li><p>Slower Initial Load: CSR typically results in a slower initial page load because the client needs to download the minimal HTML and then execute JavaScript to populate the content.</p>
</li>
<li><p>Interactive and Fast Navigation: Once the initial load is complete, CSR can provide a smoother and more interactive user experience as subsequent navigation and content updates can be faster.</p>
</li>
<li><p>Not SEO-Friendly by Default: Search engines may have difficulty indexing content initially because they might not execute JavaScript.</p>
</li>
</ul>
</li>
<li><p><strong>Use Cases:</strong></p>
<ul>
<li><p>Single-Page Applications (SPAs): Applications that require a high level of interactivity, like social media platforms or web-based productivity tools, often use CSR to provide a dynamic user experience.</p>
</li>
<li><p>Web Apps with Frequent Updates: Applications where content is frequently updated or needs real-time data often opt for CSR because it allows for quick updates without full page reloads.</p>
</li>
</ul>
</li>
</ol>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1697619365674/802740c8-b7d8-41a3-9daf-a0f33f3202a0.png" alt class="image--center mx-auto" /></p>
<p>In many real-world scenarios, a combination of SSR and CSR is used. This approach, known as "Hybrid Rendering," takes advantage of the benefits of both techniques. For example, a website may use SSR for the initial page load to optimize speed and SEO and then switch to CSR for subsequent navigation and interactions to provide a more interactive user experience. This mix allows web developers to strike a balance between performance and interactivity based on the specific needs of their application.</p>
]]></content:encoded></item><item><title><![CDATA[Filter map and reduce in Javascript]]></title><description><![CDATA[In the world of JavaScript programming, the ability to manipulate arrays efficiently and elegantly is a skill that separates novice developers from seasoned experts.
map, filter, and reduce These three versatile functions are not only essential tools...]]></description><link>https://blog.ratishfolio.com/filter-map-and-reduce-in-javascript</link><guid isPermaLink="true">https://blog.ratishfolio.com/filter-map-and-reduce-in-javascript</guid><category><![CDATA[JavaScript]]></category><category><![CDATA[Developer]]></category><category><![CDATA[Web Development]]></category><category><![CDATA[interview]]></category><category><![CDATA[internships]]></category><dc:creator><![CDATA[Ratish Jain]]></dc:creator><pubDate>Thu, 28 Sep 2023 06:00:04 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1695880616625/814d1639-2ae4-4d13-a705-b90cdba54899.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>In the world of JavaScript programming, the ability to manipulate arrays efficiently and elegantly is a skill that separates novice developers from seasoned experts.</p>
<p><code>map</code>, <code>filter</code>, and <code>reduce</code> These three versatile functions are not only essential tools in a JavaScript developer's arsenal but also shining examples of the functional programming paradigm.</p>
<p>let's learn these three very important functions in a step-by-step manner</p>
<h2 id="heading-map">Map</h2>
<ul>
<li><p>The <code>map</code> function creates a new array by applying a given function to each element of an existing array.</p>
</li>
<li><p>It does not modify the original array; instead, it returns a new array with the results.</p>
</li>
<li><pre><code class="lang-javascript">      <span class="hljs-keyword">const</span> numbers = [<span class="hljs-number">1</span>,<span class="hljs-number">2</span>,<span class="hljs-number">3</span>,<span class="hljs-number">4</span>];
      <span class="hljs-keyword">const</span> doubledNumbers = numbers.map(<span class="hljs-function">(<span class="hljs-params">num</span>) =&gt;</span> num * <span class="hljs-number">2</span>);

      <span class="hljs-built_in">console</span>.log(doubledNumbers);
      <span class="hljs-comment">//output - [1,4,6,8]</span>
</code></pre>
</li>
</ul>
<h2 id="heading-filter">Filter</h2>
<ul>
<li><p>The <code>filter</code> function creates a new array containing all the elements that pass a test implemented by the provided function.</p>
</li>
<li><p>It does not modify the original array; instead, it returns a new array with the results.</p>
</li>
<li><pre><code class="lang-javascript">      <span class="hljs-keyword">const</span> numbers = [<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>, <span class="hljs-number">4</span>, <span class="hljs-number">5</span>];
      <span class="hljs-keyword">const</span> evenNumbers = numbers.filter(<span class="hljs-function">(<span class="hljs-params">num</span>) =&gt;</span> num % <span class="hljs-number">2</span> === <span class="hljs-number">0</span>);
      <span class="hljs-built_in">console</span>.log(evenNumbers);
      <span class="hljs-comment">//output [2,4]</span>
</code></pre>
</li>
</ul>
<h2 id="heading-reduce">Reduce</h2>
<ul>
<li><p>The <code>reduce</code> function reduces an array to a single value by applying a function to each element and accumulating the result.</p>
</li>
<li><p>It takes a callback function that has an accumulator (the accumulated result) and the current element as arguments.</p>
</li>
<li><p>You can also provide an initial value for the accumulator.</p>
</li>
<li><pre><code class="lang-javascript">      <span class="hljs-keyword">const</span> numbers = [<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>, <span class="hljs-number">4</span>, <span class="hljs-number">5</span>];
      <span class="hljs-keyword">const</span> sum = numbers.reduce((accumulator, current) {
                      <span class="hljs-keyword">return</span> accumulator + current
                  }, <span class="hljs-number">0</span>);
      <span class="hljs-built_in">console</span>.log(sum);
      <span class="hljs-comment">//output - 15</span>
</code></pre>
</li>
<li><p>The second parameter 0 is the initial value given to the accumulator.</p>
</li>
</ul>
<h2 id="heading-conclusion">Conclusion</h2>
<p>In summary, <code>map</code> transforms each element of an array and returns a new array, <code>filter</code> selects elements that meet a specific condition, and <code>reduce</code> accumulates the elements into a single value. These functions are powerful tools for working with arrays functionally and concisely, improving code readability and maintainability.</p>
]]></content:encoded></item><item><title><![CDATA[Object Oriented Programming in Javascript]]></title><description><![CDATA[JavaScript, often referred to as the "language of the web," is a versatile and powerful programming language. One of its key strengths is its support for Object-Oriented Programming (OOP) principles. In this blog post, we'll dive into the world of OO...]]></description><link>https://blog.ratishfolio.com/object-oriented-programming-in-javascript</link><guid isPermaLink="true">https://blog.ratishfolio.com/object-oriented-programming-in-javascript</guid><category><![CDATA[Hashnode]]></category><category><![CDATA[hashnodebootcamp]]></category><category><![CDATA[JavaScript]]></category><category><![CDATA[Object Oriented Programming]]></category><category><![CDATA[Developer]]></category><dc:creator><![CDATA[Ratish Jain]]></dc:creator><pubDate>Thu, 21 Sep 2023 16:51:30 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1695314996159/e44d8d91-41fd-4a92-b652-bed0a96c475b.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>JavaScript, often referred to as the "language of the web," is a versatile and powerful programming language. One of its key strengths is its support for Object-Oriented Programming (OOP) principles. In this blog post, we'll dive into the world of OOP in JavaScript, exploring its key concepts and how to use them effectively.</p>
<h2 id="heading-understanding-objects">Understanding Objects</h2>
<p>At the core of Javascript OOP is objects. Everything in javascript under the hood is an object, An object is a collection of key-value pairs where keys are strings (or symbols) and values can be of any data type or even functions.</p>
<p>Here's an example of Object in Javascript -</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> person = {
  <span class="hljs-attr">name</span>: <span class="hljs-string">"John"</span>,
  <span class="hljs-attr">age</span>: <span class="hljs-number">30</span>,
  <span class="hljs-attr">sayHello</span>: <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params"></span>) </span>{
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`Hello, my name is <span class="hljs-subst">${<span class="hljs-built_in">this</span>.name}</span> and I am <span class="hljs-subst">${<span class="hljs-built_in">this</span>.age}</span> years old.`</span>);
  }
};

person.sayHello(); <span class="hljs-comment">// Output: Hello, my name is John and I am 30 years old.</span>
</code></pre>
<h2 id="heading-classes-and-constructors-in-javascript">Classes and Constructors in Javascript</h2>
<p>In ES6(ECMAScript 6), Javascript introduced a more structured and general way of creating objects. A class is a blueprint for creating objects with shared properties and methods.</p>
<p>Example -</p>
<pre><code class="lang-javascript"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Person</span> </span>{
  <span class="hljs-keyword">constructor</span>(name, age) { <span class="hljs-comment">// constructor for the class</span>
    <span class="hljs-built_in">this</span>.name = name;
    <span class="hljs-built_in">this</span>.age = age;
  }

  Hello() { <span class="hljs-comment">//no need to use function keyword in class</span>
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`Hello, my name is <span class="hljs-subst">${<span class="hljs-built_in">this</span>.name}</span> and I am <span class="hljs-subst">${<span class="hljs-built_in">this</span>.age}</span> years old.`</span>);
  }
}

<span class="hljs-keyword">const</span> person1 = <span class="hljs-keyword">new</span> Person(<span class="hljs-string">'John'</span>, <span class="hljs-number">30</span>);
<span class="hljs-keyword">const</span> person2 = <span class="hljs-keyword">new</span> Person(<span class="hljs-string">'Jane'</span>, <span class="hljs-number">25</span>);

person1.Hello(); <span class="hljs-comment">// Output: Hello, my name is John and I am 30 years old.</span>
person2.Hello(); <span class="hljs-comment">// Output: Hello, my name is Jane and I am 25 years old.</span>
</code></pre>
<p>The constructor function of the class gets called whenever a new keyword is used to create the object of that class and initializes initial values for the object.</p>
<p>The "this" keyword helps in getting the context of the current object and setting the values.  </p>
<h2 id="heading-inheritance-and-subclasses">Inheritance and Subclasses</h2>
<p>JavaScript also supports inheritance through prototype-based inheritance. You can create a subclass (a child class) that inherits properties and methods from a parent class (a superclass).</p>
<pre><code class="lang-javascript"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Student</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">Person</span> </span>{
  <span class="hljs-keyword">constructor</span>(name, age, grade) {
    <span class="hljs-built_in">super</span>(name, age); <span class="hljs-comment">// Call the parent class constructor</span>
    <span class="hljs-built_in">this</span>.grade = grade;
  }

  study() {
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`<span class="hljs-subst">${<span class="hljs-built_in">this</span>.name}</span> is studying for their <span class="hljs-subst">${<span class="hljs-built_in">this</span>.grade}</span> grade.`</span>);
  }
}

<span class="hljs-keyword">const</span> student1 = <span class="hljs-keyword">new</span> Student(<span class="hljs-string">'Alice'</span>, <span class="hljs-number">12</span>, <span class="hljs-string">'6th'</span>);
student1.sayHello(); <span class="hljs-comment">// Output: Hello, my name is Alice and I am 12 years old.</span>
student1.study();
</code></pre>
<p>The super() function calls the superclass constructor function.</p>
<p>using extends keyword class Student inherits properties and methods of class Person and now we can use the properties of Person class in a Student object.</p>
<p>This phenomena is called inheritance.</p>
<h2 id="heading-encapsulation-abstraction-and-more"><strong>Encapsulation, Abstraction, and More</strong></h2>
<p>OOP in JavaScript allows you to implement essential OOP principles such as encapsulation and abstraction. You can hide internal details and expose only the necessary interfaces, making your code more modular and maintainable.</p>
<p>Additionally, JavaScript provides tools like getters and setters to control access to object properties, further enhancing encapsulation.</p>
<p>To learn more in depth about these topics I'll be providing blogs on the topics soon.</p>
<h2 id="heading-conclusion">Conclusion</h2>
<p>Object-Oriented Programming in JavaScript empowers developers to create structured, reusable, and maintainable code. Understanding objects, classes, constructors, and inheritance is fundamental to harnessing the power of OOP in JavaScript. With these concepts in your toolkit, you can design elegant and efficient solutions for a wide range of applications.</p>
]]></content:encoded></item><item><title><![CDATA[JavaScript Prototypes and Prototypal Inheritance]]></title><description><![CDATA[Prototypes: Foundation of Javascript
In Javascript, everything is an object and the prototype serves as a blueprint for every object containing its properties and methods.
To understand it more easily let's first understand what are constructor funct...]]></description><link>https://blog.ratishfolio.com/javascript-prototypes-and-prototypal-inheritance</link><guid isPermaLink="true">https://blog.ratishfolio.com/javascript-prototypes-and-prototypal-inheritance</guid><category><![CDATA[JavaScript]]></category><category><![CDATA[Developer]]></category><category><![CDATA[development]]></category><category><![CDATA[DSA]]></category><category><![CDATA[Hashnode]]></category><dc:creator><![CDATA[Ratish Jain]]></dc:creator><pubDate>Mon, 18 Sep 2023 15:21:18 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1695050317856/d17dca02-9b77-4035-8b2e-53bfe33cff2c.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h2 id="heading-prototypes-foundation-of-javascript">Prototypes: Foundation of Javascript</h2>
<p>In Javascript, everything is an object and the prototype serves as a blueprint for every object containing its properties and methods.</p>
<p>To understand it more easily let's first understand what are constructor functions</p>
<h3 id="heading-constructor-functions">Constructor Functions -</h3>
<p>Constructor functions are used to create objects. They act as templates for objects, defining their initial state and behavior.</p>
<p>Here's an example -</p>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">myObj</span>(<span class="hljs-params">name,age</span>)</span>{ <span class="hljs-comment">//constructor functions</span>
    <span class="hljs-built_in">this</span>.name = name;
    <span class="hljs-built_in">this</span>.age = age;
}

<span class="hljs-keyword">const</span> obj1 = <span class="hljs-keyword">new</span> myObj(<span class="hljs-string">"xyz"</span>,<span class="hljs-string">"20"</span>);
<span class="hljs-keyword">const</span> obj2 = <span class="hljs-keyword">new</span> myObj(<span class="hljs-string">"yzx"</span>,<span class="hljs-string">"21"</span>);
</code></pre>
<p>The above constructor function takes properties <strong>"name"</strong> and <strong>"age"</strong> and sets them as properties on the newly created objects with the <strong>new</strong> keyword**.**</p>
<p>However, with this approach, each object created using <code>new myObj()</code> has its own copy of the properties and methods, leading to potential memory inefficiencies if there are many instances.</p>
<h3 id="heading-prototypes">Prototypes -</h3>
<p>JavaScript's prototype system comes into play to address above issue. Every function in JavaScript has a property called <code>prototype</code>, which is an object that can hold properties and methods shared among all instances created by that constructor function.</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, age</span>) </span>{
  <span class="hljs-built_in">this</span>.name = name;
  <span class="hljs-built_in">this</span>.age = age;
}

Person.prototype.sayHello = <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params"></span>) </span>{
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`Hello, my name is <span class="hljs-subst">${<span class="hljs-built_in">this</span>.name}</span> and I am <span class="hljs-subst">${<span class="hljs-built_in">this</span>.age}</span> years old.`</span>);
};

<span class="hljs-keyword">const</span> person1 = <span class="hljs-keyword">new</span> Person(<span class="hljs-string">"Alice"</span>, <span class="hljs-number">30</span>);
<span class="hljs-keyword">const</span> person2 = <span class="hljs-keyword">new</span> Person(<span class="hljs-string">"Bob"</span>, <span class="hljs-number">25</span>);

person1.sayHello(); <span class="hljs-comment">// "Hello, my name is Alice and I am 30 years old."</span>
person2.sayHello(); <span class="hljs-comment">// "Hello, my name is Bob and I am 25 years old."</span>
</code></pre>
<p>Since everything in javascript is an object we can use their prototype attribute to create our own set of properties for such objects common to all the instances of that object as the sayHello() function created above will be available to both person1 and person2 objects as both are instance of the same constructor function.</p>
<h2 id="heading-prototypal-inheritance">Prototypal Inheritance -</h2>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1695049273468/66a0bab0-b247-47b8-90ac-8bd346aeca8d.png" alt class="image--center mx-auto" /></p>
<p>You can achieve prototypal inheritance using the <code>__proto__</code> property in JavaScript. Here's an example:</p>
<pre><code class="lang-javascript"><span class="hljs-comment">// Parent object</span>
<span class="hljs-keyword">const</span> animal = {
  <span class="hljs-attr">speak</span>: <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params"></span>) </span>{
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`I am an animal.`</span>);
  },
};

<span class="hljs-comment">// Child object inheriting from the parent</span>
<span class="hljs-keyword">const</span> dog = {
  <span class="hljs-attr">__proto__</span>: animal, <span class="hljs-comment">// Set the prototype to 'animal'</span>
  <span class="hljs-attr">bark</span>: <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params"></span>) </span>{
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Woof!"</span>);
  },
};

<span class="hljs-comment">// Create instances of 'dog'</span>
<span class="hljs-keyword">const</span> dog1 = <span class="hljs-built_in">Object</span>.create(dog);
dog1.speak(); <span class="hljs-comment">// "I am an animal."</span>
dog1.bark();  <span class="hljs-comment">// "Woof!"</span>

<span class="hljs-keyword">const</span> dog2 = <span class="hljs-built_in">Object</span>.create(dog);
dog2.speak(); <span class="hljs-comment">// "I am an animal."</span>
dog2.bark();  <span class="hljs-comment">// "Woof!"</span>
</code></pre>
<p>Here, the dog object inherits the properties of the animal object with the help of <code>__proto__</code> property. so all instances of the dog object will have the speak function in their prototype methods and variables.</p>
<p>However, <code>__proto__</code> property was used in older javascript syntax in new Javascript modern syntax <code>Object.setPrototypeOf()</code> and <code>Object.getPrototypeOf()</code></p>
<p>Here's an example -</p>
<pre><code class="lang-javascript"><span class="hljs-comment">// Parent object</span>
<span class="hljs-keyword">const</span> animal = {
  <span class="hljs-attr">speak</span>: <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params"></span>) </span>{
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`I am an animal.`</span>);
  },
};

<span class="hljs-comment">// Child object</span>
<span class="hljs-keyword">const</span> dog = {
  <span class="hljs-attr">bark</span>: <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params"></span>) </span>{
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Woof!"</span>);
  },
};

<span class="hljs-comment">// Establishing prototype-based inheritance</span>
<span class="hljs-built_in">Object</span>.setPrototypeOf(dog, animal);

<span class="hljs-comment">// Create instances of 'dog'</span>
<span class="hljs-keyword">const</span> dog1 = <span class="hljs-built_in">Object</span>.create(dog);
dog1.speak(); <span class="hljs-comment">// "I am an animal."</span>
dog1.bark();  <span class="hljs-comment">// "Woof!"</span>

<span class="hljs-keyword">const</span> dog2 = <span class="hljs-built_in">Object</span>.create(dog);
dog2.speak(); <span class="hljs-comment">// "I am an animal."</span>
dog2.bark();  <span class="hljs-comment">// "Woof!"</span>
</code></pre>
<p>We use <code>Object.setPrototypeOf(dog, animal)</code> to establish prototype-based inheritance. This sets the prototype of <code>dog</code> to <code>animal</code>, creating a prototype chain where <code>dog</code> inherits from <code>animal</code>.</p>
<h2 id="heading-conclusion">Conclusion -</h2>
<p>In conclusion, JavaScript offers several mechanisms for establishing prototype-based inheritance, each with its own advantages and use cases. Whether you choose to use constructor functions, <code>Object.create()</code>, or <code>Object.setPrototypeOf()</code>, the fundamental concept remains the same: objects can inherit properties and methods from their prototypes, creating a flexible and efficient way to structure and organize your code.</p>
<p>Understanding prototype chains and how objects relate to each other through prototypes is crucial for writing maintainable and efficient JavaScript code.</p>
<h2 id="heading-subscribe-to-our-blog-post-to-learn-more-about-the-fundamentals-of-web-development">Subscribe to our blog post to learn more about the fundamentals of web development.</h2>
]]></content:encoded></item><item><title><![CDATA[Streamline Form Validation with React Hook Form and implement Email Service using EmailJS]]></title><description><![CDATA[In web development, form validation is a crucial aspect to ensure data accuracy and user experience. React Hook Form is a powerful library that simplifies the process of building robust forms in React applications. Alongside form validation, integrat...]]></description><link>https://blog.ratishfolio.com/streamline-form-validation-with-react-hook-form-and-implement-email-service-using-emailjs</link><guid isPermaLink="true">https://blog.ratishfolio.com/streamline-form-validation-with-react-hook-form-and-implement-email-service-using-emailjs</guid><category><![CDATA[CNCF]]></category><category><![CDATA[Web Development]]></category><category><![CDATA[React]]></category><category><![CDATA[JavaScript]]></category><category><![CDATA[development]]></category><dc:creator><![CDATA[Ratish Jain]]></dc:creator><pubDate>Sat, 15 Jul 2023 15:59:45 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1689436647648/0256ebc8-2b20-40f3-8681-dd1006ddc350.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>In web development, form validation is a crucial aspect to ensure data accuracy and user experience. React Hook Form is a powerful library that simplifies the process of building robust forms in React applications. Alongside form validation, integrating email services can enhance functionality by enabling automated email notifications.</p>
<p>In this blog post, we will explore how to combine the capabilities of React Hook Form and EmailJS to create a seamless form validation and email service integration.</p>
<h2 id="heading-what-is-react-hook-form">What is React Hook Form?</h2>
<p>React Hook Form is a lightweight and performant library for managing forms in React applications. It simplifies form validation, state management, and submission handling by leveraging React's hooks feature.</p>
<h2 id="heading-setting-up-a-react-application">Setting up a React Application:</h2>
<p>To get started, ensure that you have Node.js and npm (Node Package Manager) installed on your machine. Create a new React application using the following command in your terminal:</p>
<pre><code class="lang-bash">npx create-react-app form-validation-email-service
</code></pre>
<h2 id="heading-installing-react-hook-form-and-emailjs">Installing React Hook Form and EmailJS:</h2>
<p>Navigate into the project directory and install React Hook Form and EmailJS packages:</p>
<pre><code class="lang-bash"><span class="hljs-built_in">cd</span> form-validation-email-service
npm install react-hook-form @emailjs/browser --save
</code></pre>
<h2 id="heading-building-a-form-with-react-hook-form">Building a Form with React Hook Form:</h2>
<p>In your React component file, import the necessary dependencies:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">import</span> React <span class="hljs-keyword">from</span> <span class="hljs-string">'react'</span>;
<span class="hljs-keyword">import</span> { useForm } <span class="hljs-keyword">from</span> <span class="hljs-string">'react-hook-form'</span>;

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">ContactForm</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">const</span> { register, handleSubmit } = useForm();

  <span class="hljs-keyword">const</span> onSubmit = <span class="hljs-function">(<span class="hljs-params">data</span>) =&gt;</span> {
    <span class="hljs-built_in">console</span>.log(data);
  };

  <span class="hljs-keyword">return</span> (
    <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">form</span> <span class="hljs-attr">onSubmit</span>=<span class="hljs-string">{handleSubmit(onSubmit)}</span>&gt;</span>
      {/* Form fields */}
    <span class="hljs-tag">&lt;/<span class="hljs-name">form</span>&gt;</span></span>
  );
}

<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> ContactForm;
</code></pre>
<h2 id="heading-validating-form-inputs">Validating Form Inputs:</h2>
<p>React Hook Form offers a simple way to validate form inputs using built-in validation rules or custom functions. Let's add some basic validation to our form fields:</p>
<pre><code class="lang-javascript">&lt;input
  type=<span class="hljs-string">"text"</span>
  {...register(<span class="hljs-string">'name'</span>, { <span class="hljs-attr">required</span>: <span class="hljs-literal">true</span> })}
/&gt;

<span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">input</span>
  <span class="hljs-attr">type</span>=<span class="hljs-string">"email"</span>
  {<span class="hljs-attr">...register</span>('<span class="hljs-attr">email</span>', 
    { 
      <span class="hljs-attr">required:</span> <span class="hljs-attr">true</span>, 
      <span class="hljs-attr">pattern:</span> /^[<span class="hljs-attr">A-Z0-9._</span>%+<span class="hljs-attr">-</span>]+@[<span class="hljs-attr">A-Z0-9.-</span>]+\<span class="hljs-attr">.</span>[<span class="hljs-attr">A-Z</span>]{<span class="hljs-attr">2</span>,}$/<span class="hljs-attr">i</span> 
    }
  )}
/&gt;</span></span>
</code></pre>
<h2 id="heading-submitting-form-data">Submitting Form Data:</h2>
<p>To handle form submission, we'll utilize the <code>handleSubmit</code> function provided by React Hook Form. In the <code>onSubmit</code> callback, we can access the form data and perform further actions:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> onSubmit = <span class="hljs-function">(<span class="hljs-params">data</span>) =&gt;</span> {
  <span class="hljs-built_in">console</span>.log(data);

  <span class="hljs-comment">// Perform additional actions like API calls or email service integration</span>
};
</code></pre>
<h1 id="heading-integrating-emailjs">Integrating EmailJS</h1>
<p>EmailJS is a service that allows you to send emails directly from the client-side without any server-side code.</p>
<p>Sign up for an account on the EmailJS website and obtain your user ID and template ID. Import the EmailJS library and configure it with your credentials:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">import</span> emailjs <span class="hljs-keyword">from</span> <span class="hljs-string">'@emailjs/browser'</span>;

 <span class="hljs-keyword">const</span> onSubmit = <span class="hljs-function">(<span class="hljs-params">data</span>) =&gt;</span> {
    <span class="hljs-built_in">console</span>.log(data);
    <span class="hljs-keyword">const</span> params = {
        <span class="hljs-string">"user_name"</span>:data.username, <span class="hljs-comment">//key value mustbe same as in your template in emailjs</span>
        <span class="hljs-string">"user_email"</span>:data.email,
        <span class="hljs-string">"message"</span>: data.message,
    }
    emailjs.sendForm(<span class="hljs-string">'YOUR_SERVICE_ID'</span>, <span class="hljs-string">'YOUR_TEMPLATE_ID'</span>, params ,<span class="hljs-string">'YOUR_PUBLIC_KEY'</span>)
      .then(<span class="hljs-function">(<span class="hljs-params">result</span>) =&gt;</span> {
          <span class="hljs-built_in">console</span>.log(result.text);
      }, <span class="hljs-function">(<span class="hljs-params">error</span>) =&gt;</span> {
          <span class="hljs-built_in">console</span>.log(error.text);
      });
  };
</code></pre>
<p>You can now test your form by filling in the required fields and submitting it. Ensure that you receive the success message and check the recipient's email inbox for the email notification.</p>
<h1 id="heading-conclusion">Conclusion</h1>
<p>In this blog post, we explored the process of implementing form validation using React Hook Form and integrating an email service using EmailJS. React Hook Form simplified form management by providing an intuitive API for validation and submission handling. By integrating EmailJS, we were able to enhance the functionality by sending automated email notifications to the desired recipient.</p>
<p>Remember to further explore the documentation of React Hook Form and EmailJS to unleash their full potential in your projects. Happy coding!</p>
]]></content:encoded></item><item><title><![CDATA[Object Oriented Programming in Dart: An Extensive Guide!!]]></title><description><![CDATA[Object-oriented programming (OOP) is a programming approach that organizes code around objects, representing real-world entities. It involves encapsulating data and behavior within objects, using classes as blueprints. OOP emphasizes principles such ...]]></description><link>https://blog.ratishfolio.com/object-oriented-programming-in-dart-an-extensive-guide</link><guid isPermaLink="true">https://blog.ratishfolio.com/object-oriented-programming-in-dart-an-extensive-guide</guid><category><![CDATA[Object Oriented Programming]]></category><category><![CDATA[Dart]]></category><category><![CDATA[development]]></category><category><![CDATA[Flutter]]></category><category><![CDATA[Developer]]></category><dc:creator><![CDATA[Ratish Jain]]></dc:creator><pubDate>Thu, 25 May 2023 04:30:39 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1684930401574/f3dca9ce-f31d-4a0a-8787-3236a0ab7772.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Object-oriented programming (OOP) is a programming approach that organizes code around objects, representing real-world entities. It involves encapsulating data and behavior within objects, using classes as blueprints. OOP emphasizes principles such as encapsulation, inheritance, polymorphism, abstraction, and modularity to promote code organization, reusability, and flexibility.</p>
<h3 id="heading-heres-an-extensive-guide-to-object-oriented-programming-oop-in-dart">Here's an extensive guide to object-oriented programming (OOP) in Dart:</h3>
<ol>
<li><p>Classes and Objects:</p>
<ul>
<li><p>Classes in Dart define the blueprint for creating objects. You can create classes using the <code>class</code> keyword.</p>
</li>
<li><p>Objects are instances of classes, and you can create objects using the <code>new</code> keyword or by omitting it in newer Dart versions.</p>
</li>
</ul>
</li>
</ol>
<pre><code class="lang-dart">    <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Person</span> </span>{
      <span class="hljs-built_in">String</span> name; <span class="hljs-comment">//variables of a class</span>
      <span class="hljs-built_in">int</span> age; <span class="hljs-comment">//variables of a class</span>

      <span class="hljs-keyword">void</span> sayHello() {
        <span class="hljs-built_in">print</span>(<span class="hljs-string">"Hello, my name is <span class="hljs-subst">$name</span>. I'm <span class="hljs-subst">$age</span> years old."</span>);
      }
    }

    <span class="hljs-keyword">void</span> main() {
      <span class="hljs-comment">// Creating an object of the Person class</span>
      <span class="hljs-keyword">var</span> person = Person();
      person.name = <span class="hljs-string">"John"</span>;
      person.age = <span class="hljs-number">30</span>;

      <span class="hljs-comment">// Calling the sayHello() method</span>
      person.sayHello(); <span class="hljs-comment">// Output: Hello, my name is John. I'm 30 years old.</span>
    }
</code></pre>
<ul>
<li><p>Properties represent the state or data associated with an object. They are declared using variables inside a class.</p>
</li>
<li><p>Methods define the behavior of an object. They are functions defined within a class and can manipulate the object's properties.</p>
</li>
</ul>
<ol>
<li>Constructors:</li>
</ol>
<ul>
<li><p>Constructors are special methods used for object initialization. Dart provides default constructors if none is defined explicitly.</p>
</li>
<li><p>You can create named constructors to provide multiple ways to create objects.</p>
</li>
<li><p>The <code>this</code> keyword refers to the current instance of the class within a constructor.</p>
</li>
<li><p>There is another type of constructor known as redirecting constructor in Dart.</p>
</li>
</ul>
<pre><code class="lang-dart"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Point</span> </span>{
  <span class="hljs-built_in">double</span> x;
  <span class="hljs-built_in">double</span> y;

  <span class="hljs-comment">// Default constructor</span>
  Point(<span class="hljs-keyword">this</span>.x, <span class="hljs-keyword">this</span>.y);

  <span class="hljs-comment">// Named constructor</span>
  Point.origin() {
    x = <span class="hljs-number">0</span>;
    y = <span class="hljs-number">0</span>;
  }

  <span class="hljs-comment">// redirecting Constructors</span>
  Point.addval(<span class="hljs-built_in">double</span> x, <span class="hljs-built_in">double</span> y) : <span class="hljs-keyword">this</span>(x,y);
}

<span class="hljs-keyword">void</span> main() {
  <span class="hljs-keyword">var</span> p1 = Point(<span class="hljs-number">2</span>, <span class="hljs-number">3</span>); <span class="hljs-comment">// Using the default constructor</span>
  <span class="hljs-built_in">print</span>(<span class="hljs-string">"Point p1: (<span class="hljs-subst">${p1.x}</span>, <span class="hljs-subst">${p1.y}</span>)"</span>); <span class="hljs-comment">// Output: Point p1: (2.0, 3.0)</span>

  <span class="hljs-keyword">var</span> p2 = Point.origin(); <span class="hljs-comment">// Using the named constructor</span>
  <span class="hljs-built_in">print</span>(<span class="hljs-string">"Point p2: (<span class="hljs-subst">${p2.x}</span>, <span class="hljs-subst">${p2.y}</span>)"</span>); <span class="hljs-comment">// Output: Point p2: (0.0, 0.0)</span>

  <span class="hljs-keyword">var</span> p3 = Point.addval(<span class="hljs-number">4</span>,<span class="hljs-number">5</span>); <span class="hljs-comment">// Using the redirecting constructor</span>
  <span class="hljs-built_in">print</span>(<span class="hljs-string">"Point p3: (<span class="hljs-subst">${p3.x}</span>, <span class="hljs-subst">${p3.y}</span>)"</span>); <span class="hljs-comment">// Output: Point p3: (4.0, 5.0)</span>
}
</code></pre>
<h3 id="heading-important-concepts-of-oop-in-dart">Important Concepts of OOP in Dart:</h3>
<ol>
<li><p>Inheritance:</p>
<ul>
<li><p>Inheritance allows you to create new classes based on existing ones. The new class inherits the properties and methods of the parent class.</p>
</li>
<li><p>Dart supports single inheritance, meaning a class can only inherit from one superclass.</p>
</li>
<li><p>The <code>extends</code> keyword is used to establish inheritance relationships.</p>
</li>
</ul>
</li>
</ol>
<pre><code class="lang-dart">    <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Animal</span> </span>{
      <span class="hljs-keyword">void</span> eat() {
        <span class="hljs-built_in">print</span>(<span class="hljs-string">"Animal is eating."</span>);
      }
    }

    <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Dog</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">Animal</span> </span>{
      <span class="hljs-keyword">void</span> bark() {
        <span class="hljs-built_in">print</span>(<span class="hljs-string">"Dog is barking."</span>);
      }
    }

    <span class="hljs-keyword">void</span> main() {
      <span class="hljs-keyword">var</span> dog = Dog();
      dog.eat(); <span class="hljs-comment">// Output: Animal is eating.</span>
      dog.bark(); <span class="hljs-comment">// Output: Dog is barking.</span>
    }
</code></pre>
<ol>
<li><p>Polymorphism:</p>
<ul>
<li><p>Polymorphism allows objects of different classes to be treated as objects of a common superclass.</p>
</li>
<li><p>Dart achieves polymorphism through method overriding. You can override methods in a subclass to provide different implementations.</p>
</li>
</ul>
</li>
</ol>
<pre><code class="lang-dart">    <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Animal</span> </span>{
      <span class="hljs-keyword">void</span> makeSound() {
        <span class="hljs-built_in">print</span>(<span class="hljs-string">"Animal is making a sound."</span>);
      }
    }

    <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Dog</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">Animal</span> </span>{
      <span class="hljs-meta">@override</span>
      <span class="hljs-keyword">void</span> makeSound() {
        <span class="hljs-built_in">print</span>(<span class="hljs-string">"Dog is barking."</span>);
      }
    }

    <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Cat</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">Animal</span> </span>{
      <span class="hljs-meta">@override</span>
      <span class="hljs-keyword">void</span> makeSound() {
        <span class="hljs-built_in">print</span>(<span class="hljs-string">"Cat is meowing."</span>);
      }
    }

    <span class="hljs-keyword">void</span> main() {
      <span class="hljs-keyword">var</span> dog = Dog();
      <span class="hljs-keyword">var</span> cat = Cat();

      dog.makeSound(); <span class="hljs-comment">// Output: Dog is barking.</span>
      cat.makeSound(); <span class="hljs-comment">// Output: Cat is meowing.</span>

      <span class="hljs-comment">// Polymorphism in action</span>
      Animal animal = dog;
      animal.makeSound(); <span class="hljs-comment">// Output: Dog is barking.</span>

      animal = cat;
      animal.makeSound(); <span class="hljs-comment">// Output: Cat is meowing.</span>
    }
</code></pre>
<ol>
<li><p>Encapsulation:</p>
<ul>
<li><p>Encapsulation refers to the practice of hiding internal implementation details and exposing only necessary information.</p>
</li>
<li><p>In Dart, you can mark properties and methods as <code>private</code> using the underscore (_) prefix.</p>
</li>
<li><p>You can provide getter and setter methods to control access to private properties.</p>
</li>
</ul>
</li>
<li><p>Abstraction:</p>
<ul>
<li><p>Abstraction focuses on defining interfaces or abstract classes that provide a common set of methods that subclasses must implement.</p>
</li>
<li><p>Dart supports abstract classes and methods using the <code>abstract</code> keyword.</p>
</li>
<li><p>Abstract classes cannot be instantiated directly; they serve as a base for subclasses.</p>
</li>
</ul>
</li>
</ol>
<pre><code class="lang-dart">    <span class="hljs-keyword">abstract</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Animal</span> </span>{
      <span class="hljs-keyword">void</span> makeSound();
    }

    <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Dog</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">Animal</span> </span>{
      <span class="hljs-meta">@override</span>
      <span class="hljs-keyword">void</span> makeSound() {
        <span class="hljs-built_in">print</span>(<span class="hljs-string">"Dog is barking."</span>);
      }
    }

    <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Cat</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">Animal</span> </span>{
      <span class="hljs-meta">@override</span>
      <span class="hljs-keyword">void</span> makeSound() {
        <span class="hljs-built_in">print</span>(<span class="hljs-string">"Cat is meowing."</span>);
      }
    }

    <span class="hljs-keyword">void</span> main() {
      Animal dog = Dog();
      dog.makeSound(); <span class="hljs-comment">// Output: Dog is barking.</span>

      Animal cat = Cat();
      cat.makeSound(); <span class="hljs-comment">// Output: Cat is meowing.</span>
    }
</code></pre>
<ol>
<li><p>Interfaces:</p>
<ul>
<li><p>Dart does not have a separate <code>interface</code> keyword, as every class defines an interface.</p>
</li>
<li><p>You can implement multiple interfaces in a class using the <code>implements</code> keyword.</p>
</li>
<li><p>Classes implementing an interface must provide implementations for all the interface's methods.</p>
</li>
</ul>
</li>
<li><p>Static Members:</p>
<ul>
<li><p>Static members belong to the class itself rather than instances of the class.</p>
</li>
<li><p>You can declare static properties and methods using the <code>static</code> keyword.</p>
</li>
<li><p>Static members can be accessed without creating an object of the class.</p>
</li>
</ul>
</li>
</ol>
<pre><code class="lang-dart">    <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Circle</span> </span>{
      <span class="hljs-keyword">static</span> <span class="hljs-keyword">const</span> <span class="hljs-built_in">double</span> pi = <span class="hljs-number">3.14159</span>;
      <span class="hljs-keyword">static</span> <span class="hljs-built_in">int</span> numberOfCircles = <span class="hljs-number">0</span>;

      Circle() {
        numberOfCircles++;
      }

      <span class="hljs-keyword">static</span> <span class="hljs-keyword">void</span> printPi() {
        <span class="hljs-built_in">print</span>(<span class="hljs-string">"The value of pi is: <span class="hljs-subst">$pi</span>"</span>);
      }
    }

    <span class="hljs-keyword">void</span> main() {
      Circle();
      Circle();

      <span class="hljs-built_in">print</span>(<span class="hljs-string">"Number of circles: <span class="hljs-subst">${Circle.numberOfCircles}</span>"</span>); <span class="hljs-comment">// Output: Number of circles: 2</span>

      Circle.printPi(); <span class="hljs-comment">// Output: The value of pi is: 3.14159</span>
    }
</code></pre>
<ol>
<li><p>Mixins:</p>
<ul>
<li><p>Mixins are a way to reuse a set of methods in multiple classes without using inheritance.</p>
</li>
<li><p>They allow you to add behavior to a class without becoming its superclass.</p>
</li>
<li><p>You can define a mixin using the <code>mixin</code> keyword and apply it to a class using the <code>with</code> keyword.</p>
</li>
</ul>
</li>
</ol>
<pre><code class="lang-dart">    <span class="hljs-keyword">mixin</span> Swimmer {
      <span class="hljs-keyword">void</span> swim() {
        <span class="hljs-built_in">print</span>(<span class="hljs-string">"Swimming..."</span>);
      }
    }

    <span class="hljs-keyword">mixin</span> Flyer {
      <span class="hljs-keyword">void</span> fly() {
        <span class="hljs-built_in">print</span>(<span class="hljs-string">"Flying..."</span>);
      }
    }

    <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Animal</span> </span>{
      <span class="hljs-keyword">void</span> eat() {
        <span class="hljs-built_in">print</span>(<span class="hljs-string">"Eating..."</span>);
      }
    }

    <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Dolphin</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">Animal</span> <span class="hljs-title">with</span> <span class="hljs-title">Swimmer</span> </span>{}

    <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Bird</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">Animal</span> <span class="hljs-title">with</span> <span class="hljs-title">Swimmer</span>, <span class="hljs-title">Flyer</span> </span>{}

    <span class="hljs-keyword">void</span> main() {
      <span class="hljs-keyword">var</span> dolphin = Dolphin();
      dolphin.eat(); <span class="hljs-comment">// Output: Eating...</span>
      dolphin.swim(); <span class="hljs-comment">// Output: Swimming...</span>

      <span class="hljs-keyword">var</span> bird = Bird();
      bird.eat(); <span class="hljs-comment">// Output: Eating...</span>
      bird.swim(); <span class="hljs-comment">// Output: Swimming...</span>
      bird.fly(); <span class="hljs-comment">// Output: Flying...</span>
    }
</code></pre>
<p>This guide covers the key concepts of object-oriented programming in Dart. By understanding these concepts and their implementation in Dart, you can build robust and scalable applications.</p>
<p>Thank you for reading! Stay connected for more valuable content. Be sure to follow us to receive regular updates, exclusive content, and special offers. Join our vibrant community of learners by visiting our website and exploring all that we have to offer. Let's continue our journey of knowledge and growth together!!</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1684930546295/abbfdd00-5212-4e1d-9860-5dc42dc87a3d.jpeg" alt class="image--center mx-auto" /></p>
]]></content:encoded></item><item><title><![CDATA[Simplifying State Management in Flutter with Provider]]></title><description><![CDATA[What is State Management?
State management is the process of managing the state of your Flutter application. The state of an application is the data that changes over time, such as the current user, the current page, or the contents of a shopping car...]]></description><link>https://blog.ratishfolio.com/simplifying-state-management-in-flutter-with-provider</link><guid isPermaLink="true">https://blog.ratishfolio.com/simplifying-state-management-in-flutter-with-provider</guid><category><![CDATA[Flutter]]></category><category><![CDATA[Provider]]></category><category><![CDATA[Blogging]]></category><category><![CDATA[WeMakeDevs]]></category><category><![CDATA[development]]></category><dc:creator><![CDATA[Ratish Jain]]></dc:creator><pubDate>Tue, 16 May 2023 04:30:39 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1684152159848/b5eb5dbd-84d8-4015-9941-af18ef5f26af.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h2 id="heading-what-is-state-management"><strong>What is State Management?</strong></h2>
<p>State management is the process of managing the state of your Flutter application. The state of an application is the data that changes over time, such as the current user, the current page, or the contents of a shopping cart.</p>
<h2 id="heading-why-do-you-need-state-management"><strong>Why do you need State Management?</strong></h2>
<p>Flutter apps are built using a declarative programming language, which means that you describe the UI of your app in terms of how it should look, rather than how it should behave. This makes it easy to create beautiful and complex UIs, but it can also make it difficult to manage the state of your app.</p>
<p>Without state management, you would have to manually update the state of your app whenever it changes. This would be very tedious and error-prone, especially for large and complex apps.</p>
<h2 id="heading-what-is-provider"><strong>What is Provider?</strong></h2>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1684151208912/4bba9a11-9342-4282-891b-3be22e6f1446.avif" alt class="image--center mx-auto" /></p>
<p>provider is a state management package for Flutter that makes it easy to manage the state of your app. Provider uses a concept called dependency injection to manage the state of your app.</p>
<p>Dependency injection is a technique where you pass the dependencies of a class into the constructor of that class. This makes it easy to change the dependencies of a class without having to modify the class itself.</p>
<p>Provider uses dependency injection to manage the state of your app. When you create a Provider, you pass the state of your app into the constructor of the Provider. This makes it easy to change the state of your app without having to modify the code that uses the state.</p>
<h2 id="heading-how-to-use-provider"><strong>How to use Provider</strong></h2>
<p>To use Provider, you first need to install the package. You can do this by running the following command in your terminal:</p>
<pre><code class="lang-bash">flutter pub add provider
</code></pre>
<p>Once the package is installed, you can start using it in your app. The following code shows how to create a simple state management solution with Provider:</p>
<pre><code class="lang-dart"><span class="hljs-keyword">import</span> <span class="hljs-string">'package:provider/provider.dart'</span>;

<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">MyApp</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">StatelessWidget</span> </span>{
  <span class="hljs-meta">@override</span>
  Widget build(BuildContext context) {
    <span class="hljs-keyword">return</span> Provider(
      builder: (context, child) {
        <span class="hljs-keyword">return</span> MaterialApp(
          home: MyHomePage(),
        );
      },
    );
  }
}

<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">MyHomePage</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">StatelessWidget</span> </span>{
  <span class="hljs-meta">@override</span>
  Widget build(BuildContext context) {
    <span class="hljs-comment">// Get the current count from the provider</span>
    <span class="hljs-built_in">int</span> count = Provider.of&lt;Counter&gt;(context).count;

    <span class="hljs-keyword">return</span> Scaffold(
      appBar: AppBar(
        title: Text(<span class="hljs-string">'My App'</span>),
      ),
      body: Center(
        child: Text(<span class="hljs-string">'The count is <span class="hljs-subst">$count</span>'</span>),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: () {
          <span class="hljs-comment">// Increment the count</span>
          Provider.of&lt;Counter&gt;(context).increment();
        },
        child: Icon(Icons.add),
      ),
    );
  }
}

<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Counter</span> <span class="hljs-title">with</span> <span class="hljs-title">ChangeNotifier</span> </span>{
  <span class="hljs-built_in">int</span> count = <span class="hljs-number">0</span>;

  <span class="hljs-keyword">void</span> increment() {
    count++;
    notifyListeners();
  }
}
</code></pre>
<ul>
<li><p>In this code, we create a <code>Counter</code> class that extends the <code>ChangeNotifier</code> class. The <code>ChangeNotifier</code> class provides a mechanism for notifying listeners when the state of the object changes.</p>
</li>
<li><p>We then create a <code>MyHomePage</code> widget that uses Provider to get the current count from the <code>Counter</code> object. When the user clicks the floating action button, the count is incremented and the <code>Counter</code> object is notified.</p>
</li>
</ul>
<h2 id="heading-conclusion"><strong>Conclusion</strong></h2>
<p>Provider is a powerful state management library that can make it easy to manage the state of your Flutter apps.</p>
<p>With Provider, you can create a single source of truth for your app's state, and you can access the state from any widget in your app.</p>
<p>Provider also provides a number of features that make it easy to manage state, such as change notification,inheritance, and lazy loading.</p>
<p>If you are looking for a state management library for your Flutter app, I encourage you to check out Provider.</p>
]]></content:encoded></item><item><title><![CDATA[Hashing in Data Structures: Understanding the Key Concepts and Applications]]></title><description><![CDATA[Hashing is a fundamental concept in computer science and is used in various applications, from data storage to cryptography. In this blog, we will explore the basics of hashing, its advantages, and the different types of hash functions. Additionally,...]]></description><link>https://blog.ratishfolio.com/hashing-in-data-structures-understanding-the-key-concepts-and-applications</link><guid isPermaLink="true">https://blog.ratishfolio.com/hashing-in-data-structures-understanding-the-key-concepts-and-applications</guid><category><![CDATA[datastructure]]></category><category><![CDATA[Hashing]]></category><category><![CDATA[Security]]></category><category><![CDATA[development]]></category><category><![CDATA[Programming Blogs]]></category><dc:creator><![CDATA[Ratish Jain]]></dc:creator><pubDate>Mon, 01 May 2023 04:00:39 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1682759052605/42387268-d5ef-445d-8c39-d61900ee1a63.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Hashing is a fundamental concept in computer science and is used in various applications, from data storage to cryptography. In this blog, we will explore the basics of hashing, its advantages, and the different types of hash functions. Additionally, we will discuss some of the popular applications of hashing.</p>
<p>What is Hashing? Hashing is the process of mapping data of arbitrary size to a fixed-size output. This fixed-size output is called a hash or a message digest. The hash function takes input data and produces a fixed-length output, which is typically a unique representation of the input data. The resulting hash is often used for indexing, searching, and data integrity verification.</p>
<p>Advantages of Hashing: Hashing provides several advantages, such as:</p>
<ol>
<li><p>Data Integrity Verification: Hashing is widely used for verifying data integrity. By comparing the hash value of the original data with the hash value of the received data, one can determine whether the data has been modified or corrupted during transmission.</p>
</li>
<li><p>Fast Retrieval: Hashing allows for quick retrieval of data from large datasets. Instead of searching through the entire dataset, hash functions can be used to index data and retrieve it quickly.</p>
</li>
<li><p>Security: Hashing is an essential tool in cryptography. It is used to store passwords securely and to authenticate data.</p>
</li>
</ol>
<p>Types of Hash Functions: There are various types of hash functions, including:</p>
<ol>
<li><p>Cryptographic Hash Functions: Cryptographic hash functions are designed to be secure and are commonly used in cryptography. Examples of cryptographic hash functions include SHA-256 and SHA-512.</p>
</li>
<li><p>Non-Cryptographic Hash Functions: Non-cryptographic hash functions are used for indexing, searching, and data integrity verification. Examples of non-cryptographic hash functions include MurmurHash and FNV.</p>
</li>
</ol>
<p>Applications of Hashing: Hashing has several applications, including:</p>
<ol>
<li><p>Password Storage: Hashing is used to store passwords securely. When a user enters a password, it is hashed and compared with the stored hash value. If the values match, the user is granted access.</p>
</li>
<li><p>Data Integrity Verification: Hashing is used to verify the integrity of data during transmission. The hash value of the original data is compared with the hash value of the received data to determine whether the data has been modified or corrupted.</p>
</li>
<li><p>Indexing and Searching: Hashing is used to index and search large datasets quickly. Hash functions can be used to map data to a fixed-size index, allowing for fast retrieval of data.</p>
</li>
</ol>
<p>In Hashing Hash Tables are used but many times collision occurs when new data is being added to the Hash Table to avoid this there are many collision resolution techniques like linear probing, separate chaining and quadratic probing below there is an in-depth explanation of these techniques -</p>
<ol>
<li><p>Linear Probing: Linear probing is a simple method for resolving collisions. When a collision occurs, the algorithm checks the next available slot in the table and places the item there. This process continues until an empty slot is found. The main disadvantage of linear probing is that it can result in clustering, where items are stored in adjacent slots, making it more difficult to search the table efficiently.</p>
<p> <img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1682756439665/c31eec5d-95c1-476a-882b-03fdb94a1896.jpeg" alt class="image--center mx-auto" /></p>
</li>
<li><p>Separate Chaining: Separate chaining is a technique where each slot in the hash table contains a linked list of items that hash to that location. When a collision occurs, the item is added to the linked list. This method avoids clustering and is more efficient for large datasets. However, it requires additional memory to store the linked lists and may result in slower search times if the lists become too long.</p>
<p> <img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1682751787845/0cd4dba9-16e2-427a-bf24-65f189cf55a1.png" alt class="image--center mx-auto" /></p>
</li>
</ol>
<p>Quadratic Probing: Quadratic probing is a variation of linear probing that tries to distribute items more evenly across the table. Instead of checking the next available slot, the algorithm searches for the next available slot using a quadratic function. This method reduces clustering and provides better search efficiency than linear probing. However, it may result in longer search times for some inputs.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1682756944474/7ae20656-36eb-4c86-b160-db11ca328f21.png" alt class="image--center mx-auto" /></p>
<p>In conclusion, hashing is an essential concept in computer science, providing several benefits such as data integrity verification, fast retrieval, and security. Understanding the different types of hash functions and their applications can help developers make informed decisions when implementing hashing in their applications.</p>
]]></content:encoded></item><item><title><![CDATA[A  Developer's Guide to Integrating
ChatGPT and DALL-E  APIs in Your Flutter App 🚀]]></title><description><![CDATA[Open AI recently released ChatGPT and DALL-E which are AI-powered tools helping you to boost your productivity and do work efficiently without any hassle. They are natural language processing technology that enables the automation of chat conversatio...]]></description><link>https://blog.ratishfolio.com/a-developers-guide-to-integrating-chatgpt-and-dall-e-apis-in-your-flutter-app</link><guid isPermaLink="true">https://blog.ratishfolio.com/a-developers-guide-to-integrating-chatgpt-and-dall-e-apis-in-your-flutter-app</guid><category><![CDATA[chatgptguide]]></category><category><![CDATA[Flutter]]></category><category><![CDATA[APIs]]></category><category><![CDATA[Machine Learning]]></category><category><![CDATA[Artificial Intelligence]]></category><dc:creator><![CDATA[Ratish Jain]]></dc:creator><pubDate>Mon, 10 Apr 2023 04:00:39 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1680948294382/9e93d805-0f7a-4fdc-a3bb-210726360516.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Open AI recently released ChatGPT and DALL-E which are AI-powered tools helping you to boost your productivity and do work efficiently without any hassle. They are natural language processing technology that enables the automation of chat conversations and generating images based on the prompts the user provides.</p>
<p>ChatGPT API helps developers to integrate ChatGPT features into their projects which can be either chat-based or voice assistant ie - using your commands as input and the API will generate a response based on that command.</p>
<p>DALL-E API is used for image generation based on user prompts</p>
<h2 id="heading-pre-requisites-before-integration">Pre-requisites before integration</h2>
<ul>
<li><p>Create an account on Open AI by going to their documentation page</p>
</li>
<li><p>Generate your <strong>API Key</strong> which will be used to make an API call to the ChatGPT API and DALL-E API by clicking on <strong>Create new secret key</strong></p>
</li>
</ul>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1680942560910/a812c187-5c6f-4234-9fc8-01ee4abfe156.png" alt class="image--center mx-auto" /></p>
<ul>
<li>Make sure to store the API Key somewhere like the .env file as you will only be able to see it on the website only once.</li>
</ul>
<h2 id="heading-integrate-apis-in-your-flutter-project">Integrate APIs in your Flutter Project</h2>
<ul>
<li><p>Create a dart file which will contain all the functions regarding the API calls to</p>
<p>  ChatGPT and DALL-E and name it for example <strong>openai_service.dart</strong></p>
</li>
<li><p>We are gonna use the <strong>HTTP</strong> package for the API call but you can also use the dart_openai package for the API calls(<a target="_blank" href="https://pub.dev/packages/dart_openai">dart_openai</a>)</p>
</li>
<li><p>Now we are gonna use chat API(chat completions) which supports two open AI models: <strong>GPT-4</strong> and <strong>GPT-3.5-turbo</strong></p>
</li>
<li><p>Now as we are also using DALL-E API together we need some way to distinguish whether the user is asking to generate an image or not for that we will be using an async function named as isArtPrompt() and use Chat completions for it.</p>
<p>  This function returns a yes or no based on which API call is made either to ChatGPT API or DALL-E API.</p>
<p>  <img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1680944704997/c1186abc-f624-42a7-b170-b7a170d5d871.png" alt class="image--center mx-auto" /></p>
</li>
<li><pre><code class="lang-dart">  Future&lt;<span class="hljs-built_in">String</span>&gt; isArtPrompt(<span class="hljs-built_in">String</span> prompt) <span class="hljs-keyword">async</span> {
      <span class="hljs-keyword">try</span> {
        <span class="hljs-keyword">final</span> res = <span class="hljs-keyword">await</span> http.post(
            <span class="hljs-built_in">Uri</span>.parse(<span class="hljs-string">"https://api.openai.com/v1/chat/completions"</span>),
            headers: {
              <span class="hljs-string">'Content-Type'</span>: <span class="hljs-string">'application/json'</span>,
              <span class="hljs-string">'Authorization'</span>: <span class="hljs-string">'Bearer <span class="hljs-subst">$OpenAIApiKey</span>'</span>
            },
            body: jsonEncode({
              <span class="hljs-string">'model'</span>: <span class="hljs-string">"gpt-3.5-turbo"</span>,
              <span class="hljs-string">'messages'</span>: [
                {
                  <span class="hljs-string">"role"</span>: <span class="hljs-string">"user"</span>,
                  <span class="hljs-string">"content"</span>:
                      <span class="hljs-string">"Does this message want to generate an AI picture, image, art or anything similar? <span class="hljs-subst">$prompt</span> . Simply answer with a yes or no."</span>
  <span class="hljs-comment">//this content asks chatGPT and retrieves answer in yes or no </span>
                }
              ],
            }));
        <span class="hljs-built_in">print</span>(res.body);
        <span class="hljs-keyword">if</span> (res.statusCode == <span class="hljs-number">200</span>) {
          <span class="hljs-built_in">String</span> content =
              jsonDecode(res.body)[<span class="hljs-string">'choices'</span>][<span class="hljs-number">0</span>][<span class="hljs-string">'message'</span>][<span class="hljs-string">"content"</span>];
          content = content.trim(); <span class="hljs-comment">//trimming all space from output</span>
          <span class="hljs-keyword">switch</span> (content) {
            <span class="hljs-keyword">case</span> <span class="hljs-string">'yes'</span>:
            <span class="hljs-keyword">case</span> <span class="hljs-string">'Yes'</span>:
            <span class="hljs-keyword">case</span> <span class="hljs-string">'Yes.'</span>:
            <span class="hljs-keyword">case</span> <span class="hljs-string">'yes.'</span>:
                 <span class="hljs-keyword">final</span> res = <span class="hljs-keyword">await</span> dallEAPI(prompt); 
                 <span class="hljs-comment">// dalle api call if yes</span>
              <span class="hljs-keyword">return</span> res;
            <span class="hljs-keyword">default</span>:
              <span class="hljs-keyword">final</span> res = <span class="hljs-keyword">await</span> chatGPTAPI(prompt);
              <span class="hljs-comment">// ChatGPT api call if no</span>
              <span class="hljs-keyword">return</span> res;
          }
        }
        <span class="hljs-keyword">return</span> <span class="hljs-string">"An internal error!!"</span>;
      } <span class="hljs-keyword">catch</span> (e) {
        <span class="hljs-keyword">return</span> e.toString();
      }
    }
</code></pre>
<p>  Now the functions chatGPT API and DALL-E are as follows</p>
</li>
<li><pre><code class="lang-dart">  <span class="hljs-keyword">final</span> <span class="hljs-built_in">List</span>&lt;<span class="hljs-built_in">Map</span>&lt;<span class="hljs-built_in">String</span>, <span class="hljs-built_in">String</span>&gt;&gt; messages = [];
  <span class="hljs-comment">// Chat Completetion API call</span>
  Future&lt;<span class="hljs-built_in">String</span>&gt; chatGPTAPI(<span class="hljs-built_in">String</span> prompt) <span class="hljs-keyword">async</span> {
      messages.add({<span class="hljs-string">'role'</span>: <span class="hljs-string">'user'</span>, <span class="hljs-string">'content'</span>: prompt});
      <span class="hljs-keyword">try</span> {
        <span class="hljs-keyword">final</span> res = <span class="hljs-keyword">await</span> http.post(
            <span class="hljs-built_in">Uri</span>.parse(<span class="hljs-string">"https://api.openai.com/v1/chat/completions"</span>),
            headers: {
              <span class="hljs-string">'Content-Type'</span>: <span class="hljs-string">'application/json'</span>,
              <span class="hljs-string">'Authorization'</span>: <span class="hljs-string">'Bearer <span class="hljs-subst">$OpenAIApiKey</span>'</span>
            },
            body: jsonEncode({
              <span class="hljs-string">'model'</span>: <span class="hljs-string">"gpt-3.5-turbo"</span>,
              <span class="hljs-string">'messages'</span>: messages,
            }));
        <span class="hljs-built_in">print</span>(res.body);
        <span class="hljs-keyword">if</span> (res.statusCode == <span class="hljs-number">200</span>) {
          <span class="hljs-built_in">String</span> content =
              jsonDecode(res.body)[<span class="hljs-string">'choices'</span>][<span class="hljs-number">0</span>][<span class="hljs-string">'message'</span>][<span class="hljs-string">"content"</span>];
          content = content.trim();
          messages.add({<span class="hljs-string">'role'</span>: <span class="hljs-string">'assistant'</span>, <span class="hljs-string">'content'</span>: content});
          <span class="hljs-keyword">return</span> content;
        }
        <span class="hljs-keyword">return</span> <span class="hljs-string">"An internal error!!"</span>;
      } <span class="hljs-keyword">catch</span> (e) {
        <span class="hljs-keyword">return</span> e.toString();
      }
    }

  <span class="hljs-comment">// image generation API call</span>
  Future&lt;<span class="hljs-built_in">String</span>&gt; dallEAPI(<span class="hljs-built_in">String</span> prompt) <span class="hljs-keyword">async</span> {
      messages.add({<span class="hljs-string">'role'</span>: <span class="hljs-string">'user'</span>, <span class="hljs-string">'content'</span>: prompt});
      <span class="hljs-keyword">try</span> {
        <span class="hljs-keyword">final</span> res = <span class="hljs-keyword">await</span> http.post(
            <span class="hljs-built_in">Uri</span>.parse(<span class="hljs-string">"https://api.openai.com/v1/images/generations"</span>),
            headers: {
              <span class="hljs-string">'Content-Type'</span>: <span class="hljs-string">'application/json'</span>,
              <span class="hljs-string">'Authorization'</span>: <span class="hljs-string">'Bearer <span class="hljs-subst">$OpenAIApiKey</span>'</span>
            },
            body: jsonEncode({
              <span class="hljs-string">'prompt'</span>: prompt,
              <span class="hljs-string">'n'</span>: <span class="hljs-number">1</span>, <span class="hljs-comment">// number of images to be generated</span>
            }));
        <span class="hljs-built_in">print</span>(res.body);
        <span class="hljs-keyword">if</span> (res.statusCode == <span class="hljs-number">200</span>) {
          <span class="hljs-built_in">String</span> imgUrl = jsonDecode(res.body)[<span class="hljs-string">'data'</span>][<span class="hljs-number">0</span>][<span class="hljs-string">'url'</span>];
          imgUrl = imgUrl.trim();
          messages.add({<span class="hljs-string">'role'</span>: <span class="hljs-string">'assistant'</span>, <span class="hljs-string">'content'</span>: imgUrl});
          <span class="hljs-keyword">return</span> imgUrl;
        }
        <span class="hljs-keyword">return</span> <span class="hljs-string">"An internal error!!"</span>;
      } <span class="hljs-keyword">catch</span> (e) {
        <span class="hljs-keyword">return</span> e.toString();
      }
    }
</code></pre>
<p>  Thats it !! Now you can use the isArtPrompt() function and pass it your desired prompt, the function will call either of the APIs and give a response which you can use in your Flutter app to showcase the user.</p>
</li>
</ul>
<p>You can check out my Voice assistant Flutter App using ChatGPT API and DALL-E API for text response and image generation based on user prompts(<a target="_blank" href="https://github.com/ratishjain12/ChatGPT-DALLE-FLUTTER-APP">Voice Assistant App</a>).</p>
<p>Make sure to follow me and subscribe to this blog for more tech blogs like this on daily basis, P.S. - your support is much appreciated!!!</p>
]]></content:encoded></item><item><title><![CDATA[What is CRUD functionality? Learn All Crud Operations.]]></title><description><![CDATA[CRUD (Create, Read, Update, Delete) functionality is an essential feature in any application that deals with data. It is a set of operations that allow users to interact with data stored in a database. In this blog, we will explore the importance of ...]]></description><link>https://blog.ratishfolio.com/what-is-crud-functionality-learn-all-crud-operations</link><guid isPermaLink="true">https://blog.ratishfolio.com/what-is-crud-functionality-learn-all-crud-operations</guid><category><![CDATA[Developer]]></category><category><![CDATA[Blogging]]></category><category><![CDATA[coding]]></category><category><![CDATA[WeMakeDevs]]></category><category><![CDATA[Programming Blogs]]></category><dc:creator><![CDATA[Ratish Jain]]></dc:creator><pubDate>Mon, 20 Mar 2023 11:30:38 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1679201875081/62ea6361-3ae3-4658-9797-8a3df4aecfff.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>CRUD (Create, Read, Update, Delete) functionality is an essential feature in any application that deals with data. It is a set of operations that allow users to interact with data stored in a database. In this blog, we will explore the importance of CRUD functionality and how it works.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1679066731911/68d95908-9bd5-42b3-9e44-784e6057ab41.jpeg" alt class="image--center mx-auto" /></p>
<p><strong>Create:</strong> The Create operation allows users to create new data entries in the database. This can be done using a web form or an API endpoint. When the user submits the data, it is sent to the server and stored in the database. The data is validated to ensure that it meets the required criteria before it is stored in the database.</p>
<p><strong>Read:</strong> The Read operation allows users to retrieve data from the database. This can be done by querying the database using specific criteria. For example, a user might search for all the products in a specific category or all the users who have signed up in the last week. The data is returned in a format that can be easily understood by the user, such as a table or a list.</p>
<p><strong>Update:</strong> The Update operation allows users to modify existing data in the database. This can be done using a web form or an API endpoint. When the user submits the updated data, it is sent to the server and stored in the database. The data is validated to ensure that it meets the required criteria before it is updated in the database.</p>
<p><strong>Delete:</strong> The Delete operation allows users to remove data from the database. This can be done using a web form or an API endpoint. When the user confirms the deletion, the data is removed from the database. It is important to note that this operation should be used with caution, as it can result in the loss of important data.</p>
<p>Suppose, you are on Instagram and you create a post, this is called create functionality and now in that post after uploading you are trying to change the caption of the post, this is update functionality similarly you delete a post triggering delete functionality and while you are searching for an account to follow you are triggering read functionality as you are trying to search the account which Instagram will provide by reading from its database.</p>
<p>The above example, tells you that CRUD functionality is most crucial for big tech companies to maintain their product.</p>
<p>The importance of CRUD functionality: CRUD functionality is important for several reasons. First, it allows users to interact with data simply and intuitively. This makes it easier for users to manage their data and reduces the likelihood of errors.</p>
<p>Second, CRUD functionality ensures that data is consistent and accurate. When users create, read, update, and delete data using a standardized set of operations, the data remains consistent across the entire system.</p>
<p>Finally, CRUD functionality helps to ensure the security of the system. By controlling access to the Create, Read, Update, and Delete operations, the system can prevent unauthorized access to sensitive data.</p>
<p>In conclusion, CRUD functionality is an essential feature of any application that deals with data. It provides users with a simple and intuitive way to manage their data, ensures the consistency and accuracy of the data, and helps to ensure the security of the system.</p>
<h2 id="heading-to-learn-more-about-what-is-an-api-checkout-my-blog">To Learn More about what is an API checkout my Blog</h2>
<div class="embed-wrapper"><div class="embed-loading"><div class="loadingRow"></div><div class="loadingRow"></div></div><a class="embed-card" href="https://devcon.hashnode.dev/what-is-an-api-how-does-it-work-and-why-it-is-very-important-for-businesses-around-the-world">https://devcon.hashnode.dev/what-is-an-api-how-does-it-work-and-why-it-is-very-important-for-businesses-around-the-world</a></div>
]]></content:encoded></item><item><title><![CDATA[What is an API? How does it work and why it is very important for Businesses around the world]]></title><description><![CDATA[An API is an Application Programming Interface which is a set of tools that allow developers to create software and applications. API provides many facilities from providing access to data or services to providing an interface for developers to creat...]]></description><link>https://blog.ratishfolio.com/what-is-an-api-how-does-it-work-and-why-it-is-very-important-for-businesses-around-the-world</link><guid isPermaLink="true">https://blog.ratishfolio.com/what-is-an-api-how-does-it-work-and-why-it-is-very-important-for-businesses-around-the-world</guid><category><![CDATA[WeMakeDevs]]></category><category><![CDATA[APIs]]></category><category><![CDATA[Blogging]]></category><category><![CDATA[Developer]]></category><category><![CDATA[coding]]></category><dc:creator><![CDATA[Ratish Jain]]></dc:creator><pubDate>Sat, 04 Mar 2023 11:30:39 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1677856959624/d693da24-a801-4ec8-8078-eeb7251f043a.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>An API is an Application Programming Interface which is a set of tools that allow developers to create software and applications. API provides many facilities from providing access to data or services to providing an interface for developers to create applications that interact with other software.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1677647843051/b690396d-f559-4e22-9e90-c25248db55e9.png" alt class="image--center mx-auto" /></p>
<p>APIs are an essential part of software development and they are becoming highly important for businesses around the world as they are moving their operations to the cloud. APIs allow applications to access data and interact with other applications seamlessly and efficiently.</p>
<p>For example, suppose you are building an app which allows users to search for weather conditions across countries and states for this you can use a Weather API which has all the data and integrates it into your application making it very efficient and easy to build. Moreover, you can also add more features to your app by using multiple APIs.</p>
<p>Without APIs, most of your favourite software wouldn't exist today such as Google Maps API lets you integrate Google Maps on your mobile which is allowing many tech startups like Ola, Uber etc. to provide location service.</p>
<h3 id="heading-why-should-you-use-apis-in-your-application">Why should you use APIs in your application?</h3>
<ul>
<li><p>It extends application capabilities.</p>
</li>
<li><p>Allows developers to reuse certain application logic.</p>
</li>
<li><p>APIs are platform-independent, they deliver data without being affected by the requesting platform.</p>
</li>
<li><p>Enables the app to access outside resources.</p>
</li>
</ul>
<h3 id="heading-so-how-does-an-api-work">So How Does an API Work?</h3>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1677676738338/de074208-3736-40e7-8e5b-c8328f991b14.png" alt /></p>
<p>Imagine you are trying to order an item from an online e-commerce store now when you click on buy item your request gets transferred to the backend web server of the e-commerce store via an API request.</p>
<p>Now, the backend server will respond to the API request and pass on your order request to the delivery partner and the delivery partner will deliver the requested item to you.</p>
<p>This process of sending a request is called an API request and the response to the API request is called an API response.</p>
<p>So API helps in providing a secured layer between applications and the data they access, protecting sensitive information from unauthorized access.</p>
<h2 id="heading-types-of-apis">Types of APIs</h2>
<ul>
<li><p><strong>Open/Public APIs</strong> -</p>
<p>  These APIs are available to everyone as a result, open APIs typically have relatively low authentication and authorization measures and are often restricted in the assets they share. These are either free to access or have a subscription fee.</p>
</li>
<li><p><strong>Partner APIs</strong> -</p>
<p>  Partner APIs are shared externally, but only among those with a business relationship with the API company. Access is limited to authorized clients with official licenses</p>
</li>
<li><p><strong>Internal APIs</strong> -</p>
<p>  internal APIs (also called private APIs) are not intended for use by third parties. Internal APIs are only made available for use inside a company and are meant to streamline data transfers between teams and systems.</p>
</li>
<li><p><strong>Composite APIs</strong> -</p>
<p>  Composite APIs combine multiple APIs allowing developers to bundle calls or requests and receive one unified response from different servers.</p>
</li>
</ul>
<h3 id="heading-10-apis-you-can-use-in-your-applications">10 APIs you can use in your Applications -</h3>
<ul>
<li><p>Google Maps API (<a target="_blank" href="https://mapsplatform.google.com/maps-products/#embed">Checkout</a>)</p>
</li>
<li><p>Omdb API (<a target="_blank" href="https://www.omdbapi.com/">Checkout</a>)</p>
</li>
<li><p>Open Weather Map API (<a target="_blank" href="https://openweathermap.org/">Checkout</a>)</p>
</li>
<li><p>Spotify API (<a target="_blank" href="https://developer.spotify.com/documentation/web-api/">Checkout</a>)</p>
</li>
<li><p>Coinbase API (<a target="_blank" href="https://help.coinbase.com/en/cloud/api">Checkout</a>)</p>
</li>
<li><p>Fake Store API (Checkout)</p>
</li>
<li><p>Novu API (<a target="_blank" href="https://docs.novu.co/api/overview/">Checkout</a>)</p>
</li>
<li><p>Zenserp API (<a target="_blank" href="https://zenserp.com/">Checkout</a>)</p>
</li>
<li><p>Number verification API (<a target="_blank" href="https://numverify.com/?utm_source=Sitepoint&amp;utm_medium=Leads%20Acquisition&amp;utm_content=articlenumverify">Checkout</a>)</p>
</li>
<li><p>Stripe API (<a target="_blank" href="https://stripe.com/docs/api">Checkout</a>)</p>
</li>
</ul>
]]></content:encoded></item><item><title><![CDATA[Learn To Think Recursively and Solve Recursion Problems in an Interview in 4 Steps]]></title><description><![CDATA[What is Recursion?

The process in which a function calls itself either directly or indirectly is called recursion and the corresponding function is called a recursive function with recursion you can solve some complex problems quite easily examples ...]]></description><link>https://blog.ratishfolio.com/learn-to-think-recursively-and-solve-recursion-problems-in-an-interview-in-4-steps</link><guid isPermaLink="true">https://blog.ratishfolio.com/learn-to-think-recursively-and-solve-recursion-problems-in-an-interview-in-4-steps</guid><category><![CDATA[WeMakeDevs]]></category><category><![CDATA[Recursion]]></category><category><![CDATA[DSA]]></category><category><![CDATA[Programming Blogs]]></category><category><![CDATA[coding]]></category><dc:creator><![CDATA[Ratish Jain]]></dc:creator><pubDate>Sun, 05 Feb 2023 18:01:59 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1675620028223/901a09ec-f307-4781-90d9-8b3caee0dea7.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h2 id="heading-what-is-recursion">What is Recursion?</h2>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1675619578628/d00e72bb-01e5-42f5-8d3d-f553862f36a4.png" alt class="image--center mx-auto" /></p>
<p>The process in which a function calls itself either directly or indirectly is called recursion and the corresponding function is called a recursive function with recursion you can solve some complex problems quite easily examples of such problems are tower of hanoi, tree traversals, DFS of graph etc.</p>
<p>properties of recursion -</p>
<ul>
<li><p>performing the same operation multiple times with different inputs</p>
</li>
<li><p>At every step, the input is reduced to make the problem smaller</p>
</li>
<li><p>A base condition is required to stop the recursion process otherwise infinite loop will occur</p>
</li>
</ul>
<p>Many people when try to solve a problem using recursion they try to trace each recursive call to determine what each function call is doing but this is a trap of endless confusion to avoid this trap you need not need to know what each function call is doing rather you just need to pick a subproblem and believe that your function will solve the rest of the problem, you need to take a leap of faith and believe in your function.</p>
<h2 id="heading-steps-to-approach-a-problem-and-think-recursively">Steps to approach a problem and think recursively</h2>
<ul>
<li><p>Step 1) Know what your function is supposed to do.</p>
</li>
<li><p>Step 2) Determine a subproblem from the main problem.</p>
</li>
<li><p>Step 3) Find out the answer to the subproblem and use it to solve the main problem.</p>
</li>
<li><p>Step 4) Last step is to determine the base condition of the problem</p>
</li>
</ul>
<p>Let's take a simple problem such as finding the sum of 1 to n numbers and follow the 4 steps mentioned above to solve the problem.</p>
<h3 id="heading-know-what-your-function-is-supposed-to-do">Know what your function is supposed to do</h3>
<p>This is the most basic and general step but a very important one. Now in the question above, we know that we need to calculate the sum of numbers from 1 to n</p>
<p>So our function needs to take a value n and return the sum from 1 up to n so our inputs of the function cant exceed n.</p>
<p>let's say the function is sumTo().</p>
<pre><code class="lang-cpp"><span class="hljs-function"><span class="hljs-keyword">int</span> <span class="hljs-title">sumTo</span><span class="hljs-params">(<span class="hljs-keyword">int</span> n)</span></span>{

}
</code></pre>
<h3 id="heading-determine-the-subproblem-from-the-main-problem">Determine the subproblem from the main problem</h3>
<p>A subproblem is any problem that is smaller than the main problem and it is important to find the appropriate subproblem</p>
<p>In the above case, the subproblem can be solving the sum of all numbers less than n.</p>
<p>so the appropriate subproblem will be solving for the sum of (n-1) numbers.</p>
<h3 id="heading-finding-out-the-answer-to-the-subproblem-and-using-it-to-solve-the-main-problem">Finding out the answer to the subproblem and using it to solve the main problem</h3>
<p>The solution for the sum of n-1 numbers will be</p>
<p>sumToSubProblem = 1+2+3 ...... + n-1</p>
<p>Now to find the solution to the main problem we just need to add the nth number -</p>
<p>mainProblem = subProblem + n</p>
<p>So the code will be</p>
<pre><code class="lang-cpp"><span class="hljs-function"><span class="hljs-keyword">int</span> <span class="hljs-title">sumTo</span><span class="hljs-params">(<span class="hljs-keyword">int</span> n)</span></span>{
     <span class="hljs-keyword">int</span> subProblem = sumTo(n<span class="hljs-number">-1</span>);
     <span class="hljs-keyword">return</span> subProblem + n;
}
</code></pre>
<h3 id="heading-the-last-step-is-to-find-the-base-case-for-the-recursion-process">The last step is to find the base case for the recursion process -</h3>
<p>A base case condition is any condition that stops the recursion process and is necessary to avoid the infinite loop.</p>
<p>So to find the base condition we need to find at what input the function becomes irrelevant in the above case we know if n = 0 the function will become irrelevant as 0+0 will give 0 only.</p>
<p>so on applying this base condition we will have a complete solution to the main problem</p>
<pre><code class="lang-cpp"><span class="hljs-function"><span class="hljs-keyword">int</span> <span class="hljs-title">sumTo</span><span class="hljs-params">(n<span class="hljs-number">-1</span>)</span></span>{
    <span class="hljs-keyword">if</span>(n == <span class="hljs-number">0</span>) <span class="hljs-keyword">return</span> <span class="hljs-number">0</span>;
    <span class="hljs-keyword">int</span> subProblem = sumTo(n<span class="hljs-number">-1</span>);
    <span class="hljs-keyword">return</span> subProblem + n;
}
</code></pre>
<h2 id="heading-more-examples">More examples -</h2>
<p>Reversing a string using recursion</p>
<p>As per the first step, we know that we need a function that takes a string as input and return a reversed string.</p>
<pre><code class="lang-cpp"><span class="hljs-function"><span class="hljs-built_in">string</span> <span class="hljs-title">reverseString</span><span class="hljs-params">(<span class="hljs-built_in">string</span> s)</span></span>{

}
</code></pre>
<p>Now we need to determine a subproblem which in this case will be leaving the first character and solving for the rest of the characters.</p>
<p>ie - string s = "hello";</p>
<p>so the subproblem will be reversing "ello" to "olle" and adding the first character 'h' in the end.</p>
<pre><code class="lang-cpp"><span class="hljs-function"><span class="hljs-built_in">string</span> <span class="hljs-title">reverseString</span><span class="hljs-params">(<span class="hljs-built_in">string</span> s)</span></span>{
     <span class="hljs-built_in">string</span> substring = s.substr(<span class="hljs-number">1</span>,s.length());
     <span class="hljs-built_in">string</span> reversedSubProblem = reverseString(substring);
     <span class="hljs-keyword">return</span> reversedSubProblem + s[<span class="hljs-number">0</span>];
}
</code></pre>
<p>Now the last step will be finding the base case condition which in this case will be if string s become empty string because that is the most basic string a user can provide.</p>
<p>so,</p>
<pre><code class="lang-cpp"><span class="hljs-function"><span class="hljs-built_in">string</span> <span class="hljs-title">reverseString</span><span class="hljs-params">(<span class="hljs-built_in">string</span> s)</span></span>{
     <span class="hljs-keyword">if</span>(s == <span class="hljs-string">""</span>) <span class="hljs-keyword">return</span> <span class="hljs-string">""</span>;
     <span class="hljs-built_in">string</span> substring = s.substr(<span class="hljs-number">1</span>,s.length());
     <span class="hljs-built_in">string</span> reversedSubProblem = reverseString(substring);
     <span class="hljs-keyword">return</span> reversedSubProblem + s[<span class="hljs-number">0</span>];
}
</code></pre>
<p>Similarly to find the nth Fibonacci number the subproblems will be finding the Fibonacci terms (n-1) and (n-2) and the addition of these two terms will give the solution for the nth Fibonacci term.</p>
<p>and the base condition, in this case, will be for n = 0 and n = 1 as there are no two previous terms for these values</p>
<pre><code class="lang-cpp"><span class="hljs-function"><span class="hljs-keyword">int</span> <span class="hljs-title">fibonacci</span><span class="hljs-params">(<span class="hljs-keyword">int</span> n)</span></span>{
    <span class="hljs-keyword">if</span>(n == <span class="hljs-number">0</span>) <span class="hljs-keyword">return</span> <span class="hljs-number">0</span>;
    <span class="hljs-keyword">if</span>(n == <span class="hljs-number">1</span>) <span class="hljs-keyword">return</span> <span class="hljs-number">1</span>;
    <span class="hljs-keyword">int</span> term1 = fibonacci(n<span class="hljs-number">-1</span>);
    <span class="hljs-keyword">int</span> term2 = fibonacci(n<span class="hljs-number">-2</span>);
    <span class="hljs-keyword">return</span> term1+term2;
}
</code></pre>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1675619398478/cbb6ceb4-c237-4329-8fd2-186b695eb6f5.jpeg" alt class="image--center mx-auto" /></p>
]]></content:encoded></item><item><title><![CDATA[Learn how to use Git and Github to collaborate on a project or contribute on
a open-source project]]></title><description><![CDATA[Git is a distributed version control system built to handle small and very large projects easily with speed and efficiency as it allows many users to work on the same project without disturbing the main work with the help of branches.

Branches are u...]]></description><link>https://blog.ratishfolio.com/learn-how-to-use-git-and-github-to-collaborate-on-a-project-or-contribute-on-a-open-source-project</link><guid isPermaLink="true">https://blog.ratishfolio.com/learn-how-to-use-git-and-github-to-collaborate-on-a-project-or-contribute-on-a-open-source-project</guid><category><![CDATA[WeMakeDevs]]></category><category><![CDATA[Programming Blogs]]></category><category><![CDATA[Open Source]]></category><category><![CDATA[GitHub]]></category><category><![CDATA[Git]]></category><dc:creator><![CDATA[Ratish Jain]]></dc:creator><pubDate>Mon, 23 Jan 2023 11:30:42 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1674464441806/5647db92-8416-4e0f-8a98-1e420afa5f02.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Git is a distributed version control system built to handle small and very large projects easily with speed and efficiency as it allows many users to work on the same project without disturbing the main work with the help of branches.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1674461711407/18e078f2-dfad-4b78-a2b8-dfc87968558e.png" alt class="image--center mx-auto" /></p>
<p>Branches are used within the development process of the project which involves creating a new feature, and fixing bugs it acts as a copy of your main work but changes in a branch do not reflect on your main work and you can use it for trial and testing and after getting the desired output you can open a pull request to merge the changes on your branch to the main branch ie - update your main branch with the changes.</p>
<h2 id="heading-steps-for-pushing-your-project-to-github">Steps for pushing your project to GitHub-</h2>
<p>First thing first you'll need to create an empty GitHub repository inside where you would put your project files.</p>
<p>After creating the repo you will be displayed the following screen</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1674456751739/873b9a18-ffa4-4995-9a97-9bcd97b39053.png" alt class="image--center mx-auto" /></p>
<ul>
<li><p>The first step is <mark>initialising git</mark> inside your project folder.</p>
</li>
<li><p>The second step is creating a <mark>remote</mark> to your GitHub repo.</p>
</li>
<li><p>The third step is to add your project files in the staging area using the command</p>
<p>  <mark>" git add . "</mark> This will add the project files from your local directory to the staging area.</p>
</li>
<li><p>The fourth step is to commit your changes with a message using the command</p>
<p>  <mark>git commit -m "message"</mark></p>
</li>
<li><p>Create a main branch using the command,</p>
<p>  <mark>git branch -M main</mark> and push your staged files to the main using the command</p>
<p>  <mark>git push -u origin main</mark></p>
</li>
</ul>
<h2 id="heading-collaborate-on-an-existing-github-project-using-branches-and-pull-requests">Collaborate on an existing GitHub project using branches and pull requests</h2>
<p>Now to collaborate on an existing project first you'll need to clone the project on your local directory using the command <mark>git clone project_url</mark></p>
<p>After, it is a great practice to create your branch for modifications, to create a branch use the command <mark>git checkout -b &lt;branch-name&gt;</mark></p>
<p>Now inside your branch, you can add your feature and after finishing the feature you can add the changes to the staging area using the command</p>
<p><mark>git add .</mark></p>
<p>After adding, commit the changes with an appropriate message describing the feature you have changed or updated to do so use the command</p>
<p><mark>git commit -m "message"</mark></p>
<p>The above steps keep on repeating while changes are done.</p>
<p>Now the final step is to push the changes on your branch and open a pull request for the reviewer to review it and merge it with the main to do so following sets of commands are used -</p>
<ul>
<li><p>git push origin &lt;branch name&gt;</p>
</li>
<li><p>Now to open a pull request for your changes do the following steps</p>
</li>
<li><p>Navigate to your <strong>GitHub Repo</strong> and select your branch which consists of your <strong>commits</strong> -</p>
<p>  <img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1674462813196/0e244851-ecc9-497e-83c7-388cf439230c.png" alt /></p>
</li>
<li><p>Above the list of files, click <strong>Pull request</strong>.</p>
<p>  <img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1674462967246/84b8102b-1ad1-43ab-a136-9ce8b62e2a69.png" alt /></p>
</li>
<li><p>Type a <strong>title</strong> and <strong>description</strong> for your pull request.</p>
<p>  <img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1674463027818/e2534e18-391d-4f00-a109-b3964f64c9be.png" alt /></p>
</li>
<li><p>Click on create <strong>pull request button</strong></p>
<p>  <img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1674463116073/421b241c-a3b8-4061-9bf1-f6444ab3f568.png" alt class="image--center mx-auto" /></p>
</li>
</ul>
<p>After creating the pull request the owner of the project will review your code and merge it to the master branch if there are no conflicts.</p>
<p>Note - before doing any changes on your branch you must pull the changes done on the main so that there are no merge conflicts or issues to do so -</p>
<ul>
<li>Before pulling changes switch to your branch using <mark>get checkout &lt;branch-name&gt;</mark></li>
</ul>
<ul>
<li><p>fetch the current origin using <mark>git fetch origin</mark></p>
</li>
<li><p>use <mark>git merge origin/main</mark> to pull changes from the main branch to your local branch another way to do this is to use the command git rebase <mark> origin/main</mark></p>
</li>
<li><p>You can check whether you are behind commits or not using the <mark>git status</mark></p>
</li>
<li><p>Now you can simply pull the changes from the master branch to the local branch.</p>
</li>
</ul>
<p>Congrats!! now you can collaborate easily on projects with your team mates without disturbing the existing work flow and also create your own projects and push it to github to collaborate with others or work on a open source project.</p>
]]></content:encoded></item><item><title><![CDATA[Master  Linked List to Crack Any Interview]]></title><description><![CDATA[A Linked List is a data structure which can change during the execution it consists of a set of nodes linked together each node is divided into two parts one part consists of the data to be stored and the other part stores the address of the next nod...]]></description><link>https://blog.ratishfolio.com/master-linked-list-to-crack-any-interview</link><guid isPermaLink="true">https://blog.ratishfolio.com/master-linked-list-to-crack-any-interview</guid><category><![CDATA[C++]]></category><category><![CDATA[DSA]]></category><category><![CDATA[coding]]></category><category><![CDATA[Programming Blogs]]></category><category><![CDATA[WeMakeDevs]]></category><dc:creator><![CDATA[Ratish Jain]]></dc:creator><pubDate>Sun, 01 Jan 2023 10:10:49 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1672567421394/90ae2bec-1ddc-460e-848c-3c918ca49580.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1672553544599/aab1d42d-c02e-4a26-aaf7-0c317905921e.png" alt class="image--center mx-auto" /></p>
<p>A Linked List is a data structure which can change during the execution it consists of a set of nodes linked together each node is divided into two parts one part consists of the data to be stored and the other part stores the address of the next node.</p>
<p>Some key points for a linked list -</p>
<ul>
<li><p>Successive elements are connected by pointers.</p>
</li>
<li><p>last elements point to NULL in case of singly linked list and doubly linked list</p>
</li>
<li><p>It can grow or shrink in size during the execution of the program.</p>
</li>
<li><p>It does not waste memory space.</p>
</li>
</ul>
<hr />
<h2 id="heading-types-of-linked-lists">Types of Linked Lists -</h2>
<ul>
<li><p>Singly Linked List -</p>
<p>  <img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1672554680930/5e01ed25-4445-4e6a-a5e0-2e3164db4365.png" alt class="image--center mx-auto" /></p>
</li>
<li><p>Doubly Linked List -</p>
<p>  <img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1672554743809/81fe2119-705a-4283-9099-1cf45ca220ac.png" alt class="image--center mx-auto" /></p>
<p>  pointers exist between adjacent nodes in both directions, the list can be traversed either forward or backward, and two pointers are maintained to track known as head and tail.</p>
</li>
</ul>
<ul>
<li><p>Circular Linked List -</p>
<p>  <img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1672554961883/ff54a600-9d23-4eeb-9f51-40d3ada4d4a2.png" alt class="image--center mx-auto" /></p>
<p>  the pointer of the last element in the list points back to the first element.</p>
</li>
</ul>
<hr />
<h2 id="heading-basic-operations-of-linked-lists">Basic operations of Linked Lists -</h2>
<ul>
<li><p>Insert a node in Linked List.</p>
</li>
<li><p>Delete a node in Linked List.</p>
</li>
<li><p>Traverse a Linked List.</p>
</li>
</ul>
<hr />
<h2 id="heading-implementation-of-a-linked-list">Implementation of a Linked List -</h2>
<h3 id="heading-singly-linked-list">Singly Linked List</h3>
<pre><code class="lang-cpp"><span class="hljs-comment">// node structure</span>
<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Node</span> {</span>
<span class="hljs-keyword">public</span>:
  <span class="hljs-keyword">int</span> data; <span class="hljs-comment">// data element</span>
  Node *next;<span class="hljs-comment">//stores address of next element in a list</span>

  Node()
  {
    data = <span class="hljs-number">0</span>;
    next = <span class="hljs-literal">NULL</span>;
  }
  Node(<span class="hljs-keyword">int</span> x)
  {
    <span class="hljs-keyword">this</span>-&gt;data = x;
    <span class="hljs-keyword">this</span>-&gt;next = <span class="hljs-literal">NULL</span>;
  }
}

<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">ll</span> {</span>
Node *head;
<span class="hljs-keyword">public</span>:
  ll(){head = <span class="hljs-literal">NULL</span>}

  Node *insert(<span class="hljs-keyword">int</span> pos, <span class="hljs-keyword">int</span> x) {
    Node *temp = <span class="hljs-keyword">new</span> node(x);
    Node *curr;
    curr = head;
    <span class="hljs-keyword">if</span> (pos == <span class="hljs-number">1</span>) <span class="hljs-comment">// insert at first position</span>
    {
      temp-&gt;next = head;
      head = temp;
      <span class="hljs-keyword">return</span> head;
    }
    <span class="hljs-keyword">for</span> (<span class="hljs-keyword">int</span> i = <span class="hljs-number">1</span>; i &lt;= pos - <span class="hljs-number">2</span> &amp;&amp; curr != <span class="hljs-literal">NULL</span>; i++) 
    <span class="hljs-comment">// insert anywhere</span>
    {
      curr = curr-&gt;next;
    }
    temp-&gt;next = curr-&gt;next;
    curr-&gt;next = temp;
    <span class="hljs-keyword">return</span> head;
  }

  <span class="hljs-function">Node *<span class="hljs-title">del</span><span class="hljs-params">(<span class="hljs-keyword">int</span> pos)</span> </span>{
    Node *curr;
    curr = head;
    <span class="hljs-keyword">if</span> (pos == <span class="hljs-number">1</span>) <span class="hljs-comment">// delete first node</span>
    {
      head = head-&gt;next;
      <span class="hljs-keyword">return</span> head;
    }
    <span class="hljs-keyword">for</span> (<span class="hljs-keyword">int</span> i = <span class="hljs-number">1</span>; i &lt;= pos - <span class="hljs-number">2</span> &amp;&amp; curr != <span class="hljs-literal">NULL</span>; i++)
    <span class="hljs-comment">// delete any node</span>
    {
      curr = curr-&gt;next;
    }
    curr-&gt;next = curr-&gt;next-&gt;next;
    <span class="hljs-keyword">return</span> head;
  }

  <span class="hljs-function"><span class="hljs-keyword">void</span> <span class="hljs-title">display</span><span class="hljs-params">()</span> </span>{ <span class="hljs-comment">// traversing the list</span>
    Node *curr = head;
    <span class="hljs-keyword">while</span> (curr != <span class="hljs-literal">NULL</span>){
      <span class="hljs-built_in">cout</span> &lt;&lt; curr-&gt;data &lt;&lt; <span class="hljs-string">" "</span>;
      curr = curr-&gt;next;
    }
  }
}
</code></pre>
<h3 id="heading-doubly-linked-list">Doubly Linked List -</h3>
<pre><code class="lang-cpp"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Node</span>{</span>
<span class="hljs-keyword">public</span>:
    <span class="hljs-keyword">int</span> data;
    Node *prev;
    Node *next;

    Node()
    {
        prev = <span class="hljs-literal">NULL</span>;
        next = <span class="hljs-literal">NULL</span>;
        data = <span class="hljs-number">0</span>;
    }
    Node(<span class="hljs-keyword">int</span> x)
    {
        data = x;
        prev = <span class="hljs-literal">NULL</span>;
        next = <span class="hljs-literal">NULL</span>;
    }
}

<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">dll</span>{</span>
    Node *head;
<span class="hljs-keyword">public</span>:
    dll() { head = <span class="hljs-literal">NULL</span> }

    <span class="hljs-keyword">void</span> insertFront(<span class="hljs-keyword">int</span> x)
    {
        Node *newNode = <span class="hljs-keyword">new</span> Node(x);
        NewNode-&gt;next = head;
        newNode-&gt;prev = <span class="hljs-literal">NULL</span>;
        <span class="hljs-keyword">if</span> (head != <span class="hljs-literal">NULL</span>){
            head-&gt;prev = newNode;
        }
        head = newNode;
    }

    <span class="hljs-function"><span class="hljs-keyword">void</span> <span class="hljs-title">insertAfter</span><span class="hljs-params">(Node *prevNode, <span class="hljs-keyword">int</span> x)</span></span>{
        <span class="hljs-keyword">if</span> (prevNode == <span class="hljs-literal">NULL</span>){
            <span class="hljs-built_in">cout</span> &lt;&lt; <span class="hljs-string">"previous cant be null"</span>;
            <span class="hljs-keyword">return</span>;
        }
        Node *newNode = <span class="hljs-keyword">new</span> Node(x);
        newNode-&gt;prev = prevNode;
        newNode-&gt;next = prevNode-&gt;next;
        prevNode-&gt;next = newNode;
        <span class="hljs-keyword">if</span> (newNode-&gt;next != <span class="hljs-literal">NULL</span>){
            newNode-&gt;next-&gt;prev = newNode;
        }
    }
    <span class="hljs-function"><span class="hljs-keyword">void</span> <span class="hljs-title">insertEnd</span><span class="hljs-params">(<span class="hljs-keyword">int</span> x)</span></span>{
        Node *newNode = <span class="hljs-keyword">new</span> Node(x);
        newNode-&gt;next = <span class="hljs-literal">NULL</span>;
        Node *last = head;
        <span class="hljs-keyword">if</span> (head == <span class="hljs-literal">NULL</span>){
            newNode-&gt;prev = <span class="hljs-literal">NULL</span>;
            head = newNode;
            <span class="hljs-keyword">return</span>;
        }
        <span class="hljs-keyword">while</span> (last-&gt;next != <span class="hljs-literal">NULL</span>){
            last = last-&gt;next;
        }
        last-&gt;next = newNode;
        newNode-&gt;prev = last;
    }
    <span class="hljs-function"><span class="hljs-keyword">void</span> <span class="hljs-title">deleteNode</span><span class="hljs-params">(Node *delNode)</span></span>{
        <span class="hljs-keyword">if</span>(head == <span class="hljs-literal">NULL</span> || delNode == <span class="hljs-literal">NULL</span>){
            <span class="hljs-keyword">return</span>;
        }
        <span class="hljs-keyword">if</span>(head == delNode){ <span class="hljs-comment">// del first node;</span>
            head = delNode-&gt;next;
        }
        <span class="hljs-keyword">if</span>(delNode-&gt;next!=<span class="hljs-literal">NULL</span>){ 
            delNode-&gt;next-&gt;prev = delNode-&gt;prev;
        }
        <span class="hljs-keyword">if</span>(delNode-&gt;prev!=<span class="hljs-literal">NULL</span>){
            delNode-&gt;prev-&gt;next = delNode-&gt;next;
        }
        <span class="hljs-keyword">delete</span> delNode;
    }

    <span class="hljs-function"><span class="hljs-keyword">void</span> <span class="hljs-title">display</span><span class="hljs-params">(Node *node)</span> </span>{ <span class="hljs-comment">// displays a list after a given node</span>
        Node *last;

        <span class="hljs-comment">// forward direction</span>
        <span class="hljs-keyword">while</span> (node != <span class="hljs-literal">NULL</span>){
            <span class="hljs-built_in">cout</span> &lt;&lt; node-&gt;data &lt;&lt; <span class="hljs-string">"&lt;==&gt;"</span>;
            last = node;
            node = node-&gt;next;
        }
        <span class="hljs-comment">// backward direction</span>
        <span class="hljs-keyword">while</span> (last != <span class="hljs-literal">NULL</span>){
            <span class="hljs-built_in">cout</span> &lt;&lt; last-&gt;data &lt;&lt; <span class="hljs-string">"&lt;==&gt;"</span>;
            last = last-&gt;prev;
        }
    }
}
</code></pre>
<h3 id="heading-circular-linked-list">Circular Linked List -</h3>
<pre><code class="lang-cpp"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Node</span>{</span>
<span class="hljs-keyword">public</span>:
    <span class="hljs-keyword">int</span> data;
    Node *next;
    Node(){
        <span class="hljs-keyword">this</span>-&gt;data = <span class="hljs-number">0</span>;
        <span class="hljs-keyword">this</span>-&gt;next = <span class="hljs-literal">NULL</span>;
    }
    Node(<span class="hljs-keyword">int</span> x){
        <span class="hljs-keyword">this</span>-&gt;data = x;
        <span class="hljs-keyword">this</span>-&gt;next = <span class="hljs-literal">NULL</span>;
    }
}

<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">cll</span>{</span>
    Node *head;
    Node *tail;

<span class="hljs-keyword">public</span>:
    cll(){
        <span class="hljs-keyword">this</span>-&gt;head = <span class="hljs-literal">NULL</span>;
        <span class="hljs-keyword">this</span>-&gt;tail = <span class="hljs-literal">NULL</span>;
    }
    <span class="hljs-function"><span class="hljs-keyword">void</span> <span class="hljs-title">insert</span><span class="hljs-params">(<span class="hljs-keyword">int</span> x)</span>
    </span>{
        Node *newNode = newNode(x);
        <span class="hljs-keyword">if</span> (head == <span class="hljs-literal">NULL</span>){
            head = newNode;
            tail = newNode;
            <span class="hljs-keyword">return</span>;
        }
        tail-&gt;next = newNode;
        newNode-&gt;next = head;
        tail = newNode;
    }

    <span class="hljs-function"><span class="hljs-keyword">void</span> <span class="hljs-title">delNode</span><span class="hljs-params">(<span class="hljs-keyword">int</span> x)</span>
    </span>{
        Node *temp = head;
        <span class="hljs-keyword">if</span> (head == tail){
            head = <span class="hljs-literal">NULL</span>;
            tail = <span class="hljs-literal">NULL</span>;
            <span class="hljs-keyword">return</span>;
        }
        <span class="hljs-keyword">if</span> (temp-&gt;data == x){
            head = head-&gt;next;
            tail-&gt;next = head;
            <span class="hljs-keyword">return</span>;
        }
        <span class="hljs-keyword">do</span>{
            Node *n = temp-&gt;next;
            <span class="hljs-keyword">if</span> (n-&gt;data == x){
                temp-&gt;next = n-&gt;next;
                <span class="hljs-keyword">break</span>;
            }
            temp = temp-&gt;next;
        } <span class="hljs-keyword">while</span> (temp != head);
    }

    <span class="hljs-function"><span class="hljs-keyword">void</span> <span class="hljs-title">display</span><span class="hljs-params">()</span></span>{
        Node *temp = head;
        <span class="hljs-keyword">if</span> (head != <span class="hljs-literal">NULL</span>){
            <span class="hljs-keyword">do</span>{
                <span class="hljs-built_in">cout</span> &lt;&lt; temp-&gt;data &lt;&lt; <span class="hljs-string">"--&gt;"</span>;
                <span class="hljs-keyword">if</span> (temp-&gt;next != <span class="hljs-literal">NULL</span>){
                    temp = temp-&gt;next;
                }
            } <span class="hljs-keyword">while</span> (temp != head);
        }
    }
}
</code></pre>
<hr />
<h2 id="heading-interview-questions-on-linked-lists">Interview Questions on Linked Lists -</h2>
<div class="embed-wrapper"><div class="embed-loading"><div class="loadingRow"></div><div class="loadingRow"></div></div><a class="embed-card" href="https://github.com/ratishjain12/DSA">https://github.com/ratishjain12/DSA</a></div>
<p> </p>
<p>Check out all the questions about linked lists that have been asked in the FAANG interviews frequently in this GitHub repository also make sure to follow me on GitHub to stay updated on such content, also you can too contribute to this repo.</p>
<hr />
<h2 id="heading-other-related-blogs">Other related blogs -</h2>
<div class="embed-wrapper"><div class="embed-loading"><div class="loadingRow"></div><div class="loadingRow"></div></div><a class="embed-card" href="https://devcon.hashnode.dev/learn-heap-data-structure-in-easiest-way">https://devcon.hashnode.dev/learn-heap-data-structure-in-easiest-way</a></div>
<p> </p>
<div class="embed-wrapper"><div class="embed-loading"><div class="loadingRow"></div><div class="loadingRow"></div></div><a class="embed-card" href="https://devcon.hashnode.dev/learn-stack-data-structure-from-scratch-with-interview-questions">https://devcon.hashnode.dev/learn-stack-data-structure-from-scratch-with-interview-questions</a></div>
<p> </p>
<p>Congrats! you have learned the fundamentals of Linked List Data-Structure, make sure to subscribe to my blog to follow this series and follow me on Hashnode, where I'll be uploading content on Data Structures and Algorithms every weekend.</p>
]]></content:encoded></item><item><title><![CDATA[Learn Heap Data-Structure in Easiest Way]]></title><description><![CDATA[Heap is a special Tree based Data-Structure in which the tree is a complete binary tree.
It is generally of two types -

Max-heap - where the root node must be greatest among all its child nodes and the same goes for its right subtree and left subtre...]]></description><link>https://blog.ratishfolio.com/learn-heap-data-structure-in-easiest-way</link><guid isPermaLink="true">https://blog.ratishfolio.com/learn-heap-data-structure-in-easiest-way</guid><category><![CDATA[interview]]></category><category><![CDATA[data structures]]></category><category><![CDATA[C++]]></category><category><![CDATA[Java]]></category><category><![CDATA[Programming Blogs]]></category><dc:creator><![CDATA[Ratish Jain]]></dc:creator><pubDate>Sun, 25 Dec 2022 11:30:45 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1671867931680/b29636cf-7ac1-47bb-a1d8-13db9d8ba461.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Heap is a special Tree based Data-Structure in which the tree is a complete binary tree.</p>
<p>It is generally of two types -</p>
<ul>
<li><p>Max-heap - where the root node must be greatest among all its child nodes and the same goes for its right subtree and left subtree.</p>
</li>
<li><p>Min-heap - where the root node must be smallest among all its child nodes and the same goes for its right subtree and left subtree.</p>
<p>  <img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1671804396391/de80f8b0-3d71-479f-98b5-efcec23d05b0.png" alt class="image--center mx-auto" /></p>
</li>
</ul>
<h2 id="heading-operations-on-a-heap">Operations on a Heap -</h2>
<ul>
<li><p>insert() - Inserts data into Heap.</p>
</li>
<li><p>extract min() - Extracts and deletes the smallest element in the Heap while maintaining its properties.</p>
</li>
<li><p>decreaseKey() - Changes an element at an index in the Heap while maintaining its properties.</p>
</li>
<li><p>deleteKey() - Deletes an element at an index in the Heap while maintaining its properties.</p>
</li>
<li><p>heapify() - The process of creating a heap data structure from a binary tree represented using an array.</p>
</li>
<li><p>buildHeap() - converts an array into a Heap using the help of heapify function.</p>
</li>
<li><p>getMin()/getMax() - Returns the minimum/maximum element of the Heap.</p>
</li>
</ul>
<h2 id="heading-implementation-of-heap">Implementation of Heap -</h2>
<p>Heap is represented using arrays where the element at the 0-th index is greatest in the case of a Max-heap and minimum in the case of a Min-heap.</p>
<p>We find the right and left child using the formula -</p>
<ul>
<li><p>left child = 2*i+1</p>
</li>
<li><p>right child = 2*i+2</p>
</li>
<li><p>parent = (i-1)/2</p>
</li>
<li><p>Here, i is the index of the node.</p>
</li>
</ul>
<pre><code class="lang-cpp"><span class="hljs-meta">#<span class="hljs-meta-keyword">include</span> <span class="hljs-meta-string">&lt;iostream&gt;</span></span>
<span class="hljs-keyword">using</span> <span class="hljs-keyword">namespace</span> <span class="hljs-built_in">std</span>;

<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Heap</span>
{</span>
    <span class="hljs-keyword">int</span> size;
    <span class="hljs-keyword">int</span> capacity;
    <span class="hljs-keyword">int</span> arr[];
    Heap(<span class="hljs-keyword">int</span> c)
    {
        size = <span class="hljs-number">0</span>;
        capacity = c;
        arr = <span class="hljs-keyword">new</span> <span class="hljs-keyword">int</span>[c];
    }
    <span class="hljs-function"><span class="hljs-keyword">int</span> <span class="hljs-title">leftChild</span><span class="hljs-params">(<span class="hljs-keyword">int</span> i)</span> <span class="hljs-comment">// extracts left child Index</span>
    </span>{
        <span class="hljs-keyword">return</span> (<span class="hljs-number">2</span> * i + <span class="hljs-number">1</span>);
    }
    <span class="hljs-function"><span class="hljs-keyword">int</span> <span class="hljs-title">rightChild</span><span class="hljs-params">(<span class="hljs-keyword">int</span> i)</span> <span class="hljs-comment">// extracts right child index</span>
    </span>{
        <span class="hljs-keyword">return</span> (<span class="hljs-number">2</span> * i + <span class="hljs-number">2</span>);
    }
    <span class="hljs-function"><span class="hljs-keyword">int</span> <span class="hljs-title">parent</span><span class="hljs-params">(<span class="hljs-keyword">int</span> i)</span> <span class="hljs-comment">// extracts parent index of a node</span>
    </span>{
        <span class="hljs-keyword">return</span> (i - <span class="hljs-number">1</span>) / <span class="hljs-number">2</span>;
    }
    insert(<span class="hljs-keyword">int</span> x) <span class="hljs-comment">// Time Complexity o(logn) // inserts in Heap</span>
    {
        <span class="hljs-keyword">if</span> (size == capacity)
            <span class="hljs-keyword">return</span>;
        size++;
        arr[size - <span class="hljs-number">1</span>] = x;
        <span class="hljs-keyword">int</span> i = size - <span class="hljs-number">1</span>;
        <span class="hljs-keyword">while</span> (i != <span class="hljs-number">0</span> &amp;&amp; arr[parent(i)] &gt; arr[i])
        {
            swap(arr[parent(i)], arr[i]);
            i = parent(i);
        }
    }
    <span class="hljs-function"><span class="hljs-keyword">void</span> <span class="hljs-title">minHeapify</span><span class="hljs-params">(<span class="hljs-keyword">int</span> i)</span> </span>{ <span class="hljs-comment">// Time Complexity O(logN)</span>
        <span class="hljs-keyword">int</span> li = leftChild(i), ri = rightChild(i);
        <span class="hljs-keyword">int</span> smallest = i;
        <span class="hljs-keyword">if</span> (li &lt; size &amp;&amp; arr[li] &lt; arr[smallest])
        {
            smallest = li;
        }
        <span class="hljs-keyword">if</span> (ri &lt; size &amp;&amp; arr[ri] &lt; arr[smallest])
        {
            smallest = ri;
        }
        <span class="hljs-keyword">if</span> (smallest != i)
        {
            swap(arr[i], arr[smallest]);
            minHeapify(smallest);
        }
    }
    <span class="hljs-function"><span class="hljs-keyword">int</span> <span class="hljs-title">getMin</span><span class="hljs-params">()</span> <span class="hljs-comment">// extracts minimum element from heap</span>
    </span>{
        <span class="hljs-keyword">return</span> arr[<span class="hljs-number">0</span>];
    }

    <span class="hljs-function"><span class="hljs-keyword">int</span> <span class="hljs-title">extractMin</span><span class="hljs-params">()</span><span class="hljs-comment">//removes minimum element from heap and returns it</span>
    </span>{
        <span class="hljs-keyword">if</span> (size == <span class="hljs-number">0</span>)
            <span class="hljs-keyword">return</span> INT_MAX;
        <span class="hljs-keyword">if</span> (size == <span class="hljs-number">1</span>)
        {
            size--;
            <span class="hljs-keyword">return</span> arr[<span class="hljs-number">0</span>];
        }
        swap(arr[<span class="hljs-number">0</span>], arr[size - <span class="hljs-number">1</span>]);
        size--;
        minHeapify(<span class="hljs-number">0</span>);
        <span class="hljs-keyword">return</span> arr[size];
    }
    <span class="hljs-function"><span class="hljs-keyword">void</span> <span class="hljs-title">decreaseKey</span><span class="hljs-params">(<span class="hljs-keyword">int</span> i, <span class="hljs-keyword">int</span> x)</span> <span class="hljs-comment">//changes a heap element at index i</span>
    </span>{
        arr[i] = x;
        <span class="hljs-keyword">while</span> (i != <span class="hljs-number">0</span> &amp;&amp; arr[parent(i)] &gt; arr[i])
        {
            swap(arr[parent(i)], arr[i]);
            i = parent(i);
        }
    }

    <span class="hljs-function"><span class="hljs-keyword">void</span> <span class="hljs-title">deleteKey</span><span class="hljs-params">(<span class="hljs-keyword">int</span> i)</span> <span class="hljs-comment">// deletes a element at i index</span>
    </span>{
        decreaseKey(i, INT_MIN);
        extractMin();
    }

    <span class="hljs-function"><span class="hljs-keyword">void</span> <span class="hljs-title">buildHeap</span><span class="hljs-params">()</span> <span class="hljs-comment">// T.C. O(N) //builds the heap using heapify()</span>
    </span>{
        <span class="hljs-keyword">for</span> (<span class="hljs-keyword">int</span> i = (size - <span class="hljs-number">2</span>) / <span class="hljs-number">2</span>; i &gt;= <span class="hljs-number">0</span>; i--)
        {
            minHeapify(i);
        }
    }
}
</code></pre>
<h2 id="heading-applications-of-heap">Applications of Heap -</h2>
<ul>
<li><p>Heap is used to constructing a priority_queue</p>
</li>
<li><p>Heap sort is the fastest sorting algorithm with time complexity O(N*logN) and is easy to implement.</p>
</li>
</ul>
<h2 id="heading-priorityqueue">priority_queue -</h2>
<p>In c++, the STL priority_queue provides the functionality of the priority queue which is internally created using Heap Data-Structure.</p>
<p>To solve questions related to Heap priority_queue will be used in c++, it is of two types ascending priority queue and descending priority queue.</p>
<p>To create a min heap the syntax is -</p>
<ul>
<li>priority_queue&lt;int,vector&lt;int&gt;,greater&lt;int&gt;&gt; pq;</li>
</ul>
<p>To create a max heap the syntax is -</p>
<ul>
<li>priority_queue&lt;int&gt; pq;</li>
</ul>
<h3 id="heading-priorityqueue-functions">priority_queue functions -</h3>
<ul>
<li><p>size() - returns the size of the queue</p>
</li>
<li><p>push() - pushes an element inside the queue</p>
</li>
<li><p>pop() - deletes the first element of the queue</p>
</li>
<li><p>empty() - checks whether the queue is empty or not</p>
</li>
<li><p>top() - returns a topmost element of the queue</p>
</li>
</ul>
<h2 id="heading-heap-interview-questions">Heap Interview Questions -</h2>
<ul>
<li><p><a target="_blank" href="https://github.com/ratishjain12/DSA/blob/main/Heaps/implementation/heap.cpp">Heap implementation</a></p>
</li>
<li><p><a target="_blank" href="https://github.com/ratishjain12/DSA/blob/main/Heaps/checkif-arr-is-heap-or-not.cpp">Check if an array is a heap or not</a></p>
</li>
<li><p><a target="_blank" href="https://github.com/ratishjain12/DSA/blob/main/Heaps/convert-minheap-to-max.cpp">Convert a min-heap to max-heap</a></p>
</li>
<li><p><a target="_blank" href="https://github.com/ratishjain12/DSA/blob/main/Heaps/heap-sort.cpp">Heap sort</a></p>
</li>
<li><p><a target="_blank" href="https://github.com/ratishjain12/DSA/blob/main/Heaps/k-closest.cpp">K-closest</a></p>
</li>
<li><p><a target="_blank" href="https://github.com/ratishjain12/DSA/blob/main/Heaps/k-frequent-numbers.cpp">K-frequent numbers</a></p>
</li>
<li><p><a target="_blank" href="https://github.com/ratishjain12/DSA/blob/main/Heaps/kthlargestelement.cpp">K-th largest/smallest element</a></p>
</li>
<li><p><a target="_blank" href="https://github.com/ratishjain12/DSA/blob/main/Heaps/merge-k-sorted-arr.cpp">Merge-k-sorted arrays</a></p>
</li>
<li><p><a target="_blank" href="https://github.com/ratishjain12/DSA/blob/main/Heaps/minimcostofrope.cpp">The minimum cost of the rope</a></p>
</li>
<li><p><a target="_blank" href="https://github.com/ratishjain12/DSA/blob/main/Heaps/sort-k-sorted(nearly%20sorted).cpp">Sort k-sorted array(nearly sorted)</a></p>
</li>
</ul>
<h2 id="heading-a-resource-to-get-in-depth-knowledge">A resource to get in-depth knowledge -</h2>
<div class="embed-wrapper"><div class="embed-loading"><div class="loadingRow"></div><div class="loadingRow"></div></div><a class="embed-card" href="https://www.youtube.com/watch?v=-VhasEYfeT0&amp;list=PLzjZaW71kMwTF8ZcUwm9md_3MvtOfwGow">https://www.youtube.com/watch?v=-VhasEYfeT0&amp;list=PLzjZaW71kMwTF8ZcUwm9md_3MvtOfwGow</a></div>
<p> </p>
<p>Congrats! you have learned the fundamentals of Heap Data-Structure, make sure to subscribe to my blog to follow this series and follow me on Hashnode, where I'll be uploading content on Data Structures and Algorithms every weekend.</p>
]]></content:encoded></item><item><title><![CDATA[Learn Stack Data-Structure From Scratch with Interview Questions]]></title><description><![CDATA[Stack is a linear Data-Structure following First In Last Out(FILO) order ie. The last element in a stack will be removed first.

Operations on a Stack -

push() - pushes an element in the stack.

pop() - removes an element from the top of the stack.
...]]></description><link>https://blog.ratishfolio.com/learn-stack-data-structure-from-scratch-with-interview-questions</link><guid isPermaLink="true">https://blog.ratishfolio.com/learn-stack-data-structure-from-scratch-with-interview-questions</guid><category><![CDATA[datastructure]]></category><category><![CDATA[stack]]></category><category><![CDATA[Programming Blogs]]></category><category><![CDATA[coding]]></category><category><![CDATA[C++]]></category><dc:creator><![CDATA[Ratish Jain]]></dc:creator><pubDate>Sun, 18 Dec 2022 12:30:42 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1671296587099/CNB5nrbpR.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Stack is a linear Data-Structure following First In Last Out(FILO) order ie. The last element in a stack will be removed first.</p>
<p><img src="https://www.tutorialspoint.com/data_structures_algorithms/images/stack_representation.jpg" alt="Stack Representation" class="image--center mx-auto" /></p>
<h2 id="heading-operations-on-a-stack">Operations on a Stack -</h2>
<ul>
<li><p>push() - pushes an element in the stack.</p>
</li>
<li><p>pop() - removes an element from the top of the stack.</p>
</li>
<li><p>peek()/top() - returns the top element of the stack.</p>
</li>
<li><p>isEmpty() - checks if the stack is empty or not.</p>
</li>
<li><p>isFull() - checks if the stack is full or not</p>
</li>
</ul>
<h3 id="heading-ways-of-implementing-stack">Ways of implementing Stack -</h3>
<ul>
<li><p>Using Arrays</p>
</li>
<li><p>Using Linked list</p>
</li>
</ul>
<h3 id="heading-using-arrays">Using Arrays -</h3>
<pre><code class="lang-cpp"><span class="hljs-meta">#<span class="hljs-meta-keyword">include</span> <span class="hljs-meta-string">&lt;iostream&gt;</span></span>
<span class="hljs-keyword">using</span> <span class="hljs-keyword">namespace</span> <span class="hljs-built_in">std</span>;

<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Stack</span>{</span>
<span class="hljs-keyword">private</span>:
  <span class="hljs-keyword">int</span> top;
  <span class="hljs-keyword">int</span> cap;
  <span class="hljs-keyword">int</span> *arr;

<span class="hljs-keyword">public</span>:

  Stack(<span class="hljs-keyword">int</span> c){
    top = <span class="hljs-number">-1</span>;
    cap = c;
    arr = <span class="hljs-keyword">new</span> <span class="hljs-keyword">int</span>[c];
  }

  <span class="hljs-function"><span class="hljs-keyword">void</span> <span class="hljs-title">push</span><span class="hljs-params">(<span class="hljs-keyword">int</span> x)</span></span>{ <span class="hljs-comment">//pushes element in the stack</span>
    <span class="hljs-keyword">if</span>(isFull()){
      <span class="hljs-built_in">cout</span>&lt;&lt;<span class="hljs-string">"Stack overflow"</span>;
    }
    top++;
    arr[top] = x;
  }

  <span class="hljs-function"><span class="hljs-keyword">int</span> <span class="hljs-title">pop</span><span class="hljs-params">()</span></span>{ <span class="hljs-comment">//removes element from the top of stack</span>
    <span class="hljs-keyword">if</span>(isEmpty()){
      <span class="hljs-built_in">cout</span>&lt;&lt;<span class="hljs-string">"Stack underflow"</span>;
    }
    <span class="hljs-keyword">int</span> p = arr[top];
    top--;
    <span class="hljs-keyword">return</span> p;
  }

  <span class="hljs-function"><span class="hljs-keyword">int</span> <span class="hljs-title">peek</span><span class="hljs-params">()</span></span>{ <span class="hljs-comment">//returns top elements of the stack</span>
    <span class="hljs-keyword">return</span> arr[top];
  }

  <span class="hljs-function"><span class="hljs-keyword">bool</span> <span class="hljs-title">isFull</span><span class="hljs-params">()</span></span>{
       <span class="hljs-keyword">if</span>(top == cap<span class="hljs-number">-1</span>){
          <span class="hljs-keyword">return</span> <span class="hljs-literal">true</span>;
       }
    <span class="hljs-keyword">return</span> <span class="hljs-literal">false</span>; 
  }

  <span class="hljs-function"><span class="hljs-keyword">bool</span> <span class="hljs-title">isEmpty</span><span class="hljs-params">()</span></span>{ <span class="hljs-comment">//checks if stack is empty or not</span>
    <span class="hljs-keyword">if</span>(top == <span class="hljs-number">-1</span>){
      <span class="hljs-keyword">return</span> <span class="hljs-literal">true</span>;
    }
    <span class="hljs-keyword">return</span> <span class="hljs-literal">false</span>;
  }
};
</code></pre>
<h3 id="heading-using-linked-list">Using Linked List -</h3>
<pre><code class="lang-cpp"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Node</span>
{</span>
<span class="hljs-keyword">public</span>:
    <span class="hljs-keyword">int</span> data;
    Node *next;
    Node(<span class="hljs-keyword">int</span> d)
    {
        <span class="hljs-keyword">this</span>-&gt;data = d;
        <span class="hljs-keyword">this</span>-&gt;next = <span class="hljs-literal">NULL</span>;
    }
};

<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">myStack</span>
{</span>
<span class="hljs-keyword">private</span>:
    Node *top;
    <span class="hljs-keyword">int</span> size = <span class="hljs-number">0</span>;
    <span class="hljs-keyword">int</span> capacity = <span class="hljs-number">5</span>;

<span class="hljs-keyword">public</span>:
    myStack()
    {
        top = <span class="hljs-literal">NULL</span>;
    }
    <span class="hljs-function"><span class="hljs-keyword">void</span> <span class="hljs-title">push</span><span class="hljs-params">(<span class="hljs-keyword">int</span> x)</span>
    </span>{
        <span class="hljs-keyword">if</span> (size &gt;= capacity)
        {
            <span class="hljs-built_in">cout</span> &lt;&lt; <span class="hljs-string">"stack overflow"</span>;
            <span class="hljs-keyword">return</span>;
        }
        Node *newNode;
        newNode = (Node *)<span class="hljs-built_in">malloc</span>(<span class="hljs-keyword">sizeof</span>(Node));
        newNode-&gt;data = x;
        newNode-&gt;next = top;
        top = newNode;
        size++;
    }

    <span class="hljs-function"><span class="hljs-keyword">int</span> <span class="hljs-title">pop</span><span class="hljs-params">()</span>
    </span>{
        Node *temp;
        <span class="hljs-keyword">int</span> data;
        <span class="hljs-keyword">if</span> (size &lt;= <span class="hljs-number">0</span>)
        {
            <span class="hljs-built_in">cout</span> &lt;&lt; <span class="hljs-string">"stack underflow"</span>;
            <span class="hljs-keyword">return</span>;
        }
        temp = top;
        data = top-&gt;data;
        top = top-&gt;next;
        <span class="hljs-built_in">free</span>(temp);
        size--;
        <span class="hljs-keyword">return</span> data;
    }

    <span class="hljs-function"><span class="hljs-keyword">bool</span> <span class="hljs-title">isEmpty</span><span class="hljs-params">()</span>
    </span>{
        <span class="hljs-keyword">return</span> size &lt;= <span class="hljs-number">0</span>;
    }

    <span class="hljs-function"><span class="hljs-keyword">int</span> <span class="hljs-title">peek</span><span class="hljs-params">()</span>
    </span>{
        <span class="hljs-keyword">if</span> (!isEmpty())
        {
            <span class="hljs-keyword">return</span> top-&gt;data;
        }
        <span class="hljs-keyword">else</span>
        {
            <span class="hljs-built_in">cout</span> &lt;&lt; <span class="hljs-string">"Stack is empty."</span>;
        }
    }
    <span class="hljs-function"><span class="hljs-keyword">void</span> <span class="hljs-title">display</span><span class="hljs-params">()</span>
    </span>{
        Node *temp = top;
        <span class="hljs-keyword">while</span> (top != <span class="hljs-literal">NULL</span>)
        {
            <span class="hljs-built_in">cout</span> &lt;&lt; temp-&gt;data &lt;&lt; <span class="hljs-string">" "</span>;
            temp = temp-&gt;next;
        }
    }
};
</code></pre>
<h2 id="heading-stack-overflow-and-stack-underflow">Stack Overflow and Stack Underflow -</h2>
<p>Stack Overflow - It is a situation in which the stack is full and no elements can be pushed ie. when we try to push more items in a stack than it can hold.</p>
<p>Stack Underflow - this happens when we try to pop an element from an empty stack.</p>
<h2 id="heading-top-interview-questions">Top Interview Questions -</h2>
<ul>
<li><p><a target="_blank" href="https://github.com/ratishjain12/DSA/blob/main/Stack%26Queue/stack/questions/balanced-parenthesis.cpp">Balanced-parenthesis problem</a></p>
</li>
<li><p><a target="_blank" href="https://github.com/ratishjain12/DSA/blob/main/Stack%26Queue/stack/questions/asteroid-collision.cpp">Astroid-collision problem</a></p>
</li>
<li><p><a target="_blank" href="https://github.com/ratishjain12/DSA/blob/main/Stack%26Queue/stack/questions/celebrity-problem.cpp">Celebrity-problem</a></p>
</li>
<li><p><a target="_blank" href="https://github.com/ratishjain12/DSA/blob/main/Stack%26Queue/stack/questions/largest-rect-histogram.cpp">Largest-Rectangle-histogram problem</a></p>
</li>
<li><p><a target="_blank" href="https://github.com/ratishjain12/DSA/blob/main/Stack%26Queue/stack/questions/maximal-rectangle.cpp">Maximal-Rectangle problem</a></p>
</li>
<li><p><a target="_blank" href="https://github.com/ratishjain12/DSA/blob/main/Stack%26Queue/stack/questions/stock_span.cpp">Stock-Span Problem</a></p>
</li>
<li><p><a target="_blank" href="https://github.com/ratishjain12/DSA/blob/main/Stack%26Queue/stack/questions/next-greater-element.cpp">Next-greater-element problem</a></p>
</li>
<li><p><a target="_blank" href="https://github.com/ratishjain12/DSA/blob/main/Stack%26Queue/stack/questions/next-greater-element-2.cpp">Next-greater-element-2(Circular)</a></p>
</li>
<li><p><a target="_blank" href="https://github.com/ratishjain12/DSA/blob/main/Stack%26Queue/stack/questions/remove-k-digits.cpp">remove-k-digits problem</a></p>
</li>
<li><p><a target="_blank" href="https://github.com/ratishjain12/DSA/blob/main/Stack%26Queue/stack/questions/deleteMiddle.cpp">delete the middle element of the stack</a></p>
</li>
<li><p><a target="_blank" href="https://github.com/ratishjain12/DSA/blob/main/Stack%26Queue/stack/questions/sortStack.cpp">sort the stack</a></p>
</li>
<li><p><a target="_blank" href="https://github.com/ratishjain12/DSA/blob/main/Stack%26Queue/stack/questions/reverseStack.cpp">reverse the stack</a></p>
</li>
<li><p><a target="_blank" href="https://github.com/ratishjain12/DSA/blob/main/Stack%26Queue/stack/implementation-prblms/usingqueue.cpp">Implement stack using a queue</a></p>
</li>
<li><p><a target="_blank" href="https://github.com/ratishjain12/DSA/blob/main/Stack%26Queue/stack/implementation-prblms/usingtwoqueue.cpp">Implement stack using two queue</a></p>
</li>
</ul>
<h2 id="heading-resources-to-get-in-depth-knowledge">Resources to get in-depth knowledge -</h2>
<p>Aditya Verma Stack playlist -</p>
<div class="embed-wrapper"><div class="embed-loading"><div class="loadingRow"></div><div class="loadingRow"></div></div><a class="embed-card" href="https://www.youtube.com/watch?v=P1bAPZg5uaE&amp;list=PL_z_8CaSLPWdeOezg68SKkeLN4-T_jNHd">https://www.youtube.com/watch?v=P1bAPZg5uaE&amp;list=PL_z_8CaSLPWdeOezg68SKkeLN4-T_jNHd</a></div>
<p> </p>
<p>Love Babbar Stack playlist -</p>
<div class="embed-wrapper"><div class="embed-loading"><div class="loadingRow"></div><div class="loadingRow"></div></div><a class="embed-card" href="https://www.youtube.com/watch?v=_6COl6V6mng&amp;list=PLDzeHZWIZsTrhXYYtx4z8-u8zA-DzuVsj">https://www.youtube.com/watch?v=_6COl6V6mng&amp;list=PLDzeHZWIZsTrhXYYtx4z8-u8zA-DzuVsj</a></div>
<p> </p>
<p>Congrats! you have learned the fundamentals of Stack Data-Structure, make sure to subscribe to my blog to follow this series and follow me on Hashnode, where I'll be uploading content on Data Structures and Algorithms every weekend.</p>
]]></content:encoded></item></channel></rss>