<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Diwakar Kumar on Medium]]></title>
        <description><![CDATA[Stories by Diwakar Kumar on Medium]]></description>
        <link>https://medium.com/@diwakarsingh6853?source=rss-ef27431e21e------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*QjYpH2OEZe0khKGP</url>
            <title>Stories by Diwakar Kumar on Medium</title>
            <link>https://medium.com/@diwakarsingh6853?source=rss-ef27431e21e------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 18 May 2026 06:36:37 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@diwakarsingh6853/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com" rel="hub"/>
        <item>
            <title><![CDATA[Mastering TypeScript: Comprehensive Guide to Types]]></title>
            <link>https://medium.com/@diwakarsingh6853/mastering-typescript-comprehensive-guide-to-types-eb9a9d5c84d3?source=rss-ef27431e21e------2</link>
            <guid isPermaLink="false">https://medium.com/p/eb9a9d5c84d3</guid>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[angular]]></category>
            <category><![CDATA[es6]]></category>
            <dc:creator><![CDATA[Diwakar Kumar]]></dc:creator>
            <pubDate>Fri, 13 Dec 2024 15:42:36 GMT</pubDate>
            <atom:updated>2024-12-13T15:42:36.414Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*9dIsAYwkQPYBqjPK" /><figcaption>Photo by <a href="https://unsplash.com/@timothycuenat?utm_source=medium&amp;utm_medium=referral">Timothy Cuenat</a> on <a href="https://unsplash.com?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>1. Primitive Types</h3><p>Primitive types are the fundamental building blocks in TypeScript.</p><h4>string</h4><p>Used to represent textual data.</p><pre>let greeting: string = &quot;Hello, World!&quot;;</pre><p><strong>When to use</strong>: For text-based data like names, messages, or descriptions.</p><h4>number</h4><p>Handles numeric values, including integers and floats.</p><pre>let count: number = 42;</pre><p><strong>When to use</strong>: For mathematical operations, counters, or numerical data.</p><h4>boolean</h4><p>Represents true/false values.</p><pre>let isComplete: boolean = true;</pre><p><strong>When to use</strong>: For conditional logic or flags.</p><h4>bigint</h4><p>Stores large integers beyond the range of number.</p><pre>let big: bigint = 123456789012345678901234567890n;</pre><p><strong>When to use</strong>: For calculations involving large numbers.</p><h4>symbol</h4><p>Represents unique values.</p><pre>const uniqueKey: symbol = Symbol(&quot;unique&quot;);</pre><p><strong>When to use</strong>: To create unique object keys.</p><h4>undefined and null</h4><ul><li>undefined: Absence of a value.</li><li>null: Intentional absence of a value.</li></ul><pre>let u: undefined = undefined;<br>let n: null = null;</pre><p><strong>When to use</strong>: For optional fields or resettable variables.</p><h3>2. Object Types</h3><p>Objects are collections of key-value pairs.</p><h4>General Object</h4><pre>let person: object = { name: &quot;John&quot;, age: 30 };</pre><p><strong>When to use</strong>: For loosely structured objects.</p><h4>Specific Object Shape</h4><pre>let person: { name: string; age: number } = { name: &quot;John&quot;, age: 30 };</pre><p><strong>When to use</strong>: For defining object structure explicitly.</p><h3>3. Array Types</h3><p>Arrays store multiple values of the same type.</p><h4>Typed Array</h4><pre>let numbers: number[] = [1, 2, 3];</pre><p><strong>When to use</strong>: For homogeneous lists like arrays of numbers or strings.</p><h4>Array&lt;Type&gt; Syntax</h4><pre>let strings: Array&lt;string&gt; = [&quot;one&quot;, &quot;two&quot;, &quot;three&quot;];</pre><p><strong>When to use</strong>: Alternative array declaration syntax.</p><h4>Tuple</h4><p>Fixed-length arrays with specific types.</p><pre>let tuple: [string, number] = [&quot;John&quot;, 30];</pre><p><strong>When to use</strong>: For ordered data with mixed types, like coordinates.</p><h3>4. Function Types</h3><p>TypeScript enforces type safety for function parameters and return values.</p><h4>Function Declaration</h4><pre>function add(a: number, b: number): number {<br>  return a + b;<br>}</pre><p><strong>When to use</strong>: For well-defined inputs and outputs.</p><h4>Arrow Functions</h4><pre>const multiply = (x: number, y: number): number =&gt; x * y;</pre><p><strong>When to use</strong>: For concise function expressions.</p><h4>Function Type</h4><pre>let log: (message: string) =&gt; void;<br>log = (message) =&gt; console.log(message);</pre><p><strong>When to use</strong>: To pass functions as arguments or store them in variables.</p><h3>5. Union and Intersection Types</h3><h4>Union Types</h4><p>Allow multiple possible types.</p><pre>let id: string | number = 123;<br>id = &quot;ABC&quot;;</pre><p><strong>When to use</strong>: For variables that can hold multiple types, like IDs.</p><h4>Intersection Types</h4><p>Combine multiple types.</p><pre>type A = { name: string };<br>type B = { age: number };<br>let person: A &amp; B = { name: &quot;John&quot;, age: 30 };</pre><p><strong>When to use</strong>: For merging type requirements.</p><h3>6. Literal Types</h3><p>Define exact allowed values.</p><h4>String Literals</h4><pre>let direction: &quot;up&quot; | &quot;down&quot; = &quot;up&quot;;</pre><h4>Numeric Literals</h4><pre>let bit: 0 | 1 = 1;</pre><p><strong>When to use</strong>: For specific predefined values like enums.</p><h3>7. Enum</h3><p>Defines a set of named constants.</p><h4>Numeric Enum</h4><pre>enum Direction {<br>  Up = 1,<br>  Down,<br>  Left,<br>  Right,<br>}<br>let move: Direction = Direction.Up;</pre><h4>String Enum</h4><pre>enum Status {<br>  Success = &quot;SUCCESS&quot;,<br>  Failure = &quot;FAILURE&quot;,<br>}</pre><p><strong>When to use</strong>: For grouping related constants.</p><h3>8. Advanced Types</h3><h4>any vs. unknown</h4><h4>any</h4><p>Opt-out of type checking.</p><pre>let value: any = 42;<br>value = &quot;hello&quot;;</pre><p>unknown</p><p>Safer alternative to any.</p><pre>let data: unknown;<br>data = &quot;John&quot;;<br>if (typeof data === &quot;string&quot;) {<br>  console.log(data.toUpperCase());<br>}</pre><p><strong>When to use</strong>: Prefer unknown for safer type checking.</p><h4>void and never</h4><h4>void</h4><p>For functions with no return value.</p><pre>function logMessage(): void {<br>  console.log(&quot;Logging...&quot;);<br>}</pre><h4>never</h4><p>For functions that never return.</p><pre>function throwError(): never {<br>  throw new Error(&quot;Something went wrong!&quot;);<br>}</pre><p><strong>When to use</strong>: Use never for unreachable code.</p><h3>9. Utility Types</h3><h4>Partial</h4><p>Makes all properties optional.</p><pre>type PartialPerson = Partial&lt;{ name: string; age: number }&gt;;</pre><h4>Readonly</h4><p>Makes all properties read-only.</p><pre>type ReadonlyPerson = Readonly&lt;{ name: string; age: number }&gt;;</pre><h4>Required</h4><p>Makes all properties mandatory.</p><pre>type RequiredPerson = Required&lt;PartialPerson&gt;;</pre><h4>Pick</h4><p>Select specific properties.</p><pre>type NameOnly = Pick&lt;{ name: string; age: number }, &quot;name&quot;&gt;;</pre><h4>Omit</h4><p>Exclude specific properties.</p><pre>type WithoutAge = Omit&lt;{ name: string; age: number }, &quot;age&quot;&gt;;</pre><h3>10. Generics</h3><p>Generics enable reusable components that work with multiple types.</p><pre>function identity&lt;T&gt;(arg: T): T {<br>  return arg;<br>}<br>let output = identity&lt;string&gt;(&quot;Hello&quot;);</pre><p><strong>When to use</strong>: For flexible and type-safe code.</p><h3>11. Type Aliases</h3><p>Define reusable custom types.</p><pre>type ID = string | number;<br>let userId: ID = &quot;abc123&quot;;</pre><h3>12. Interface</h3><p>Describes the shape of an object.</p><pre>interface Person {<br>  name: string;<br>  age: number;<br>}<br><br>let person: Person = { name: &quot;John&quot;, age: 30 };</pre><h3>13. Conditional Types</h3><p>Types based on conditions.</p><pre>type IsString&lt;T&gt; = T extends string ? true : false;<br>let test: IsString&lt;string&gt; = true;</pre><h3>14. Mapped Types</h3><p>Transform properties of a type.</p><pre>type ReadonlyPerson = {<br>  [K in keyof Person]: Person[K];<br>};</pre><h3>15. U<strong>nion and Intersection Types</strong></h3><p>When one param pass second become mandatory and if not then third become mandatory scenario for button text vs button icon</p><pre>type Params =<br>  | { first: string; second: string; third?: never }<br>  | { first?: never; second?: never; third: string };</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=eb9a9d5c84d3" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Js essential methods and its customcode implemenation]]></title>
            <link>https://medium.com/@diwakarsingh6853/js-essential-methods-and-its-customcode-implemenation-dfbc48a92873?source=rss-ef27431e21e------2</link>
            <guid isPermaLink="false">https://medium.com/p/dfbc48a92873</guid>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[es6]]></category>
            <category><![CDATA[js]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Diwakar Kumar]]></dc:creator>
            <pubDate>Mon, 16 Sep 2024 18:25:07 GMT</pubDate>
            <atom:updated>2024-09-16T18:25:07.831Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*XMEY5f5qnFd8jRlq" /><figcaption>Photo by <a href="https://unsplash.com/@6heinz3r?utm_source=medium&amp;utm_medium=referral">Gabriel Heinzer</a> on <a href="https://unsplash.com?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h4>Bind method</h4><pre>##First Approach Using apply<br><br>Function.prototype.customBind = function (context, ...args) {<br>  // Store the reference to the original function<br>  const fn = this;<br><br>  return function (...newArgs) {<br>    // Apply the function with the combined arguments and context<br>    return fn.apply(context, [...args, ...newArgs]);<br>  };<br>};<br><br>##Second Approach Using call<br><br>Function.prototype.customBind = function (context, ...args) {<br>  const fn = this; // Store the original function reference<br><br>  return function (...newArgs) {<br>    // Call the function with the context and individual arguments<br>    return fn.call(context, ...args, ...newArgs);<br>  };<br>};<br><br>##Third Approach Using arguments<br><br>Function.prototype.customBind = function (context) {<br>  const fn = this;<br>  const bindArgs = Array.prototype.slice.call(arguments, 1); // Capture arguments except for the context<br><br>  return function () {<br>    const callArgs = Array.prototype.slice.call(arguments); // Capture arguments passed to the returned function<br>    return fn.call(context, ...bindArgs, ...callArgs); // Use call to invoke the function with all arguments<br>  };<br>};</pre><pre>##How to use above code<br><br>const person = {<br>  name: &#39;Diwakar&#39;,<br>};<br><br>function greet(greeting, message) {<br>  return `${greeting}, ${this.name}! ${message}`;<br>}<br><br>// Using customBind<br>const customGreet = greet.customBind(person, &#39;Hello&#39;);<br>console.log(customGreet(&#39;Hope you are doing well!&#39;));<br>// Output: &quot;Hello, Diwakar! Hope you are doing well!&quot;</pre><h4>Debounce Method</h4><pre>function debounce(func, delay) {<br>  let timeoutId;<br>  <br>  return function (...args) {<br>    const context = this;<br>    <br>    // Clear the previous timeout if the function is triggered again before the delay<br>    clearTimeout(timeoutId);<br>    <br>    // Set a new timeout for the function execution after the delay<br>    timeoutId = setTimeout(() =&gt; {<br>      func.apply(context, args);<br>    }, delay);<br>  };<br>}<br><br>##Usage <br><br><br>// Example: Debouncing an input field<br>const input = document.getElementById(&#39;searchInput&#39;);<br>input.addEventListener(&#39;input&#39;, debounce(() =&gt; {<br>    console.log(&#39;Search query:&#39;, input.value);<br>}, 500));<br><br>##Where we use debounce<br><br># Search input fields (to delay making API requests)<br># Button click prevention (e.g., disabling multiple form submissions)<br># Input field validation (on change events)</pre><h4>Throttle Method</h4><pre>function throttle(func, delay) {<br>    let lastCall = 0;<br>    return function(...args) {<br>        const now = new Date().getTime();<br>        if (now - lastCall &lt; delay) {<br>            return;<br>        }<br>        lastCall = now;<br>        return func(...args);<br>    };<br>}<br><br>// Example: Throttling a window resize event<br>window.addEventListener(&#39;resize&#39;, throttle(() =&gt; {<br>    console.log(&#39;Window resized&#39;);<br>}, 1000));<br><br>##Where we use debounce<br><br># Scrolling event<br># Window resizing<br># Mouse movements<br></pre><h4>Curry Function</h4><pre>function curry(fn) {<br>    return function curried(...args) {<br>        // If the number of arguments passed is sufficient, call the original function<br>        if (args.length &gt;= fn.length) {<br>            return fn.apply(this, args);<br>        }<br>        // Otherwise, return a function that takes the remaining arguments<br>        else {<br>            return function (...nextArgs) {<br>                return curried.apply(this, args.concat(nextArgs));<br>            };<br>        }<br>    };<br>}<br><br>// Example: -<br><br>// Regular function<br>function multiply(a, b, c) {<br>    return a * b * c;<br>}<br><br>// Currying the multiply function<br>const curriedMultiply = curry(multiply);<br><br>// Calling it step by step<br>console.log(curriedMultiply(2)(3)(4)); // Output: 24</pre><h4>Memoization Function</h4><pre>function memoize(fn) {<br>    const cache = {};<br>    <br>    return function (...args) {<br>        const key = JSON.stringify(args); // Create a unique key for the arguments<br>        <br>        if (cache[key]) {<br>            console.log(`Fetching from cache for args: ${args}`);<br>            return cache[key]; // Return cached result if available<br>        }<br>        <br>        console.log(`Calculating result for args: ${args}`);<br>        const result = fn.apply(this, args); // Compute result<br>        cache[key] = result; // Store the result in the cache<br>        <br>        return result;<br>    };<br>}<br><br>// Example -<br><br>// Normal Fibonacci function (without memoization)<br>function fibonacci(n) {<br>    if (n &lt;= 1) return n;<br>    return fibonacci(n - 1) + fibonacci(n - 2);<br>}<br><br>// Memoized Fibonacci function<br>const memoizedFibonacci = memoize(fibonacci);<br><br>// Test the performance<br>console.log(memoizedFibonacci(10)); // Output: 55<br>console.log(memoizedFibonacci(15)); // Output: 610<br>console.log(memoizedFibonacci(10)); // This will fetch from cache</pre><h4>Custom Filter Method</h4><pre>Array.prototype.customFilter = function(callback, thisArg) {<br>    const result = [];<br>    for (let i = 0; i &lt; this.length; i++) {<br>        // Check if the element passes the test implemented by the callback<br>        if (callback.call(thisArg, this[i], i, this)) {<br>            result.push(this[i]);<br>        }<br>    }<br>    return result; // Return the filtered array<br>};<br><br>// Example<br><br>// Original array<br>const numbers = [1, 2, 3, 4, 5, 6, 7, 8];<br><br>// Custom filter method to return even numbers<br>const evenNumbers = numbers.customFilter(function(number) {<br>    return number % 2 === 0; // Check if number is even<br>});<br><br>console.log(evenNumbers); // Output: [2, 4, 6, 8]<br><br>// Custom filter method with a &#39;thisArg&#39; context<br>const threshold = {<br>    min: 5<br>};<br><br>const greaterThanMin = numbers.customFilter(function(number) {<br>    return number &gt; this.min; // Compare against &#39;this.min&#39;<br>}, threshold);<br><br>console.log(greaterThanMin); // Output: [6, 7, 8]</pre><h4>Custom unshift Method</h4><pre>Array.prototype.customUnshift = function(...args) {<br>    // Step 1: Create space for the new elements by shifting existing elements to the right<br>    const argsLength = args.length;<br>    const originalLength = this.length;<br><br>    // Move elements to the right by the number of arguments passed<br>    for (let i = originalLength - 1; i &gt;= 0; i--) {<br>        this[i + argsLength] = this[i];<br>    }<br><br>    // Step 2: Insert new elements at the beginning<br>    for (let j = 0; j &lt; argsLength; j++) {<br>        this[j] = args[j];<br>    }<br><br>    // Step 3: Return the new length of the array<br>    return this.length;<br>};<br><br>// Example -<br><br><br>// Example array<br>const arr = [3, 4, 5];<br><br>// Use customUnshift to add elements to the beginning<br>const newLength = arr.customUnshift(1, 2);<br><br>console.log(arr);        // Output: [1, 2, 3, 4, 5]<br>console.log(newLength);  // Output: 5 (new length of the array)</pre><h4>Custom shift method</h4><pre>Array.prototype.customShift = function() {<br>    // Step 1: Check if the array is empty<br>    if (this.length === 0) return undefined;<br><br>    // Step 2: Store the first element, which will be removed and returned<br>    const firstElement = this[0];<br><br>    // Step 3: Shift all elements to the left by 1 position<br>    for (let i = 1; i &lt; this.length; i++) {<br>        this[i - 1] = this[i];<br>    }<br><br>    // Step 4: Remove the last element (which is now duplicated)<br>    this.length = this.length - 1;<br><br>    // Step 5: Return the removed first element<br>    return firstElement;<br>};<br><br>// Example -<br><br>// Example array<br>const arr = [10, 20, 30, 40];<br><br>// Use customShift to remove the first element<br>const removedElement = arr.customShift();<br><br>console.log(arr);            // Output: [20, 30, 40]<br>console.log(removedElement); // Output: 10 (the removed element)<br></pre><h4>Custom Console.log Method</h4><pre>// Store the original console.log method<br>const originalConsoleLog = console.log;<br><br>// Redefine console.log<br>console.log = function(...args) {<br>    // Add custom behavior here, e.g., add a timestamp<br>    const timestamp = new Date().toISOString();<br>    originalConsoleLog.call(console, `[${timestamp}]`, ...args);<br>};<br><br>// Test the custom console.log<br>console.log(&#39;This is a custom log message.&#39;);</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=dfbc48a92873" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding API Architecture Styles]]></title>
            <link>https://medium.com/@diwakarsingh6853/understanding-api-architecture-styles-91132188cdef?source=rss-ef27431e21e------2</link>
            <guid isPermaLink="false">https://medium.com/p/91132188cdef</guid>
            <category><![CDATA[restful-api]]></category>
            <category><![CDATA[graphql]]></category>
            <category><![CDATA[api]]></category>
            <category><![CDATA[grpc]]></category>
            <dc:creator><![CDATA[Diwakar Kumar]]></dc:creator>
            <pubDate>Tue, 10 Sep 2024 11:01:47 GMT</pubDate>
            <atom:updated>2024-09-10T11:01:47.470Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Q_WljXGjIYIW-MCM" /><figcaption>Photo by <a href="https://unsplash.com/@mitchel3uo?utm_source=medium&amp;utm_medium=referral">Mitchell Luo</a> on <a href="https://unsplash.com?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>API architecture styles provide essential frameworks for the interaction between various components of an application programming interface (API). The choice of architecture style impacts an API’s efficiency, reliability, and integration capability. Below are some of the most commonly used API styles, each offering unique advantages suited for different use cases:</p><h4>RESTful (Representational State Transfer)</h4><ul><li><strong>Popular, easy-to-implement, HTTP methods</strong><br>REST is perhaps the most widely adopted style today. It leverages standard HTTP methods (GET, POST, PUT, DELETE) to manage resources. This simplicity makes it ideal for web services, and it’s easy to integrate, especially for applications that need a uniform interface.</li></ul><h4>GraphQL</h4><ul><li><strong>Query language, request specific data</strong><br>GraphQL is designed to solve many of the limitations of REST by allowing clients to request exactly the data they need, reducing the number of network requests. It provides a more flexible and efficient way to handle complex data fetching and can significantly reduce network overhead, providing faster responses.</li></ul><h4>gRPC (Google Remote Procedure Call)</h4><ul><li><strong>Modern, high-performance, Protocol Buffers</strong><br>Built on HTTP/2 and using Protocol Buffers for data serialization, gRPC is a performance-focused API style suitable for microservices architectures. It’s known for its low-latency, high-efficiency communication, making it a solid choice for real-time applications.</li></ul><h4>WebSocket</h4><ul><li><strong>Real-time, bidirectional, persistent connections</strong><br>WebSocket excels in scenarios that require low-latency, real-time data exchange. It’s perfect for applications like chat services, live updates, and gaming, where maintaining a persistent connection is crucial.</li></ul><h4>Webhook</h4><ul><li><strong>Event-driven, HTTP callbacks, asynchronous</strong><br>Webhooks provide an efficient way for systems to communicate asynchronously by triggering HTTP callbacks when specific events occur. They are particularly useful in event-driven architectures and scenarios where the system needs to notify external services about certain changes.</li></ul><h4><strong>RESTful API</strong></h4><ul><li><strong>HTTP Methods</strong>: REST utilizes the standard HTTP methods — GET, POST, PUT, DELETE — for managing CRUD operations.</li><li><strong>Uniformity</strong>: REST works well for applications requiring simple, consistent interfaces between services.</li><li><strong>Caching</strong>: REST’s caching strategies are relatively straightforward, making it easier to implement performance improvements.</li><li><strong>Downside</strong>: REST may require multiple requests to different endpoints to retrieve related data, which can increase network traffic.</li></ul><pre>const express = require(&#39;express&#39;);<br>const app = express();<br><br>app.get(&#39;/users/:id&#39;, (req, res) =&gt; {<br>  const userId = req.params.id;<br>  res.send(`Fetching user with ID: ${userId}`);<br>});<br><br>app.listen(3000, () =&gt; {<br>  console.log(&#39;Server running on port 3000&#39;);<br>});</pre><h4>GraphQL</h4><ul><li><strong>Single Endpoint</strong>: GraphQL uses a single endpoint for all queries, allowing clients to specify precisely which data fields they need, leading to optimized payloads.</li><li><strong>Complex Queries</strong>: Clients can request nested and aggregated data from multiple sources in one query.</li><li><strong>Real-Time Support</strong>: GraphQL also supports real-time features like mutations and subscriptions.</li><li><strong>Downside</strong>: Caching strategies in GraphQL can be more complex compared to REST, and improper use can lead to abusive queries, adding complexity to the client side.</li></ul><pre>#GraphQl<br><br>query {<br>  user(id: &quot;123&quot;) {<br>    name<br>    email<br>    posts {<br>      title<br>      content<br>    }<br>  }<br>}<br><br>##Appollo-Server<br><br>const { ApolloServer, gql } = require(&#39;apollo-server&#39;);<br><br>// Type definitions<br>const typeDefs = gql`<br>  type User {<br>    id: ID!<br>    name: String<br>    email: String<br>    posts: [Post]<br>  }<br><br>  type Post {<br>    title: String<br>    content: String<br>  }<br><br>  type Query {<br>    user(id: ID!): User<br>  }<br>`;<br><br>// Resolvers<br>const resolvers = {<br>  Query: {<br>    user: () =&gt; ({<br>      id: &quot;123&quot;,<br>      name: &quot;John Doe&quot;,<br>      email: &quot;john.doe@example.com&quot;,<br>      posts: [<br>        { title: &quot;First Post&quot;, content: &quot;Content of first post&quot; },<br>        { title: &quot;Second Post&quot;, content: &quot;Content of second post&quot; }<br>      ]<br>    })<br>  }<br>};<br><br>// Server setup<br>const server = new ApolloServer({ typeDefs, resolvers });<br>server.listen().then(({ url }) =&gt; {<br>  console.log(`Server ready at ${url}`);<br>});<br></pre><h4>gRPC</h4><p>gRPC is a modern RPC framework that excels in microservices architectures due to its low-latency, high-performance nature. Here’s how gRPC operates:</p><ol><li><strong>REST Call</strong>: A client sends a REST call, typically with a JSON payload.</li><li><strong>gRPC Encoding</strong>: The gRPC client encodes the request into binary format and sends it over the network via HTTP/2.</li><li><strong>Server Processing</strong>: The gRPC server decodes the binary request, processes it, and sends a response back in the same manner.</li><li><strong>Result Delivery</strong>: The client decodes the binary response and delivers it to the application.</li></ol><p>gRPC is typically five times faster than traditional JSON-based REST calls due to its binary encoding and optimized data transmission. It is an excellent fit for high-performance services, especially in microservices-based systems.</p><pre>// gRPC uses Protocol Buffers for data serialization. Below is an example of a gRPC server in Node.js:<br><br>#proto file:<br><br>syntax = &quot;proto3&quot;;<br><br>service UserService {<br>  rpc GetUser (UserRequest) returns (UserResponse);<br>}<br><br>message UserRequest {<br>  string id = 1;<br>}<br><br>message UserResponse {<br>  string name = 1;<br>  string email = 2;<br>}</pre><pre>#gRPC Server (Node.js):<br><br>const grpc = require(&#39;@grpc/grpc-js&#39;);<br>const protoLoader = require(&#39;@grpc/proto-loader&#39;);<br><br>const packageDefinition = protoLoader.loadSync(&#39;user.proto&#39;);<br>const userProto = grpc.loadPackageDefinition(packageDefinition).UserService;<br><br>const server = new grpc.Server();<br><br>server.addService(userProto.service, {<br>  GetUser: (call, callback) =&gt; {<br>    callback(null, { name: &#39;John Doe&#39;, email: &#39;john.doe@example.com&#39; });<br>  }<br>});<br><br>server.bindAsync(&#39;127.0.0.1:50051&#39;, grpc.ServerCredentials.createInsecure(), () =&gt; {<br>  server.start();<br>});</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=91132188cdef" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Micro frontend with Angular elements | Web component technique.]]></title>
            <link>https://medium.com/@diwakarsingh6853/micro-frontend-with-angular-elements-web-component-technique-c940f68e1d3c?source=rss-ef27431e21e------2</link>
            <guid isPermaLink="false">https://medium.com/p/c940f68e1d3c</guid>
            <category><![CDATA[angular]]></category>
            <category><![CDATA[custom-elements]]></category>
            <category><![CDATA[web-components]]></category>
            <category><![CDATA[js]]></category>
            <dc:creator><![CDATA[Diwakar Kumar]]></dc:creator>
            <pubDate>Sun, 08 Sep 2024 04:21:17 GMT</pubDate>
            <atom:updated>2024-09-08T04:21:17.797Z</atom:updated>
            <content:encoded><![CDATA[<p>In this guide, we’ll create a <strong>Micro Frontend using Angular Elements</strong>, where the core app will load smaller sub-applications (or elements) built with Angular v16</p><h4>Steps Overview</h4><ol><li>Create an Angular Application</li><li>Create an Angular Element</li><li>Use the Angular Element in the main app</li><li>Serve the Micro Frontend</li></ol><h4>Creating an Angular Application</h4><p>Start by creating an Angular application using the Angular CLI.</p><pre>ng new core-app<br>cd core-app</pre><h4>Creating an Angular Element</h4><p>Now We’ll create a new Angular application that will act as a micro frontend.</p><pre>ng new micro-frontend --routing=false --style=scss<br>cd micro-frontend</pre><p>Install the Angular Elements and polyfills needed to support older browsers.</p><pre>npm install @angular/elements --save<br>npm install document-register-element --save</pre><p>Create a simple component that will be exposed as an Angular Element.</p><pre>ng generate component hello-world</pre><p>In the <strong><em>hello-world.component.ts</em></strong> file, add a simple template:</p><pre>import { Component, Input } from &#39;@angular/core&#39;;<br><br>@Component({<br>  selector: &#39;app-hello-world&#39;,<br>  template: `&lt;h1&gt;Hello, {{name}}!&lt;/h1&gt;`,<br>  styles: []<br>})<br>export class HelloWorldComponent {<br>  @Input() name: string = &#39;World&#39;;<br>}</pre><p>Next, modify the <strong><em>app.module.ts </em></strong>to convert the component into a custom element:</p><pre>import { BrowserModule } from &#39;@angular/platform-browser&#39;;<br>import { NgModule, Injector } from &#39;@angular/core&#39;;<br>import { createCustomElement } from &#39;@angular/elements&#39;;<br>import { HelloWorldComponent } from &#39;./hello-world/hello-world.component&#39;;<br>import { DOCUMENT } from &#39;@angular/common&#39;;<br><br>@NgModule({<br>  declarations: [HelloWorldComponent],<br>  imports: [BrowserModule],<br>  providers: [],<br>  entryComponents: [HelloWorldComponent],<br>})<br>export class AppModule {<br>  constructor(private injector: Injector, private document: Document) {}<br><br>  ngDoBootstrap() {<br>    const helloElement = createCustomElement(HelloWorldComponent, { injector: this.injector });<br>    customElements.define(&#39;hello-world&#39;, helloElement);<br>  }<br>}</pre><blockquote><strong>createCustomElement</strong>: Converts the “HelloWorldComponent” into web component</blockquote><blockquote><strong>ngDoBootstrap</strong>: Angular doesn’t automatically bootstrap a component in this approach, so we use this method to manually define our custom element.</blockquote><p>Since Angular Elements are not supported natively by some browsers, we include the polyfill by updating the <strong><em>polyfill.ts</em></strong> file:</p><pre>import &#39;document-register-element&#39;;</pre><h4>Building the Angular Element</h4><p>Next, build the project and extract the JavaScript file that contains our custom element.</p><pre>ng build --output-hashing=none --prod</pre><p>This generates files in the <strong><em>dist/micro-frontend</em></strong>folder. You will need the <strong><em>main.js,</em></strong> <strong><em>polyfill.ts</em></strong> and runtime.js files.</p><h4>Using the Micro Frontend in the Core App</h4><p>Now, go back to the <strong>core-app</strong> (the host application).</p><p>In the <strong><em>index.html </em></strong>of the <strong>core-app</strong>, include the built files from the micro frontend:</p><pre>&lt;!DOCTYPE html&gt;<br>&lt;html lang=&quot;en&quot;&gt;<br>&lt;head&gt;<br>  &lt;meta charset=&quot;UTF-8&quot;&gt;<br>  &lt;meta name=&quot;viewport&quot; content=&quot;width=device-width, initial-scale=1.0&quot;&gt;<br>  &lt;title&gt;Core App with Micro Frontend&lt;/title&gt;<br>&lt;/head&gt;<br>&lt;body&gt;<br>  &lt;hello-world name=&quot;Diwakar&quot;&gt;&lt;/hello-world&gt;<br><br>  &lt;script src=&quot;assets/micro-frontend/runtime.js&quot;&gt;&lt;/script&gt;<br>  &lt;script src=&quot;assets/micro-frontend/polyfills.js&quot;&gt;&lt;/script&gt;<br>  &lt;script src=&quot;assets/micro-frontend/main.js&quot;&gt;&lt;/script&gt;<br>&lt;/body&gt;<br>&lt;/html&gt;</pre><p>This includes the JavaScript files for the micro frontend into the core app.</p><p>Make sure to move the files from<strong><em> dist/micro-frontend </em></strong>to <strong><em>src/assets/micro-frontend</em></strong> in the core app so they are accessible.</p><h4>Serving the Application</h4><p>Run the core app using Angular CLI:</p><pre>ng serve</pre><p>Visit <a href="http://localhost:4200"><strong><em>http://localhost:4200</em></strong></a><strong><em> </em></strong>and you should see the custom Angular Element (micro frontend) rendering inside the core app. The <strong><em>hello-world.component.ts </em></strong>should display:</p><pre>Hello, Diwakar!</pre><h4>Explanation</h4><blockquote><strong>Micro Frontend</strong>:<em> We split the app into independent parts. Here, the </em><strong>hello-world.component.ts<em> </em></strong><em>is a simple micro frontend that can be developed and deployed separately.</em></blockquote><blockquote><em>Angular Elements: The hello-world.component.ts is converted into a custom element using Angular Elements. This allows it to be embedded in any web application (not just Angular apps).</em></blockquote><blockquote><strong>Loose Coupling</strong>:<em> The core app is loosely coupled with the micro frontend. You can replace or update the micro frontend independently.</em></blockquote><h4>Why Angular Elements?</h4><blockquote><strong>Interoperability</strong>: <em>Angular Elements are web components, meaning they can be used with other frameworks like React, Vue, or even plain HTML.</em></blockquote><blockquote><strong>Micro Frontend Architecture</strong>: <em>You can build self-contained parts of your application and independently deploy them, improving scalability and maintainability.</em></blockquote><h4>Conclusion</h4><p>In this article, we explored how to build a micro frontend using Angular Elements in Angular v16. This approach helps in creating highly scalable, independent modules that can be developed and deployed separately. Angular Elements allows the integration of Angular components into other frameworks seamlessly, making it a powerful tool for implementing Micro Frontends.</p><p>By following this guide, you can start developing micro frontends and boost your application’s scalability while keeping it modular and maintainable.</p><p>Note — like, shares , and subscribe if you want such content to be published. Happy Learning 😊</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c940f68e1d3c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A Beginner’s Guide to Web Components: Building Reusable, Custom Elements for the Web]]></title>
            <link>https://medium.com/@diwakarsingh6853/a-beginners-guide-to-web-components-building-reusable-custom-elements-for-the-web-ee168fcefa1f?source=rss-ef27431e21e------2</link>
            <guid isPermaLink="false">https://medium.com/p/ee168fcefa1f</guid>
            <category><![CDATA[custom-elements]]></category>
            <category><![CDATA[shadow-dom]]></category>
            <category><![CDATA[web-components]]></category>
            <dc:creator><![CDATA[Diwakar Kumar]]></dc:creator>
            <pubDate>Sat, 07 Sep 2024 17:39:13 GMT</pubDate>
            <atom:updated>2024-09-07T17:39:13.619Z</atom:updated>
            <content:encoded><![CDATA[<p>As web developers, one of the golden rules we follow is <strong>reusability</strong> — writing code once and using it in multiple places. However, when it comes to creating custom user interfaces, this can get tricky. How do we ensure that our custom HTML, CSS, and JavaScript don’t interfere with the rest of our page? How can we package complex features into neat, reusable blocks?</p><p>The answer lies in <strong>Web Components</strong>.</p><p>Web Components are a set of technologies that help you build <strong>custom, reusable HTML elements</strong>. Whether it’s a fancy button or a complete user interface, Web Components allow you to encapsulate everything within a single, modular element. Let’s explore how!</p><h4>Why Web Components?</h4><p>Imagine you’re working on a website that needs a special button with animations and specific behaviors. Without Web Components, you’d have to write the same HTML, CSS, and JavaScript every time you use the button. This not only clutters your code but also increases the chances of bugs and conflicts.</p><p><strong>Web Components solve this problem</strong> by letting you create a single, self-contained component — say, &lt;fancy-button&gt;—that can be reused anywhere on your site. You only write the code once, and you’re done!</p><p><strong>In short, Web Components:</strong></p><ul><li>Promote <strong>modularity</strong>: Your component’s code won’t mix with other parts of your page.</li><li>Enable <strong>reusability</strong>: Create once, use everywhere.</li><li>Provide <strong>maintainability</strong>: Make updates in one place, and they apply everywhere the component is used</li></ul><h4>Three Key Technologies Behind Web Components</h4><ol><li><strong>Custom Elements</strong><br>Think of this as creating your own HTML tags. Instead of being limited to standard tags like &lt;div&gt; or &lt;button&gt;, you can now create something like &lt;my-button&gt; and define its behavior using JavaScript.</li><li><strong>Shadow DOM</strong><br>The <strong>Shadow DOM</strong> isolates the component’s internal structure from the rest of the page. In simple terms, it creates a mini DOM tree just for your component, keeping its s</li><li><strong>HTML Templates</strong><br>The &lt;template&gt; element allows you to define HTML that isn’t displayed when the page first loads but can be inserted later. This is particularly useful when you want to define reusable structures for your components.</li></ol><h4>Breaking it Down: How to Create a Web Component</h4><p>Let’s walk through a simple example to see how we can create a web component.</p><h4>Step 1: Define a Custom Element</h4><p>First, we need to define the behavior of our custom element. We do this by creating a JavaScript class:</p><pre>class MyButton extends HTMLElement {<br>  connectedCallback() {<br>    this.innerHTML = `&lt;button&gt;Click Me!&lt;/button&gt;`;<br>  }<br>}</pre><p>This code defines a new “MyButton”component that will display a button with the text &quot;Click Me!&quot;</p><h4>Step 2: Register the Custom Element</h4><p>Next, we register our new custom element using the customElements.define() method. This step is crucial because it tells the browser, &quot;Hey, this is a valid HTML tag now!&quot;</p><pre>customElements.define(&#39;my-button&#39;, MyButton);</pre><h4>Step 3: Use the Custom Element</h4><p>Now you can use &lt;my-button&gt; anywhere in your HTML just like a normal tag:</p><pre>&lt;my-button&gt;&lt;/my-button&gt;</pre><h4>Digging Deeper: Using Shadow DOM for Encapsulation</h4><p>One of the most powerful features of Web Components is the <strong>Shadow DOM</strong>. It ensures that the styles and scripts within a component are completely isolated from the rest of the page.</p><h4>Example:</h4><p>Let’s say you want to create a styled button, but you don’t want the button’s styles to affect (or be affected by) other parts of the page. You can use Shadow DOM to encapsulate the button’s styles:</p><pre>class MyButton extends HTMLElement {<br>  constructor() {<br>    super();<br>    const shadow = this.attachShadow({ mode: &#39;open&#39; });<br>    shadow.innerHTML = `<br>      &lt;style&gt;<br>        button {<br>          background-color: blue;<br>          color: white;<br>          padding: 10px;<br>          border-radius: 5px;<br>        }<br>      &lt;/style&gt;<br>      &lt;button&gt;My Button&lt;/button&gt;<br>    `;<br>  }<br>}</pre><p>In this case, the button’s style is contained within its Shadow DOM, so it won’t affect other buttons on your page, and no external styles will accidentally modify it.</p><h4>HTML Templates and Slots: Adding Flexibility to Your Components</h4><p>Sometimes, you’ll want to create a template for your component and reuse it multiple times. This is where the &lt;template&gt; and &lt;slot&gt; elements come in handy.</p><ul><li><strong>&lt;template&gt;</strong>: Defines HTML that isn’t rendered right away but can be inserted when needed.</li><li><strong>&lt;slot&gt;</strong>: Acts like a placeholder, allowing external content to be passed into your component.</li></ul><h4>Example:</h4><p>Here’s how you can use a &lt;template&gt; to create a reusable structure for a modal window:</p><pre>&lt;template id=&quot;modal-template&quot;&gt;<br>  &lt;div class=&quot;modal&quot;&gt;<br>    &lt;slot&gt;&lt;/slot&gt;<br>  &lt;/div&gt;<br>&lt;/template&gt;</pre><p>With the &lt;slot&gt; element, you can dynamically insert content into the modal, making it flexible and reusable.</p><h4>Lifecycle Callbacks: Controlling Your Component’s Behavior</h4><p>Web Components come with built-in lifecycle callbacks that allow you to hook into different phases of the component’s life:</p><ul><li><strong>connectedCallback()</strong>: Triggered when the component is added to the DOM.</li><li><strong>disconnectedCallback()</strong>: Triggered when the component is removed from the DOM.</li><li><strong>attributeChangedCallback()</strong>: Fired when an attribute changes on the component.</li></ul><p>These hooks give you precise control over how your component behaves at every stage of its existence.</p><h4>Conclusion: Why Web Components Are the Future of Front-End Development</h4><p>Web Components provide a way to create reusable, encapsulated custom elements that work across frameworks and libraries. This makes them perfect for building modular, maintainable user interfaces. By mastering Web Components, you’ll write cleaner, more efficient code and have an easier time managing large web projects.</p><p>Whether you’re building a custom button, a modal, or an entire user interface, <strong>Web Components are the key to creating powerful, reusable components</strong>.</p><p>So why not start today? Build your first Web Component and make your code more modular, maintainable, and future-proof!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ee168fcefa1f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding Angular Micro-Frontends with Module Federation]]></title>
            <link>https://medium.com/@diwakarsingh6853/understanding-angular-micro-frontends-with-module-federation-b522434ef558?source=rss-ef27431e21e------2</link>
            <guid isPermaLink="false">https://medium.com/p/b522434ef558</guid>
            <category><![CDATA[webpack]]></category>
            <category><![CDATA[angular]]></category>
            <category><![CDATA[micro-frontends]]></category>
            <category><![CDATA[front-end-development]]></category>
            <dc:creator><![CDATA[Diwakar Kumar]]></dc:creator>
            <pubDate>Sat, 07 Sep 2024 16:17:22 GMT</pubDate>
            <atom:updated>2024-09-07T16:17:22.975Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*rNyA4ZNm9ngmKlK7" /><figcaption>Photo by <a href="https://unsplash.com/@casparrubin?utm_source=medium&amp;utm_medium=referral">Caspar Camille Rubin</a> on <a href="https://unsplash.com?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h4><strong>What is micro-frontend ?</strong></h4><p>Micro-frontends are a way to break down a large frontend application into smaller, independently deployable modules, similar to microservices on the backend. Angular micro-frontends use <strong>Webpack 5’s Module Federation</strong> feature to enable this architecture. Module Federation allows multiple teams to build and deploy features in isolation while composing them together at runtime.</p><p>In this article, we’ll explore how to achieve micro-frontends in Angular using Module Federation, with practical code snippets and explanations.</p><h4>Why Micro-Frontends?</h4><p>Micro-frontends bring several benefits to modern web development:</p><ul><li><strong>Independent Deployment:</strong> Teams can build, test, and deploy individual parts of the frontend independently.</li><li><strong>Better Scalability:</strong> Teams can work on their domain-specific features without interference from other teams.</li><li><strong>Technology Agnostic:</strong> Different micro-frontends can use different frameworks.</li></ul><h4>What is Module Federation?</h4><p>Module Federation is a feature in Webpack 5 that allows multiple applications to share code or load remote code at runtime. This is especially useful for micro-frontends, as it allows one Angular application to load modules from another application seamlessly.</p><h4>How to Implement Angular Micro-Frontends Using Module Federation</h4><p>We will break the setup into two parts:</p><ol><li><strong>Host Application</strong>: The main shell that loads different micro-frontends.</li><li><strong>Remote Applications</strong>: Individual Angular micro-frontend apps that are federated into the host.</li></ol><h4>Step 1: Setup the Angular Applications</h4><p>First, create two Angular applications:</p><p>One for the <strong>Host</strong> application (the shell).</p><p>One for the <strong>Remote</strong> application (the micro-frontend).</p><pre>ng new host-app<br>ng new remote-app</pre><h4>Step 2: Install Webpack Module Federation Plugin</h4><p>In both the <strong>host</strong> and <strong>remote</strong> applications, install Webpack 5 by running:</p><pre>npm install @angular-architects/module-federation --save</pre><h4>Step 3: Configure Module Federation for Remote Application</h4><p>In the remote-app, configure the webpack.config.js for Module Federation.</p><p>Create a new webpack.config.js file in the remote-app:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_eI6mbWf_GqbnjhsGrLLvg.png" /><figcaption>webpack.config.js for remote-app</figcaption></figure><p>In the above configuration:</p><ul><li><strong><em>name</em></strong><em>: The unique name of the remote application.</em></li><li><strong><em>filename</em></strong><em>: The file that will be used to expose the remote component.</em></li><li><strong><em>exposes</em></strong><em>: The Angular component that you want to share with the host application.</em></li><li><strong><em>shared</em></strong><em>: The libraries that will be shared between the host and remote apps.</em></li></ul><h4>Step 4: Configure Module Federation for Host Application</h4><p>In the host-app, create a similar webpack.config.js file:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vNksKv72VcXxFf0Mog57QQ.png" /><figcaption>webpack.config.js for host-app</figcaption></figure><p>In above configuration:</p><ul><li><strong><em>remotes</em></strong><em>: Specifies the remote applications to be consumed by the host application. The remote URL is where the </em><em>remoteEntry.js is located.</em></li><li><strong><em>shared</em></strong><em>: This ensures that shared libraries (like Angular core libraries) are only loaded once.</em></li></ul><h4>Step 5: Configure Angular Router to Load Remote Modules</h4><p>To dynamically load the remote module, use Angular’s router in the host-app. Open the app-routing.module.ts in the host-app and add a route to the remote component:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-cb_dWkrlxG3vTCcE0kjbA.png" /><figcaption>app-routing.module.ts in host-app</figcaption></figure><h4>Step 6: Expose Remote Components</h4><p>In the remote-app, create the remote.component.ts file to define the component you want to expose:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*asfvWLpZHSsHq27c-4ap_A.png" /><figcaption>remote.component.ts</figcaption></figure><p>Then, ensure that this component is part of an Angular module so that it can be properly exposed.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HOpUzrW0PVfzLyk4opDUlw.png" /><figcaption>app.module.ts in remote-app</figcaption></figure><h4>Step 7: Run Both Applications</h4><p>Start both applications with different ports.</p><p>For the <strong>remote-app</strong>, start it on localhost:4201 and For the <strong>host-app</strong>, run it on localhost:4200</p><pre>remote app - ng serve --port 4201<br><br>host-app - ng serve --port 4200<br></pre><p>Now, when you visit http://localhost:4200/remote, the remote component from remote-app should be displayed inside the host application.</p><h3>Final Thoughts</h3><p>Using Angular with Webpack 5’s Module Federation allows you to develop and deploy micro-frontends efficiently. This approach promotes decoupling, enabling independent teams to develop their own features, release them independently, and improve scalability.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b522434ef558" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Copy of object in js | Deep copy vs Shallow copy]]></title>
            <link>https://medium.com/@diwakarsingh6853/copy-of-object-in-js-deep-copy-vs-shallow-copy-59873bea133d?source=rss-ef27431e21e------2</link>
            <guid isPermaLink="false">https://medium.com/p/59873bea133d</guid>
            <dc:creator><![CDATA[Diwakar Kumar]]></dc:creator>
            <pubDate>Fri, 19 Jan 2024 04:53:28 GMT</pubDate>
            <atom:updated>2024-01-19T05:29:56.702Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*n-HlmgVsOoBVIlOd" /><figcaption>Photo by <a href="https://unsplash.com/@blakeconnally?utm_source=medium&amp;utm_medium=referral">Blake Connally</a> on <a href="https://unsplash.com?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>Cloning Objects in JavaScript: A Simple Guide</h3><p>JavaScript objects, as versatile data structures, play a crucial role in handling various data types through key-value pairs. Often, you may find the need to modify values or add properties to an object. However, when such modifications are involved, it’s essential to be mindful of object referencing to avoid unintended consequences.</p><p>Consider the following scenario<em>:</em></p><pre>const userDetails = {<br>  name: &quot;John Doe&quot;,<br>  age: 20,<br>  verified: false<br>};</pre><blockquote>In JavaScript, objects are reference types. A common mistake occurs when attempting to clone or copy an object using the equality operator (=). Let&#39;s explore why this can lead to unexpected results and delve into three effective methods for cloning or coping objects.</blockquote><p><strong>The Pitfall of Reference Types</strong></p><pre>const newUser = userDetails;<br>newUser.name = &quot;Jane Doe&quot;;<br><br>console.log(userDetails.name); // Outputs: &#39;Jane Doe&#39; <br><br>// It modify the userDetails &#39;name&#39; property since both object<br>//  newUser and userDetails points to same reference</pre><p>Modifying newUser inadvertently alters the original userDetails object due to object referencing. This is not ideal, especially when the intention is to create an independent copy.</p><p><strong>So what is solution for this 🧐</strong></p><p>we usually use three approaches to solve this in js.</p><ol><li><strong>Spread Operator(ES6):</strong></li></ol><pre>let cloneUser = { ...userDetails };<br><br>cloneUser.name = &quot;Jane Doe&quot;;<br><br>console.log(userDetails.name); // Outputs: &#39;John Doe&#39;<br>console.log(cloneUser.name); // Outputs: &#39;Jane Doe&#39;<br><br>// Worked fine but catch here is it will only create shallow copy<br>// Will discuss shallow copy in below section</pre><p><strong>2. Object.assign() Method:</strong></p><pre>let cloneUser = Object.assign({}, userDetails);<br><br>cloneUser.name = &quot;Jane Doe&quot;;<br><br>console.log(userDetails.name); // Outputs: &#39;John Doe&#39;<br>console.log(cloneUser.name); // Outputs: &#39;Jane Doe&#39;<br><br>// Worked fine but catch here is it will only create shallow copy<br>// Will discuss shallow copy in below section</pre><p><strong>3. JSON.parse() Method:</strong></p><pre>let cloneUser = JSON.parse(JSON.stringify(userDetails));<br><br>cloneUser.name = &quot;Jane Doe&quot;;<br><br>console.log(userDetails.name); // Outputs: &#39;John Doe&#39;<br>console.log(cloneUser.name); // Outputs: &#39;Jane Doe&#39;<br><br>// Worked fine but catch here is it wont work with properties like function<br>// symbol and undefined value <br>// Will discuss this in below post</pre><h3>Understanding the shallow copy</h3><blockquote>Both Object.assign and (…) spread operator create shallow copy</blockquote><pre>const userDetails = {<br>  name: &quot;John Doe&quot;,<br>  age: 14,<br>  verified: false,<br>  status: {<br>    enrolled: false<br>  }<br>};<br><br>// let cloneUser = { ...userDetails };<br>let cloneUser = Object.assign({}, userDetails);<br>cloneUsers.status.enrolled = true;<br><br>console.log(cloneUser.status.enrolled); // Outputs: true<br>console.log(userDetails.status.enrolled); // Outputs: true<br><br>// As seen status for enarollment changed for both the object as nested object <br>// properies not copied and its pass by reference still </pre><h3>JSON.parse() Method for Deep Cloning</h3><p>For more complex objects with nested structures, JSON.parse() along with JSON.stringify() provides a solution:</p><pre><br>const userDetails = {<br>  name: &quot;John Doe&quot;,<br>  age: 14,<br>  verified: false,<br>  status: {<br>    enrolled: false<br>  }<br>};<br><br>let cloneUser = JSON.parse(JSON.stringify(userDetails));<br><br>cloneUsers.status.enrolled = true;<br><br>console.log(cloneUser.status.enrolled); // Outputs: true<br>console.log(userDetails.status.enrolled); // Outputs: false<br><br>// Wow 😎 It worked and solved the problem of nested object 🥳</pre><p>Wait ………………… be cautious when usingJSON.parse() with functions, symbols, or undefined values, as they may result in data loss</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/938/1*Sng89LHEPE3w04y0p4XRPw.png" /></figure><pre>const userDetails = {<br>  name: &quot;John Doe&quot;,<br>  age: 14,<br>  status: {<br>    verified: false,<br>    method: Symbol(),<br>    title: undefined<br>  }<br>};<br><br>let cloneUser = JSON.parse(JSON.stringify(userDetails));<br><br>console.log(cloneUser); // output is as shown above in attached screenshot<br>// and this is how we lost method , symbol properties<br></pre><h3><strong>Final Solution</strong></h3><h4>Lodash: The Ideal Solution</h4><pre>const userDetails = {<br>  name: &quot;John Doe&quot;,<br>  age: 14,<br>  status: {<br>    verified: false,<br>    method: Symbol(),<br>    title: undefined<br>  }<br>};<br><br>console.log(_.cloneDeep(userDetails));</pre><p>Using similar libraries ensures comprehensive deep cloning, addressing the challenges posed by nested objects and various data types.</p><h4>Custom Deep Cloning Method</h4><pre>function deepClone(obj) {<br>  if (obj === null || typeof obj !== &quot;object&quot;) {<br>    return obj;<br>  }<br><br>  const clone = Array.isArray(obj) ? [] : {};<br><br>  for (const key in obj) {<br>    if (obj.hasOwnProperty(key)) {<br>      clone[key] = deepClone(obj[key]);<br>    }<br>  }<br><br>  return clone;<br>}<br><br>const userDetails = {<br>  name: &quot;John Doe&quot;,<br>  age: 14,<br>  status: {<br>    verified: false,<br>    method: Symbol(),<br>    title: undefined<br>  }<br>};<br><br>let cloneUser = deepClone(userDetails);</pre><p>This custom deep cloning method provides a tailored solution for handling nested objects and various data types.</p><p>Final word:-</p><blockquote>Cloning objects in JavaScript demands careful consideration of object referencing and the nature of the data being manipulated. While methods like the spread operator, Object.assign(), and JSON.parse() offer solutions, their limitations underscore the importance of using dedicated libraries like Lodash or underscore or jQuery or crafting custom deep cloning methods. Choose the approach that aligns with your project&#39;s requirements, ensuring data integrity and preventing unexpected side effects</blockquote><p>Happy Learning 👏 Subscribe for more such stories 😊</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=59873bea133d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Polyfill for call method in js]]></title>
            <link>https://medium.com/@diwakarsingh6853/polyfill-for-call-method-in-js-76a1c625ff9e?source=rss-ef27431e21e------2</link>
            <guid isPermaLink="false">https://medium.com/p/76a1c625ff9e</guid>
            <dc:creator><![CDATA[Diwakar Kumar]]></dc:creator>
            <pubDate>Wed, 17 Jan 2024 04:42:21 GMT</pubDate>
            <atom:updated>2024-01-17T04:42:21.648Z</atom:updated>
            <content:encoded><![CDATA[<p>This will show how to add custom call method in javascript</p><figure><img alt="polyfill for call in js" src="https://cdn-images-1.medium.com/max/1024/0*cNQwX1ZLv0ONBCYw" /><figcaption>Photo by <a href="https://unsplash.com/@gamell?utm_source=medium&amp;utm_medium=referral">Joan Gamell</a> on <a href="https://unsplash.com?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><pre>Function.prototype.customCall = function(context, ...args) {<br>    // Ensure that the context is an object or use the global object (window in the browser) if not provided.<br>    context = context || window;<br><br>    // Generate a unique identifier for the function to avoid naming conflicts on the context object.<br>    const uniqueID = &#39;fn_&#39; + Date.now();<br>    <br>    // Attach the original function to the context using the unique identifier.<br>    context[uniqueID] = this;<br><br>    // Invoke the function with the specified context and arguments.<br>    const result = context[uniqueID](...args);<br><br>    // Clean up by removing the temporarily attached function from the context object.<br>    delete context[uniqueID];<br><br>    // Return the result of the function invocation.<br>    return result;<br>  };<br>}</pre><p><strong>Define the </strong><strong>customCall method:</strong></p><p>This line adds the customCall method to the Function.prototype. The method takes two parameters: context (the object to which the this keyword should refer) and args (an array of arguments to be passed to the function).</p><pre>Function.prototype.customCall = function(context, ...args) {<br><br>// context is object to which this keyword will refers and args is arguments<br><br>function showFullName(lastName) {<br>  console.log(`I am ${this.firstName} ${lastName}`);<br>}<br><br>const person = {<br>  firstName: &#39;Diwakar&#39;<br>}<br><br>showFullName.customCall(person, &#39;Kumar&#39;) // I am Diwakar Kumar<br><br>// Here &#39;person&#39; is context to customCall method<br>// &#39;kumar&#39; is argument passed to customCall method </pre><blockquote>This polyfill essentially mimics the behavior of the native call method, allowing you to call a function with a specific context and arguments.</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=76a1c625ff9e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Javascript Object Properties]]></title>
            <link>https://medium.com/@diwakarsingh6853/javascript-object-properties-9a303cec4f23?source=rss-ef27431e21e------2</link>
            <guid isPermaLink="false">https://medium.com/p/9a303cec4f23</guid>
            <dc:creator><![CDATA[Diwakar Kumar]]></dc:creator>
            <pubDate>Tue, 16 Jan 2024 16:24:42 GMT</pubDate>
            <atom:updated>2024-01-16T16:24:42.103Z</atom:updated>
            <content:encoded><![CDATA[<h3>Demystifying JavaScript Object Properties: Flags and Descriptors</h3><p>As JavaScript developers, we often work with objects and their properties. Properties not only hold values but also come with special attributes, known as “flags” or descriptors. In this article, we’ll unravel the concept of property flags and descriptors, exploring their significance and practical use cases.</p><h3>Understanding Property Flags</h3><ol><li><strong>Writable</strong>: If true, the value can be changed; otherwise, it&#39;s read-only.</li><li><strong>Enumerable</strong>: If true, the property is listed in loops; otherwise, it remains hidden.</li><li><strong>Configurable: </strong>If true, the property can be deleted, and its attributes can be modified.</li></ol><h3>Accessing Property Descriptors</h3><p>To inspect these flags, we can use Object.getOwnPropertyDescriptor(obj, propertyName). It returns a property descriptor object containing the value and all the flags.</p><pre>let user = { name: &quot;Diwakar&quot; };<br>let descriptor = Object.getOwnPropertyDescriptor(user, &#39;name&#39;);<br><br>console.log(descriptor);<br>/* Output:<br>{<br>  &quot;value&quot;: &quot;Diwakar&quot;,<br>  &quot;writable&quot;: true,<br>  &quot;enumerable&quot;: true,<br>  &quot;configurable&quot;: true<br>}<br>*/</pre><h3>Modifying Flags with defineProperty</h3><p>To change flags, we use Object.defineProperty(obj, propertyName, descriptor). It can update existing flags or create a new property with specified values and flags.</p><pre>let user = {};<br>Object.defineProperty(user, &quot;name&quot;, { value: &quot;Diwakar&quot; });<br><br>let descriptor = Object.getOwnPropertyDescriptor(user, &#39;name&#39;);<br>console.log(descriptor);<br>/* Output:<br>{<br>  &quot;value&quot;: &quot;Diwakar&quot;,<br>  &quot;writable&quot;: false,<br>  &quot;enumerable&quot;: false,<br>  &quot;configurable&quot;: false<br>}<br>*/</pre><h3>Exploring Flag Effects</h3><h4>Non-writable Property</h4><p>Making a property non-writable prevents its value from being reassigned.</p><pre>let user = { name: &quot;Diwakar&quot; };<br>Object.defineProperty(user, &quot;name&quot;, { writable: false });<br><br>user.name = &quot;Pete&quot;; // Error: Cannot assign to read-only property &#39;name&#39;</pre><h4>Non-enumerable Property</h4><p>Setting a property as non-enumerable excludes it from loops and Object.keys.</p><pre>let user = { firstName: &quot;Diwakar&quot;, lastName: &quot;kumar&quot;};<br>Object.defineProperty(user, &quot;lastName&quot;, { enumerable: false });<br><br>for (let key in user) console.log(key); // Output: firstName<br>console.log(Object.keys(user)); // Output: [&quot;firstName&quot;]</pre><h4>Non-configurable Property</h4><p>A non-configurable property can’t be deleted, and its attributes can’t be modified.</p><pre>let user = { name: &quot;Diwakar&quot; };<br>Object.defineProperty(user, &quot;name&quot;, { configurable: false });<br><br>user.name = &quot;Mohit&quot;; // Works fine<br>delete user.name; // Error</pre><h3>Object Property Management</h3><p>Object.defineProperties(obj, descriptors) allows defining multiple properties at once.</p><p>Object.getOwnPropertyDescriptors(obj) provides all property descriptors, useful for creating a deep clone of an object.</p><pre>let clone = Object.defineProperties({}, Object.getOwnPropertyDescriptors(obj));</pre><h3>Sealing Objects</h3><p>To control access to the entire object, we have global methods:</p><ul><li>Object.preventExtensions(obj): Forbids adding new properties.</li><li>Object.seal(obj): Forbids adding/removing properties. (configurable = ‘false’)</li><li>Object.freeze(obj): Forbids adding/removing/changing properties. (writable = ‘false’ and configurable = ‘false’)</li></ul><pre>let user = { name: &quot;Diwakar&quot; };<br><br>Object.seal(user);<br><br>user.name = &quot;Mohit&quot;; // Work<br>delete user.name; // Error<br><br>Object.freeze(user);<br><br>user.name = &quot;Rohit&quot;; // Error<br>delete user.name; // Error</pre><p>Understanding property flags and descriptors enhances our ability to control and protect object properties in JavaScript. Whether it’s making properties read-only, non-enumerable, or non-configurable, these features empower developers to create robust and secure code.</p><blockquote>In conclusion, dive deeper into JavaScript object properties, explore the flags, and leverage descriptors to master the art of object manipulation. Happy coding!</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9a303cec4f23" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Javascript ‘this’]]></title>
            <link>https://medium.com/@diwakarsingh6853/javascript-this-e4f20f86a5da?source=rss-ef27431e21e------2</link>
            <guid isPermaLink="false">https://medium.com/p/e4f20f86a5da</guid>
            <dc:creator><![CDATA[Diwakar Kumar]]></dc:creator>
            <pubDate>Tue, 16 Jan 2024 15:48:03 GMT</pubDate>
            <atom:updated>2024-01-17T09:07:18.705Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Y4xnNmuxkFf-SKEq" /><figcaption>Photo by <a href="https://unsplash.com/@gamell?utm_source=medium&amp;utm_medium=referral">Joan Gamell</a> on <a href="https://unsplash.com?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>Demystifying the this Keyword in JavaScript</h3><p>Understanding the behavior of the this keyword is a fundamental aspect of JavaScript, influencing how functions and methods behave in various contexts. In this article, we&#39;ll explore the intricacies of this through practical examples and scenarios.</p><h3>1. The this in Object Methods</h3><p>Consider the following counter object:</p><pre>let counter = {<br>  count: 0,<br>  next: function () {<br>    // &#39;this&#39; represents the counter object<br>    return ++this.count;<br>  },<br>};<br><br>counter.next(); // Returns: 1</pre><p>In this example, when next is invoked, this refers to the counter object. Understanding the context in which a function is called is crucial for interpreting the value of this.</p><h3>2. Global Object and Strict Mode</h3><p>In non-strict mode, if a function is called without an explicit context, this defaults to the global object (usually window in a browser).</p><pre>function show() {<br>  console.log(this === window); // true<br>}<br><br>show();</pre><p>However, in strict mode, JavaScript sets this inside a function to undefined:</p><pre>&quot;use strict&quot;;<br><br>function show() {<br>  console.log(this === undefined); // true<br>}<br><br>show();</pre><h3>3. Method Invocation and this</h3><p>When a method of an object is called, this is set to the object that owns the method. Consider the following example with a car object:</p><pre>let car = {<br>  brand: &#39;Tata&#39;,<br>  getBrand: function () {<br>    return this.brand;<br>  }<br>}<br><br>console.log(car.getBrand()); // Output: Tata<br><br>let brand = car.getBrand;<br>console.log(brand()); // Output: undefined<br><br>let newBrand = car.getBrand.bind(car);<br>console.log(newBrand()); // Output: Tata</pre><p>In the first call to getBrand, this refers to the car object. However, when the method is assigned to the brand variable, this loses its context, resulting in undefined. Using bind to explicitly set this to the car object resolves this issue.</p><p>Understanding the behavior of this is crucial for writing robust and predictable JavaScript code. Whether it&#39;s working with objects, functions, or methods, being mindful of context ensures that this behaves as expected.</p><p>In conclusion, the this keyword in JavaScript is a dynamic aspect that requires attention to detail. By grasping its behavior in different scenarios, developers can write more effective and reliable code</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e4f20f86a5da" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>