<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>DEV Community: vikash tiwary</title>
    <description>The latest articles on DEV Community by vikash tiwary (@vt2730).</description>
    <link>https://dev.to/vt2730</link>
    <image>
      <url>https://media2.dev.to/dynamic/image/width=90,height=90,fit=cover,gravity=auto,format=auto/https:%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F675795%2F4fae2fcd-b398-491b-b4c8-4ee969725c63.jpeg</url>
      <title>DEV Community: vikash tiwary</title>
      <link>https://dev.to/vt2730</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://dev.to/feed/vt2730"/>
    <language>en</language>
    <item>
      <title>Design Patterns Cheat Sheet.</title>
      <dc:creator>vikash tiwary</dc:creator>
      <pubDate>Tue, 09 Jan 2024 07:11:21 +0000</pubDate>
      <link>https://dev.to/vt2730/design-patterns-cheat-sheet-3o53</link>
      <guid>https://dev.to/vt2730/design-patterns-cheat-sheet-3o53</guid>
      <description>&lt;p&gt;&lt;strong&gt;Creational Patterns ✍️:&lt;/strong&gt;&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;Abstract Factory:&lt;/strong&gt; Creates related objects without specifying the concrete classes. For example -&amp;gt; A car manufacturing plant that produces multiple models and brands of cars without specifying the concrete classes of each part.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;Builder:&lt;/strong&gt; Separates the construction of complex objects from their representation. For example -&amp;gt;A pizza restaurant that lets customers build their own pizza by selecting toppings, crust, and sauce separately.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;Factory Method:&lt;/strong&gt; Defines an interface for creating objects, but lets subclasses decide which class to instantiate. For example -&amp;gt; A car dealership that sells different types of cars and lets customers choose which brand and model they prefer.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;Prototype:&lt;/strong&gt; Creates new objects by cloning an existing object. For example -&amp;gt; A graphic design software that lets users clone an existing object and modify it to create a new design.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;Singleton:&lt;/strong&gt; Ensures only one instance of a class is created and provides a global point of access to it. For example -&amp;gt; A logging system that ensures only one instance is created and used throughout the application to manage log messages.&lt;/p&gt;&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;&lt;strong&gt;Structural Patterns ✍️:&lt;/strong&gt;&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;Bridge:&lt;/strong&gt; Separates an object’s interface from its implementation. For example -&amp;gt; A camera that separates its user interface from its hardware components, allowing users to adjust settings and capture images separately.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;Composite:&lt;/strong&gt; Composes objects into tree structures to represent part-whole hierarchies. For example -&amp;gt; A file manager that displays files and folders in a tree structure, allowing users to navigate and manage them hierarchically.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;Decorator:&lt;/strong&gt; Dynamically adds responsibilities to an object. For example -&amp;gt; A coffee shop that offers a variety of flavors and toppings to add to a basic coffee drink.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;Facade:&lt;/strong&gt; Provides a unified interface to a set of interfaces in a subsystem. For example -&amp;gt; An online shopping site that provides a simplified interface to a complex e-commerce system.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;Flyweight:&lt;/strong&gt; Shares objects to reduce memory usage. For example -&amp;gt; A game that shares textures and sprites to reduce memory usage and improve performance.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;Proxy:&lt;/strong&gt; Provides a placeholder for another object to control access to it. For example -&amp;gt; A user authentication system that provides a proxy interface to validate user credentials and control access to restricted resources.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;Adapter:&lt;/strong&gt; Converts the interface of a class into another interface that clients expect. For example -&amp;gt; A power adapter that converts the interface of a foreign electrical device to match the interface of the socket.&lt;/p&gt;&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;&lt;strong&gt;Behavioral Patterns ✍️:&lt;/strong&gt;&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;Command:&lt;/strong&gt; Encapsulates a request as an object to allow its invocation at a later time. For example -&amp;gt; A TV remote control that sends commands to a TV set, allowing users to turn it on/off, change channels, and adjust the volume.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;Interpreter:&lt;/strong&gt; Defines a representation for a grammar of a language and provides an interpreter for it. For example -&amp;gt; A language translation service that provides an interpreter to translate text from one language to another.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;Iterator:&lt;/strong&gt; Provides a way to access the elements of an aggregate object sequentially without exposing its underlying representation. For example -&amp;gt; A music player that allows users to navigate through a playlist sequentially without exposing the underlying structure of the playlist.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;Mediator:&lt;/strong&gt; Defines an object that encapsulates how a set of objects interact. For example -&amp;gt; A chat application that allows users to send messages to each other through a centralized server.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;Memento:&lt;/strong&gt; Captures an object’s internal state to restore it later. For example -&amp;gt; A game that allows players to save and restore their game progress at any point in time.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;Observer:&lt;/strong&gt; Defines a one-to-many dependency between objects so that when one object changes state, all its dependents are notified and updated automatically. For example -&amp;gt; A weather app that notifies users of weather changes in real-time based on their location.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;State:&lt;/strong&gt; Allows an object to change its behavior when its internal state changes. For example -&amp;gt; A traffic light system that changes its behavior depending on the current state of traffic flow.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;Strategy:&lt;/strong&gt; Defines a family of algorithms, encapsulates each one, and makes them interchangeable. For example -&amp;gt; A payment system that offers different payment methods, such as credit card, PayPal, and bank transfer, and allows users to choose which one to use.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;Template Method:&lt;/strong&gt; Defines the skeleton of an algorithm in a method, allowing subclasses to redefine certain steps of the algorithm without changing its structure. For example -&amp;gt; A recipe app that provides a template for cooking a dish, allowing users to customize certain steps of the recipe.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;Visitor:&lt;/strong&gt; Separates an algorithm from an object structure by moving the algorithm into a separate object. For example -&amp;gt; A code editor that analyzes the syntax of a program and provides a visitor to detect and fix coding errors.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;Chain of Responsibility:&lt;/strong&gt; Allows multiple objects to handle a request. For example -&amp;gt; A customer service hotline that forwards customer complaints to multiple levels of support until they are resolved.&lt;/p&gt;&lt;/li&gt;
&lt;/ol&gt;

</description>
    </item>
    <item>
      <title>Implementing Lock Using Promise.</title>
      <dc:creator>vikash tiwary</dc:creator>
      <pubDate>Mon, 24 Jul 2023 13:11:18 +0000</pubDate>
      <link>https://dev.to/vt2730/implementing-lock-using-promise-4h71</link>
      <guid>https://dev.to/vt2730/implementing-lock-using-promise-4h71</guid>
      <description>&lt;p&gt;There are some (rare) cases when you want to forbid a block of code to be executed in “parallel,” or let’s say, that since JavaScript is single-threaded, you want to have more on the execution flow and force execution of a block of code to be sequential.&lt;/p&gt;

&lt;p&gt;&lt;em&gt;A really simple definition of a using a lock can be that, once a block of code acquires a lock, it becomes locked and no one else can run the same block until the lock is released regardless of the size of the block. It could be one line or 100.&lt;/em&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;interface Lock {
  await(): Promise&amp;lt;void&amp;gt;;

  acquire(): void;

  release(): void;
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;To get the lock, you first need to await for it, then acquire it, and finally release it once done.&lt;/p&gt;

&lt;p&gt;Implementing this with Promise is pretty straightforward. The await function needs to return a Promise which has been created by the acquire call, and resolved by the release call. The implementation also needs to initialize the Promise as resolved since the first one that needs to await for it does not have to be locked. This can be implemented as follows:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;class LockImpl implements Lock {
  private promise: Promise&amp;lt;void&amp;gt;;

  private resolve: (() =&amp;gt; void) | undefined;

  constructor() {
    this.promise = Promise.resolve(); //Line 7
    this.resolve = undefined;
  }

  await() {
    console.log("await lock");
    return this.promise; // Line 13
  }

  acquire() {
    console.log("acquire");
    // eslint-disable-next-line no-return-assign, no-promise-executor-return
    this.promise = new Promise&amp;lt;void&amp;gt;((resolve) =&amp;gt; (this.resolve = resolve)); //Line 19
  }

  release() {
    console.log("release");
    if (this.resolve) {
      this.resolve(); // Line 25
    }
  }
}
const lock = new LockImpl();

export default lock;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Here’s some explanations about what is happening in the Lock implementation:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Line 7: Create a resolved Promise&lt;/li&gt;
&lt;li&gt;Line 13, await(): Return the Promise. The consumer can await for it to be resolved&lt;/li&gt;
&lt;li&gt;Line 19, acquire(): instantiate a new Promise, and save the resolve reference in the lock instance&lt;/li&gt;
&lt;li&gt;Line 25, release(): resolve the Promise, unlock the current consumer block, and allow another block of code to acquire the lock.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Using it is as easy as awaiting the lock by calling await lock.await() , then locking the block by calling lock.acquire() and finally releasing it by calling lock.release(). Here’s the code:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import lock from "./lock";

const send = async (id: number) =&amp;gt; {
  await lock.await();
  lock.acquire();

  try {
    console.log("Calling", id);
  } catch (err) {
    console.log(err);
  } finally {
    lock.release();
  }
};

Promise.all(Array.from(Array(20), (v, k) =&amp;gt; k).map((v) =&amp;gt; send(v)));
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In the code above, the send function is expected to be called 20 times from a Promise.all call which ‘virtually’ make parallel calls since sendreturns a Promise.&lt;/p&gt;

&lt;p&gt;By using the Lock, we force the block between lock.acquire() and lock.release() to be called one after the other. This is pretty useless in the current example, but imagine if you replace line 8 with something more complex that takes time, shares a scope, or does anything you cannot control, like a third-party library, a remote service, etc.&lt;/p&gt;

&lt;p&gt;You can now force everyone calling send to wait until the previous call is complete, even if it has been called from several places at the same time, just by using a really simple Lock, based on a Promise and a resolve callback.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://codesandbox.io/s/broken-fire-5c9056?file=/src/index.ts"&gt;codesandbox example&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Using the web locks API&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Web Locks API is more powerful than just our Promise-based implementation. By using it, you can lock code running on the same origin, on multiple tabs, and even more on workers opening the door to create really advanced process control and coordination.&lt;/p&gt;

&lt;p&gt;The API is pretty simple and can be used as follows:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;navigator.locks.request("my_resource", async (lock) =&amp;gt; {
  // The lock has been acquired.
  await do_something();
  await do_something_else();
  // Now the lock will be released.
});
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;ol&gt;
&lt;li&gt;&lt;p&gt;Once the lock is acquired, the callback (async (lock) =&amp;gt; {}) will be executed. The callback is the block of code to be locked, which is something really clear. It does not force you to call acquire and release like we did in our implementation. Once the callback is executed, the next one can be, since the lock is released and can be acquired.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Notice the first parameter of the locks.request function, which is a string. This allows us to use locks from many places (tabs and workers) and also allows us to use the same lock name for different blocks, which is something more powerful than our single lock instance.&lt;/p&gt;&lt;/li&gt;
&lt;/ol&gt;




</description>
    </item>
    <item>
      <title>React: Virtualized List From Scratch</title>
      <dc:creator>vikash tiwary</dc:creator>
      <pubDate>Thu, 06 Apr 2023 08:22:02 +0000</pubDate>
      <link>https://dev.to/vt2730/react-virtualized-list-from-scratch-121j</link>
      <guid>https://dev.to/vt2730/react-virtualized-list-from-scratch-121j</guid>
      <description>&lt;p&gt;A virtualized list is a list that renders only a subset of its items and replaces the invisible items with placeholders. The virtualization technique can significantly improve the performance of rendering long lists by reducing the number of DOM nodes that need to be created and updated.&lt;/p&gt;

&lt;p&gt;To build a virtualized list from scratch, we will follow these steps:&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;1. Create a component for the list.&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;The first step in building a virtualized list is to create a component that represents the list. We can create a functional component that takes an array of items as a prop.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;function VirtualizedList({ items }) {
  return (
    &amp;lt;div&amp;gt;
      {items.map((item) =&amp;gt; (
        &amp;lt;div key={item.id}&amp;gt;{item.content}&amp;lt;/div&amp;gt;
      ))}
    &amp;lt;/div&amp;gt;
  );
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In this example, we use the map method to iterate over the items array and render each item as a div element. We also assign a unique key to each item to help React identify them.&lt;/p&gt;




&lt;p&gt;&lt;strong&gt;2. Render a subset of the list items.&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;The second step in building a virtualized list is to render only a subset of the list items. To achieve this, we need to know the height of each item and the height of the container that holds the list.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;function VirtualizedList({ items, itemHeight, containerHeight }) {
  const startIndex = Math.floor(scrollTop / itemHeight);
  const endIndex = Math.min(
    startIndex + Math.ceil(containerHeight / itemHeight),
    items.length
  );
  const visibleItems = items.slice(startIndex, endIndex);

return (
    &amp;lt;div style={{ height: `${items.length * itemHeight}px` }}&amp;gt;
      &amp;lt;div
        style={{
          position: "relative",
          height: `${visibleItems.length * itemHeight}px`,
          top: `${startIndex * itemHeight}px`,
        }}
      &amp;gt;
        {visibleItems.map((item) =&amp;gt; (
          &amp;lt;div key={item.id} style={{ height: `${itemHeight}px` }}&amp;gt;
            {item.content}
          &amp;lt;/div&amp;gt;
        ))}
      &amp;lt;/div&amp;gt;
    &amp;lt;/div&amp;gt;
  );
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In this updated example, we added the itemHeight and containerHeight props to the component. We also calculated the startIndex and endIndex based on the scrollTop, itemHeight, and containerHeight. The startIndex represents the index of the first visible item, and the endIndex represents the index of the last visible item.&lt;/p&gt;

&lt;p&gt;We then used the slice method to extract only the visible items from the items array. Finally, we rendered the visible items as div elements with a height of itemHeight. We also positioned the container using the top property, which is equal to startIndex * itemHeight.&lt;/p&gt;




&lt;p&gt;&lt;strong&gt;3. Replace the invisible items with placeholders.&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;The third step in building a virtualized list is to replace the invisible items with placeholders. This step is essential to maintain the correct height of the list and prevent the visible items from jumping when scrolling.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;function VirtualizedList({ items, itemHeight, containerHeight }) {
  const startIndex = Math.floor(scrollTop / itemHeight);
  const endIndex = Math.min(
    startIndex + Math.ceil(containerHeight / itemHeight),
    items.length
  );
  const visibleItems = items.slice(startIndex, endIndex);
  const invisibleItemsHeight =
    (startIndex + visibleItems.length - endIndex) * itemHeight;

  return (
    &amp;lt;div style={{ height: `${items.length * itemHeight}px` }}&amp;gt;
      &amp;lt;div
        style={{
          position: "relative",
          height: `${visibleItems.length * itemHeight}px`,
          top: `${startIndex * itemHeight}px`,
        }}
      &amp;gt;
        {visibleItems.map((item) =&amp;gt; (
          &amp;lt;div key={item.id} style={{ height: `${itemHeight}px` }}&amp;gt;
            {item.content}
          &amp;lt;/div&amp;gt;
        ))}
      &amp;lt;/div&amp;gt;
      &amp;lt;div style={{ height: `${invisibleItemsHeight}px` }} /&amp;gt;
    &amp;lt;/div&amp;gt;
  );
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In this updated example, we calculated the &lt;code&gt;invisibleItemsHeight&lt;/code&gt; by subtracting the height of the visible items from the height of the container. We then added an empty &lt;code&gt;div&lt;/code&gt; element with a height equal to &lt;code&gt;invisibleItemsHeight&lt;/code&gt; to replace the invisible items.&lt;/p&gt;




&lt;p&gt;&lt;strong&gt;4. Add scrolling functionality to the list.&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;The fourth and final step in building a virtualized list is to add scrolling functionality to the list. We can achieve this by adding an event listener to the container element and updating the &lt;code&gt;scrollTop&lt;/code&gt; state whenever the user scrolls.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;function VirtualizedList({ items, itemHeight, containerHeight }) {
  const [scrollTop, setScrollTop] = useState(0);
  const startIndex = Math.floor(scrollTop / itemHeight);
  const endIndex = Math.min(
    startIndex + Math.ceil(containerHeight / itemHeight),
    items.length
  );
  const visibleItems = items.slice(startIndex, endIndex);
  const invisibleItemsHeight = (startIndex + visibleItems.length - endIndex) * itemHeight;
  const handleScroll = (event) =&amp;gt; {
    setScrollTop(event.target.scrollTop);
  };
  return (
    &amp;lt;div
      style={{ height: `${containerHeight}px`, overflowY: "scroll" }}
      onScroll={handleScroll}
    &amp;gt;
      &amp;lt;div style={{ height: `${items.length * itemHeight}px` }}&amp;gt;
        &amp;lt;div
          style={{
            position: "relative",
            height: `${visibleItems.length * itemHeight}px`,
            top: `${startIndex * itemHeight}px`,
          }}
        &amp;gt;
          {visibleItems.map((item) =&amp;gt; (
            &amp;lt;div key={item.id} style={{ height: `${itemHeight}px` }}&amp;gt;
              {item.content}
            &amp;lt;/div&amp;gt;
          ))}
        &amp;lt;/div&amp;gt;
        &amp;lt;div style={{ height: `${invisibleItemsHeight}px` }} /&amp;gt;
      &amp;lt;/div&amp;gt;
    &amp;lt;/div&amp;gt;
  );
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In this final example, we added the scrollTop state using the useState hook. We also added the onScroll event listener to the container element and called the handleScroll function to update the scrollTop state whenever the user scrolls.&lt;/p&gt;

&lt;p&gt;We also added the overflowY property to the container element to enable scrolling. Finally, we wrapped the entire list inside the container element with a height equal to containerHeight.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://asimzaidi.medium.com/"&gt;Reference: taken from here&lt;/a&gt;&lt;/p&gt;

</description>
      <category>react</category>
      <category>nextjs</category>
    </item>
  </channel>
</rss>
