<?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 youssef moti on Medium]]></title>
        <description><![CDATA[Stories by youssef moti on Medium]]></description>
        <link>https://medium.com/@youssefmoti_91796?source=rss-dc7aed43be77------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*vNNfaM5fCrFLsWst</url>
            <title>Stories by youssef moti on Medium</title>
            <link>https://medium.com/@youssefmoti_91796?source=rss-dc7aed43be77------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 30 Nov 2026 15:30:15 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@youssefmoti_91796/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[Exploring Node v23.6.0: New Features]]></title>
            <link>https://medium.com/@youssefmoti_91796/exploring-node-v23-6-0-new-features-a5fbdb9ee6ef?source=rss-dc7aed43be77------2</link>
            <guid isPermaLink="false">https://medium.com/p/a5fbdb9ee6ef</guid>
            <category><![CDATA[node-js-tutorial]]></category>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[node-new-feature]]></category>
            <dc:creator><![CDATA[youssef moti]]></dc:creator>
            <pubDate>Thu, 09 Jan 2025 18:50:31 GMT</pubDate>
            <atom:updated>2025-01-09T18:59:52.574Z</atom:updated>
            <content:encoded><![CDATA[<p>Node.js v23.6.0, released on January 7, 2025, introduces several significant enhancements to improve developer experience and expand the platform’s capabilities. This article delves into these new features, providing advanced insights and practical examples to help you leverage them effectively in your projects.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*YhOao3zBSoN4VeDvnUVRuQ.jpeg" /></figure><h3>Unflagging --experimental-strip-types</h3><p>One of the most notable changes in this release is the unflagging of the --experimental-strip-types feature. Previously, executing TypeScript files required additional configuration or transpilation steps. With this update, Node.js can execute TypeScript files directly without extra setup:</p><pre>node file.ts</pre><p>his enhancement streamlines the workflow for TypeScript developers, allowing for the immediate execution of .ts files. However, it&#39;s important to note that this feature is still experimental and has certain limitations regarding supported syntax. Detailed information about these limitations can be found in the official Node.js documentation.</p><p><strong>Example: </strong>Executing a TypeScript File</p><p>Consider a simple TypeScript file named example.ts:</p><pre>function greet(name: string): string {<br>  return `Hello, ${name}!`;<br>}<br><br>console.log(greet(&#39;World&#39;));</pre><p>With Node.js v23.6.0, you can execute this file directly:</p><pre>node example.ts</pre><p>This command will output: Hello, World!</p><p>This feature simplifies the development process by eliminating the need for a separate compilation step in many cases.</p><h3>TypeScript Support in STDIN Evaluation</h3><p>Building upon the TypeScript execution capabilities, Node.js v23.6.0 adds support for evaluating TypeScript code via STDIN. This means you can pipe TypeScript code directly into Node.js for immediate execution.</p><p><strong>Example: </strong>Evaluating TypeScript via STDIN</p><pre>echo &quot;console.log((x: number, y: number): number =&gt; x + y)(2, 3);&quot; | node</pre><p>This command will output: 5</p><p>This enhancement is particularly useful for quick experiments and integrating TypeScript code into shell scripts.</p><h3>process.ref() and process.unref() Methods</h3><p>The introduction of process.ref() and process.unref() methods give developers finer control over the event loop&#39;s behavior concerning the process itself.</p><ul><li><strong>process.unref()</strong>: Calling this method indicates that the current process should not prevent the Node.js event loop from exiting. In other words, if the process is the only active event loop reference, the program can terminate naturally.</li><li><strong>process.ref()</strong>: This method can be used to reverse the effect of a previous process.unref() call, ensuring that the process keeps the event loop active.</li></ul><p><strong>Example: </strong>Using process.unref()</p><pre>setTimeout(() =&gt; {<br>  console.log(&#39;This will not keep the process running.&#39;);<br>}, 1000).unref();</pre><p>In this example, the setTimeout is unreferenced, meaning its existence alone won&#39;t keep the Node.js process alive. If no other operations are keeping the event loop active, the process will exit before the timeout callback is invoked.</p><p><strong>Example: </strong>Using process.ref()</p><pre>const timer = setTimeout(() =&gt; {<br>  console.log(&#39;This will keep the process running.&#39;);<br>}, 1000);<br><br>timer.unref();<br>timer.ref();</pre><p>Here, the timer is first unreferenced and then re-referenced, ensuring that the process remains active until the timeout completes.</p><p>These methods offer advanced control over process behavior, which can be particularly beneficial in scenarios involving long-running asynchronous operations or when integrating with native modules.</p><h3>TypeScript Evaluation in Worker Threads</h3><p>Node.js v23.6.0 extends TypeScript support to worker threads, allowing for the evaluation of TypeScript code within workers. This enhancement facilitates the development of multi-threaded applications using TypeScript.</p><p><strong>Example: </strong>Evaluating TypeScript in a Worker Thread</p><pre>const { Worker } = require(&#39;worker_threads&#39;);<br><br>const worker = new Worker(`<br>  const greet = (name: string): string =&gt; {<br>    return \`Hello, \${name}!\`;<br>  };<br>  console.log(greet(&#39;Worker&#39;));<br>`, { eval: true });</pre><p>In this example, a worker thread is created to execute TypeScript code that defines a greet function and logs a greeting message. The eval: true option allows the worker to evaluate the provided code string.</p><p>This feature enhances the versatility of worker threads, enabling developers to leverage TypeScript’s type safety and features across multiple threads.</p><h3>Conclusion</h3><p>Node.js v23.6.0 introduces significant advancements that enhance TypeScript integration and provide developers with greater control over process behavior. The unflagging --experimental-strip-types simplifies TypeScript execution, while the new process.ref() and process.unref() methods offer refined event loop management. Additionally, extending TypeScript support to STDIN evaluation and worker threads broadens the scope for developing robust, type-safe applications.</p><p>As these features are currently experimental, it’s advisable to review the official <a href="https://nodejs.org/en/blog/release/v23.6.0">Node.js documentation</a> for detailed information and to exercise caution when deploying them in production environments.</p><p>By staying informed about these developments, you can effectively leverage the latest capabilities of Node.js to build efficient and maintainable applications.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a5fbdb9ee6ef" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Exploring Kotlin 2.1.0: New Features]]></title>
            <link>https://medium.com/@youssefmoti_91796/exploring-kotlin-2-1-0-new-features-1986e63ce5fd?source=rss-dc7aed43be77------2</link>
            <guid isPermaLink="false">https://medium.com/p/1986e63ce5fd</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[kotlinupdates]]></category>
            <category><![CDATA[kotlin]]></category>
            <dc:creator><![CDATA[youssef moti]]></dc:creator>
            <pubDate>Sun, 05 Jan 2025 02:43:31 GMT</pubDate>
            <atom:updated>2025-01-05T19:49:59.754Z</atom:updated>
            <content:encoded><![CDATA[<p>Kotlin 2.1.0, released on November 27, 2024, introduces several new features and improvements that enhance the language’s expressiveness and performance</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*_ifCHZYHQZPbxQF3RlpUdA.jpeg" /></figure><p>All the features have IDE support in the latest 2024.3 version of IntelliJ IDEA with K2 mode enabled.</p><p>Learn more in the <a href="https://blog.jetbrains.com/idea/2024/11/intellij-idea-2024-3/">IntelliJ IDEA 2024.3 blog post</a>.</p><h3>1. Guard Conditions in “when” Expressions</h3><p><strong>Before Kotlin 2.1.0:</strong> To include additional conditions, developers needed nested if statements or explicit checks inside each branch.</p><pre>sealed interface Animal {<br>    data class Cat(val mouseHunter: Boolean) : Animal<br>    data class Dog(val breed: String) : Animal<br>}<br><br>fun feedAnimal(animal: Animal) {<br>     when (animal) {<br>        is Animal.Dog -&gt; {<br>            if (animal.age &lt; 10) {<br>                println(&quot;Feeding a young dog&quot;)<br>            } else {<br>                println(&quot;Feeding a senior dog special food&quot;)<br>            }<br>        }<br>        is Animal.Cat -&gt; {<br>            if (!animal.mouseHunter) {<br>                println(&quot;Feeding a cat&quot;)<br>            } else {<br>                println(&quot;This cat hunts mice; no feeding needed&quot;)<br>            }<br>        }<br>    }<br>}</pre><p><strong>Starting from Kotlin 2.1.0:</strong> Guard conditions allow you to include more than one condition for the branches of a when expression, making complex control flows more explicit and concise as well as flattening the code structure.</p><p>To include a guard condition in a branch, place it after the primary condition, separated by if:</p><pre>fun feedAnimal(animal: Animal) {<br>    when (animal) {<br>        is Animal.Dog if animal.age &lt; 10 -&gt; println(&quot;Feeding a young dog&quot;)<br>        is Animal.Dog if animal.age &gt;= 10 -&gt; println(&quot;Feeding a senior dog special food&quot;)<br>        is Animal.Cat if !animal.mouseHunter -&gt; println(&quot;Feeding a cat&quot;)<br>        is Animal.Cat if animal.mouseHunter -&gt; println(&quot;This cat hunts mice; no feeding needed&quot;)<br>    }<br>}</pre><p>In a single when expression, you can combine branches with and without guard conditions. The code in a branch with a guard condition runs only if both the primary condition and the guard condition are true. If the primary condition does not match, the guard condition is not evaluated. Additionally, guard conditions support else if.</p><p>To enable guard conditions in your project, add -Xwhen-guard in the compilerOptions {} block of your Gradle build file:</p><pre>// build.gradle.kts<br>kotlin {<br>    compilerOptions {<br>        freeCompilerArgs.add(&quot;-Xwhen-guards&quot;)<br>    }<br>}</pre><h3>2. Non-Local break and continue</h3><p><strong>Before Kotlin 2.1.0:</strong> Developers used labels to handle complex loops in lambdas, leading to verbose and less readable code.</p><pre>fun processList(elements: List&lt;Int&gt;): Boolean {<br>    loop@ for (element in elements) {<br>        val variable = element.takeIf { it &gt; 0 } ?: continue@loop // Using labeled return since continue wasn&#39;t available <br>        if (variable == 0) return true // Non-local return was already supported<br>    }<br>    return false<br>}</pre><p><strong>Starting from Kotlin 2.1.0:</strong> The new feature allows direct break and continue in lambdas passed to inline functions.</p><p>This feature expands the toolset you can use in the scope of inline functions and reduces boilerplate code in your project.</p><pre>fun processList(elements: List&lt;Int&gt;): Boolean {<br>    elements.forEach { element -&gt;<br>        val variable = element.takeIf { it &gt; 0 } ?: continue  // Can now use continue instead of return@forEach<br>        if (variable == 0) break // Can now use break instead of return true<br>    }<br>    return false<br>}</pre><p>To enable <strong>Non-local break</strong> and <strong>continue</strong>, add -Xnon-local-break-continue in the compilerOptions {} block of your Gradle build file:</p><pre>// build.gradle.kts<br>kotlin {<br>    compilerOptions {<br>        freeCompilerArgs.add(&quot;-Xnon-local-break-continue&quot;)<br>    }<br>}</pre><h3>3. Multi-Dollar String Interpolation</h3><p><strong>Before Kotlin 2.1.0:</strong> Working with strings requiring literal dollar signs required escaping every instance, which could be tedious and error-prone.</p><pre>val KClass&lt;*&gt;.jsonSchema: String<br>    get() = &quot;&quot;&quot;<br>        {<br>            &quot;\$schema&quot;: &quot;https://json-schema.org/draft/2020-12/schema&quot;,<br>            &quot;\$id&quot;: &quot;https://example.com/product.schema.json&quot;,<br>            &quot;title&quot;: &quot;${simpleName ?: qualifiedName ?: &quot;unknown&quot;}&quot;,<br>            &quot;type&quot;: &quot;object&quot;<br>        }<br>    &quot;&quot;&quot;</pre><p><strong>Starting from Kotlin 2.1.0: </strong>String interpolation in Kotlin uses a single dollar sign. However, using a literal dollar sign in a string, which is common in financial data and templating systems, required workarounds such as ${&#39;$&#39;}. With the multi-dollar interpolation feature enabled, you can configure how many dollar signs trigger interpolation, with fewer dollar signs being treated as string literals.</p><p>Here’s an example of how to generate a JSON schema multi-line string with placeholders using $:</p><pre>val KClass&lt;*&gt;.jsonSchema: String<br>    get() = $$&quot;&quot;&quot;<br>        {<br>            &quot;$schema&quot;: &quot;https://json-schema.org/draft/2020-12/schema&quot;,<br>            &quot;$id&quot;: &quot;https://example.com/product.schema.json&quot;,<br>            &quot;title&quot;: &quot;$${simpleName ?: qualifiedName ?: &quot;unknown&quot;}&quot;,<br>            &quot;type&quot;: &quot;object&quot;<br>        }<br>    &quot;&quot;&quot;</pre><p>Here, the initial $$ means that two dollar signs are required to trigger interpolation, preventing $schema, $id, and $dynamicAnchor from being interpreted as interpolation markers. To enable this feature, add the<br> -Xmulti-dollar-interpolation in the compilerOptions {} block of your Gradle build file:</p><pre>// build.gradle.kts<br>kotlin {<br>    compilerOptions {<br>        freeCompilerArgs.add(&quot;-Xmulti-dollar-interpolation&quot;)<br>    }<br>}</pre><h3>4. K2 Compiler Updates</h3><p>The K2 compiler in Kotlin 2.1.0 offers more flexibility around compiler checks and improvements to the kapt implementation. These updates enhance performance and give developers more control over the compilation process.</p><h3>5. Kotlin Multiplatform Enhancements</h3><p>Kotlin 2.1.0 introduces basic support for Swift export, allowing for better interoperability with Swift code. Additionally, a stable Gradle DSL for compiler options has been introduced, simplifying the configuration of compiler settings in multiplatform projects.</p><h3>6. Kotlin/Native Improvements</h3><p>This release brings improved support for iosArm64, enhancing the development experience for iOS applications. Other updates include performance optimizations and bug fixes that contribute to a more stable and efficient Kotlin/Native environment.</p><h3>7. Kotlin/Wasm Updates</h3><p>Kotlin 2.1.0 includes multiple updates for Kotlin/Wasm, notably support for incremental compilation. This enhancement reduces build times and improves the development workflow when targeting WebAssembly.</p><h3>8. Gradle Support Enhancements</h3><p>The release improves compatibility with newer versions of Gradle and the Android Gradle plugin. Updates to the Kotlin Gradle plugin API provide developers with more tools and options for building Kotlin projects efficiently.</p><h3>9. Documentation Improvements</h3><p>Significant improvements have been made to the Kotlin documentation, providing clearer and more comprehensive guides and references to assist developers in utilizing the language effectively.</p><h3>10. Updating to Kotlin 2.1.0</h3><p>To start using Kotlin 2.1.0, change the Kotlin version to 2.1.0 in your build scripts. The Kotlin plugins that support 2.1.0 are bundled in the latest versions of IntelliJ IDEA and Android Studio, so no additional plugin updates are necessary.</p><p>By exploring and adopting these new features and improvements, you can enhance your Kotlin development experience and take advantage of the latest advancements in the language.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1986e63ce5fd" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ Kotlin Collections Mastery: From Basics to Advanced Techniques ]]></title>
            <link>https://medium.com/@youssefmoti_91796/kotlin-collections-mastery-from-basics-to-advanced-techniques-cc2190fa1207?source=rss-dc7aed43be77------2</link>
            <guid isPermaLink="false">https://medium.com/p/cc2190fa1207</guid>
            <category><![CDATA[kotlin-collection]]></category>
            <category><![CDATA[lists]]></category>
            <category><![CDATA[tricks]]></category>
            <category><![CDATA[kotlin]]></category>
            <dc:creator><![CDATA[youssef moti]]></dc:creator>
            <pubDate>Tue, 31 Dec 2024 21:26:34 GMT</pubDate>
            <atom:updated>2025-02-04T16:39:59.242Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*UEHtsXsJkQ65_A-AzWZoJQ.jpeg" /><figcaption>Kotlin collection</figcaption></figure><h3>🍐 Introduction: The Power of Kotlin Collections</h3><p>This comprehensive guide will walk you through every aspect of Kotlin collections, ensuring you become a true collection maestro. Let’s explore these collections using delicious fruits! <br>🍎 🍐 🍊 🍌 🍇</p><figure><img alt="Diagram of the Kotlin collection interfaces" src="https://cdn-images-1.medium.com/max/1024/0*THiIzxfzgO5ZL1VA.png" /><figcaption>Diagram of the Kotlin collection interfaces</figcaption></figure><h3>🍊 Chapter 1: Lists — The Versatile Collection</h3><h4>1.1 List Creation Techniques</h4><ul><li>Immutable List Creation — Cannot modify</li></ul><pre>data class Fruit(val id: Int, val name: String, val emoji: String)<br><br>// Creating a List of Fruits<br>val fruits = listOf(<br>    Fruit(1, &quot;Banana&quot;, &quot;🍌&quot;),<br>    Fruit(2, &quot;Cherry&quot;, &quot;🍒&quot;),<br>    Fruit(3, &quot;Apple&quot;, &quot;🍎&quot;),<br>    Fruit(4, &quot;Date&quot;, &quot;🌴&quot;)<br>)<br><br>println(fruits)<br>// output =&gt; [Fruit(id=1, name=Banana, emoji=🍌), Fruit(id=2, name=Cherry, emoji=🍒), Fruit(id=3, name=Apple, emoji=🍎), Fruit(id=4, name=Date, emoji=🌴)]<br><br><br>val fruitNames: List&lt;String&gt; = fruits.map { it.name }<br>// or<br>// val fruitNames: List&lt;String&gt; = listOf(&quot;Banana&quot;, &quot;Cherry&quot;, &quot;Apple&quot;, &quot;Date&quot;)<br><br>println(fruitNames)<br>// output =&gt; [Banana, Cherry, Apple, Date]<br><br>val fruitEmojis = fruits.map { it.emoji }<br>// or <br>// val fruitEmojis = listOf(&quot;🍌&quot;, &quot;🍒&quot;, &quot;🍎&quot;, &quot;🌴&quot;)<br><br>println(fruitEmojis)<br>// output =&gt; [🍌, 🍒, 🍎, 🌴]<br><br><br><br>// String to List<br>val stringList = &quot;Hello&quot;.toList()<br><br>println(stringList)<br>// output =&gt; [H, e, l, l, o]<br><br><br>// Create list from mapOf<br>val mapOfFruitToList = mapOf(<br>    &quot;Banana&quot; to &quot;🍌&quot;,<br>    &quot;Cherry&quot; to &quot;🍒&quot;,<br>    &quot;Apple&quot; to &quot;🍎&quot;<br>).toList()<br><br>println(mapOfFruitToList)<br>// output =&gt; [(Banana, 🍌), (Cherry, 🍒), (Apple, 🍎)]<br><br>// Empty List with Type Inference<br>val emptyFruits = emptyList&lt;String&gt;()<br><br>println(emptyFruits)<br>// output =&gt; []<br><br><br>// Creating list using List constructor<br>val listConstructor = List(5) { idx -&gt; &quot;item: $idx&quot; }<br><br>println(listConstructor)<br>// output =&gt; [item: 0, item: 1, item: 2, item: 3, item: 4]<br><br><br>// List with Initialization<br>val numberFruits = List(5) { index -&gt; &quot;🍎 ${index + 1}&quot; }<br><br>println(numberFruits)<br>// output =&gt; [🍎 1, 🍎 2, 🍎 3, 🍎 4, 🍎 5]<br><br>val integerRange = (1..10).toList()<br><br>println(integerRange)<br>// output =&gt; [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]</pre><ul><li>Mutable List Initialization — Can modify</li></ul><pre><br>// Creating a mutable list of Fruits<br>val mutableFruits = mutableListOf(<br>    Fruit(1, &quot;Banana&quot;, &quot;No emoji&quot;),<br>    Fruit(2, &quot;Cherry&quot;, &quot;🍒&quot;),<br>    Fruit(3, &quot;Apple&quot;, &quot;🍎&quot;)<br>)<br><br>println(mutableFruits)<br>/* output =&gt; <br>[<br>  Fruit(id=1, name=Banana, emoji=No emoji), <br>  Fruit(id=2, name=Cherry, emoji=🍒), <br>  Fruit(id=3, name=Apple, emoji=🍎)<br>]<br>*/</pre><ul><li>Accessing Elements</li></ul><pre>// The get(index) function retrieves the element at the specified index in a list.<br>println(mutableFruits.get(1))<br>// output =&gt; Fruit(id=2, name=Cherry, emoji=🍒)<br><br>// The square bracket operator ([]) is shorthand for calling get(index).<br>println(mutableFruits[1])<br>// output =&gt; Fruit(id=2, name=Cherry, emoji=🍒)<br><br>// The getOrElse function retrieves the element at the specified index if it exists. Otherwise, it returns a default value provided as a lambda.<br>println(mutableFruits.getOrElse(3){ println(&quot;Not found&quot;) })<br>// output =&gt; Not found<br><br>// The getOrNull function retrieves the element at the specified index or returns null if the index is out of bounds.<br>println(mutableFruits.getOrNull(3))<br>// output =&gt; Null</pre><ul><li>Adding, Removing, and Modifying Collections</li></ul><pre>// Add new item to mutableFruits<br>mutableFruits.add(Fruit(4, &quot;Date&quot;, &quot;🌴&quot;))<br>// or<br>// mutableFruits += Fruit(4, &quot;Date&quot;, &quot;🌴&quot;)<br><br>println(mutableFruits)<br>/* output =&gt; <br>[<br>  Fruit(id=1, name=Banana, emoji=No emoji), <br>  Fruit(id=2, name=Cherry, emoji=🍒), <br>  Fruit(id=3, name=Apple, emoji=🍎), <br>  Fruit(id=4, name=Date, emoji=🌴)<br>]<br>*/<br><br>// Modify item at index 0<br>mutableFruits[0] = Fruit(1, &quot;Banana&quot;, &quot;🍌&quot;)<br><br>println(mutableFruits)<br>/* output =&gt; <br>[<br>  Fruit(id=1, name=Banana, emoji=🍌), <br>  Fruit(id=2, name=Cherry, emoji=🍒), <br>  Fruit(id=3, name=Apple, emoji=🍎), <br>  Fruit(id=4, name=Date, emoji=🌴)<br>]<br>*/<br><br>// Remove item at index<br>mutableFruits.removeAt(1)<br><br>println(mutableFruits)<br>/* output =&gt; <br>[<br>  Fruit(id=1, name=Banana, emoji=🍌), <br>  Fruit(id=3, name=Apple, emoji=🍎), <br>  Fruit(id=4, name=Date, emoji=🌴)<br>]<br>*/<br><br>// Remove item<br>mutableFruits.remove(Fruit(id=1, name=&quot;Banana&quot;, emoji=&quot;🍌&quot;))<br>// or <br>// mutableFruits -= Fruit(id=1, name=&quot;Banana&quot;, emoji=&quot;🍌&quot;)<br><br>println(mutableFruits)<br>/* output =&gt; <br>[<br>  Fruit(id=3, name=Apple, emoji=🍎), <br>  Fruit(id=4, name=Date, emoji=🌴)<br>]<br>*/<br><br>val newMutableFruits = fruits.toMutableList()<br><br>println(newMutableFruits)<br>/*<br> output =&gt;<br>[<br>  Fruit(id=1, name=Banana, emoji=🍌), <br>  Fruit(id=2, name=Cherry, emoji=🍒), <br>  Fruit(id=3, name=Apple, emoji=🍎), <br>  Fruit(id=4, name=Date, emoji=🌴)<br>]<br>*/<br><br>newMutableFruits.fill(Fruit(3, &quot;Apple&quot;, &quot;🍎&quot;))<br><br>println(newMutableFruits)<br>/*<br> output =&gt;<br>[<br>  Fruit(id=3, name=Apple, emoji=🍎), <br>  Fruit(id=3, name=Apple, emoji=🍎), <br>  Fruit(id=3, name=Apple, emoji=🍎), <br>  Fruit(id=3, name=Apple, emoji=🍎)<br>]<br>*/<br><br>// clear newMutableFruits<br>newMutableFruits.clear()<br>// output =&gt; []<br><br>// Remove all items with a name length of less than 5 characters.<br>mutableFruits.removeAll{ it.name.length &lt; 5 }<br><br>println(mutableFruits)<br>// output =&gt; [Fruit(id=3, name=Apple, emoji=🍎)]<br><br>// keeps all items in the letters list that match<br>val letters = mutableListOf(&quot;Banana&quot;,  &quot;🍎&quot;, &quot;5&quot;, &quot;Cherry&quot;, &quot;🌴&quot;)<br>letters.retainAll { it.all{ it.isLetter() } }<br><br>println(letters)<br>// output =&gt; [Banana, Cherry]</pre><ul><li>Transforming Collections</li></ul><pre>// subList takes a beginning and end index, which determines which items should be shown<br>val sub = fruits.subList(1, 3)<br><br>println(sub)<br>// output =&gt; [Fruit(id=2, name=Cherry, emoji=🍒), Fruit(id=3, name=Apple, emoji=🍎)]<br><br>val fruitNames = fruits.map { it.name }<br><br>println(fruitNames) <br>// Output =&gt; [Banana, Cherry, Apple, Date]<br><br>val fruitIds = fruits.mapNotNull { it.takeIf { fruit -&gt; fruit.id % 2 == 0 }?.id }<br><br>println(fruitIds) <br>// Output =&gt; [2, 4]<br><br>val indexedFruits = fruits.mapIndexed { index, fruit -&gt; &quot;$index: ${fruit.name}&quot; }<br><br>println(indexedFruits)<br>// Output =&gt; [&quot;0: Banana&quot;, &quot;1: Cherry&quot;, &quot;2: Apple&quot;, &quot;3: Date&quot;]<br><br>val mixedStrsList = listOf( &quot;3&quot;, &quot;1&quot;, &quot;two&quot;, &quot;4&quot;, &quot;X&quot;)<br><br>val nums: List&lt;Int&gt; = mixedStrsList.mapNotNull {<br>    it.toIntOrNull()<br>}<br><br>println(nums)<br>// output =&gt; [3, 1, 4]</pre><ul><li>Filtering Collections</li></ul><pre>val mixedList = listOf(&quot;Apple&quot;, 42, null, &quot;Banana&quot;)<br><br>val filtered = mixedList.filterIsInstance&lt;String&gt;()<br><br>println(filtered) <br>// Output =&gt; [Apple, Banana]<br><br>val filteredNot = mixedList.filterNot { it is Int }<br><br>println(filteredNot) <br>// Output =&gt; [Apple, null, Banana]<br><br>val filteredNotNull = mixedList.filterNotNull()<br><br>println(filteredNotNull) <br>// Output =&gt; [Apple, 42, Banana]<br><br><br>val filtered = fruits.filter { it.name.startsWith(&quot;A&quot;) }<br><br>println(filtered) <br>// Output =&gt; [Fruit(id=3, name=Apple, emoji=🍎)]<br><br>// Fruits excluding startsWith &quot;B&quot;<br>val filteredNot = fruits.filterNot { it.name.startsWith(&quot;B&quot;) }<br><br>println(filteredNot) <br>// Output =&gt; [Fruit(id=2, name=Cherry, emoji=🍒), Fruit(id=3, name=Apple, emoji=🍎), Fruit(id=4, name=Date, emoji=🌴)]<br><br>val nullableFruits: List&lt;Fruit?&gt; = listOf(null, Fruit(1, &quot;Apple&quot;, &quot;🍎&quot;))<br><br><br>println(nullableFruits.filterNotNull()) <br>// Output =&gt; [Fruit(id=1, name=Apple, emoji=🍎)]</pre><ul><li>Checking Conditions</li></ul><pre>val isContainsA = fruits.any{ it.name.contains(&quot;a&quot;, ignoreCase = true) }<br><br>println(isContainsA)<br>// output =&gt; true<br><br><br>val isNotContainsA = fruits.none{ it.name.contains(&quot;a&quot;, ignoreCase = true) }<br><br>println(isNotContainsA)<br>// output =&gt; false<br><br>val isAllItemsApple = fruits.all{ it.name.equals(&quot;Apple&quot;, ignoreCase = true) }<br><br>println(isAllItemsApple)<br>// output =&gt; false<br><br>val numOfItemsContainsA = fruits.count{ it.name.contains(&quot;a&quot;, ignoreCase = true) }<br><br>println(numOfItemsContainsA)<br>// output =&gt; 3<br><br>// Other examples<br>val numbers = listOf(2, 4, 6)<br><br>val allEven = numbers.all { it % 2 == 0 }<br><br>println(allEven) <br>// Output =&gt; true<br><br>val anyOdd = numbers.any { it % 2 != 0 }<br><br>println(anyOdd) <br>// Output =&gt; false<br><br>val noneNegative = numbers.none { it &lt; 0 }<br><br>println(noneNegative) <br>// Output =&gt; true</pre><ul><li>Counting and Finding Elements</li></ul><pre>println(fruits.count())<br>// Output =&gt; 4<br><br>println(fruits.count { it.id &gt; 2 })<br>// Output =&gt; 2<br><br>println(fruits.count { it.name.contains(&quot;y&quot;) }) <br>// Output =&gt; 1<br><br>println(fruits.first { it.name.startsWith(&quot;C&quot;) }) <br>// Output =&gt; Fruit(id=2, name=Cherry, emoji=🍒)<br><br>println(fruits.firstOrNull { it.name.startsWith(&quot;X&quot;) })<br>// Output =&gt; null<br><br>println(fruits.last { it.id &lt; 4 })<br>// Output =&gt; Fruit(id=3, name=Apple, emoji=🍎)<br><br>// More examples<br>val numbers = listOf(1, 2, 3, 2, 1)<br><br>println(numbers.count { it == 2 }) <br>// Output =&gt; 2<br><br>println(numbers.first { it &gt; 1 }) <br>// Output =&gt; 2<br><br>println(numbers.firstOrNull { it &gt; 5 }) <br>// Output =&gt; null<br><br>println(numbers.last { it &lt; 3 }) <br>// Output =&gt; 2<br><br>println(numbers.lastOrNull { it &lt; 0 }) <br>// Output =&gt; null<br><br>val unique = listOf(42)<br><br>println(unique.single()) <br>// Output =&gt; 42<br><br>println(unique.singleOrNull { it &gt; 50 }) <br>// Output =&gt; null</pre><ul><li>Aggregation</li></ul><pre>val cumulativeLength = fruits.sumOf { it.name.length }<br><br>println(cumulativeLength)<br>// Output =&gt; 21<br><br>val randomNumbers = listOf(10, 5, 20, 15, 1, 9, 3)<br><br>println(randomNumbers.average())<br>// Output =&gt; 9.0<br><br>println(randomNumbers.sum())<br>// Output =&gt; 63<br><br><br>println(randomNumbers.minOrNull())<br>// Output =&gt; 1<br><br>println(randomNumbers.maxOrNull())<br>// Output =&gt; 20<br><br><br>println(fruits.minOf { it.name.length })<br>// Output =&gt; 4<br><br>println(fruits.maxOf { it.name.length })<br>// Output =&gt; 6<br><br>// using reduce<br>val reducedIndexed = randomNumbers.reduceIndexed { index, acc, num -&gt; acc + index * num }<br><br>println(reducedIndexed) <br>// Output =&gt; 167<br><br>val reducedOrNull = emptyList&lt;Int&gt;().reduceOrNull { acc, num -&gt; acc + num }<br><br>println(reducedOrNull) <br>// Output =&gt; null<br><br>val combinedNames = fruits.reduce { acc, fruit -&gt; <br>    Fruit(0, acc.name + &quot;, &quot; + fruit.name, &quot;&quot;)<br>}<br><br>println(combinedNames.name)<br>// Output =&gt; Banana, Cherry, Apple, Date<br><br>// using fold<br>val foldedNames = fruits.fold(&quot;Fruits:&quot;) { acc, fruit -&gt; acc + &quot; &quot; + fruit.name }<br>println(foldedNames)<br>// Output =&gt; Fruits: Banana Cherry Apple Date<br><br>val folded = randomNumbers.fold(10) { acc, num -&gt; acc + num }<br><br>println(folded)<br>// Output =&gt; 73<br><br>val foldedIndexed = randomNumbers.foldIndexed(10) { index, acc, num -&gt; acc + index * num }<br><br>println(foldedIndexed)<br>// Output =&gt; 167</pre><ul><li>Grouping</li></ul><pre>val groupedByEmoji = fruits.groupBy { it.emoji }<br>println(groupedByEmoji)<br>// Output =&gt; {<br>// 🍌=[Fruit(id=1, name=Banana, emoji=🍌)], <br>// 🍒=[Fruit(id=2, name=Cherry, emoji=🍒)], <br>// 🍎=[Fruit(id=3, name=Apple, emoji=🍎)], <br>// 🌴=[Fruit(id=4, name=Date, emoji=🌴)]<br>// }<br><br>val groupByToMap = mutableMapOf&lt;String, MutableList&lt;Fruit&gt;&gt;()<br>val groupedByColor = fruits.groupByTo(groupByToMap) { fruit -&gt;<br>    when {<br>        fruit.emoji == &quot;🍎&quot; || fruit.emoji == &quot;🍒&quot; -&gt; &quot;RED&quot;<br>        else -&gt; &quot;OTHER&quot;<br>    }<br>}<br><br><br> println(groupedByColor)<br>// Output =&gt; {<br>// OTHER=[Fruit(id=1, name=Banana, emoji=🍌), Fruit(id=4, name=Date, emoji=🌴)], <br>// RED=[Fruit(id=2, name=Cherry, emoji=🍒), Fruit(id=3, name=Apple, emoji=🍎)]<br>// }<br><br>val groupedByColorCount = fruits.groupingBy { fruit -&gt;<br>    when {<br>        fruit.emoji == &quot;🍎&quot; -&gt; &quot;RED&quot;<br>        fruit.emoji == &quot;🍒&quot; -&gt; &quot;RED&quot;<br>        else -&gt; &quot;OTHER&quot;<br>    }<br>}.eachCount()<br><br><br> println(groupedByColorCount)<br>// Output =&gt; {OTHER=2, RED=2}</pre><ul><li>Associations</li></ul><pre>val associated = fruits.associate { it.name to it.emoji }<br><br>println(associated) <br>// Output =&gt; {Banana=🍌, Cherry=🍒, Apple=🍎, Date=🌴}<br><br><br>val associatedBy = fruits.associateBy() { <br>    when {<br>        it.emoji == &quot;🍎&quot; -&gt; &quot;RED&quot;<br>        it.emoji == &quot;🍒&quot; -&gt; &quot;RED&quot;<br>        else -&gt; &quot;OTHER&quot;<br>    } <br>}<br><br>println(associatedBy) <br>// Output =&gt; {<br>// OTHER=Fruit(id=4, name=Date, emoji=🌴), <br>// RED=Fruit(id=3, name=Apple, emoji=🍎)<br>// }<br><br>val associatedBy2 = fruits.associateBy { it.name to it.emoji }<br><br>println(associatedBy2) <br>// Output =&gt; {<br>// (Banana, 🍌)=Fruit(id=1, name=Banana, emoji=🍌), <br>// (Cherry, 🍒)=Fruit(id=2, name=Cherry, emoji=🍒), <br>// (Apple, 🍎)=Fruit(id=3, name=Apple, emoji=🍎), <br>// (Date, 🌴)=Fruit(id=4, name=Date, emoji=🌴)<br>// }<br><br>val associateWith = fruits.associateWith { <br>    when {<br>        it.emoji == &quot;🍎&quot; || it.emoji == &quot;🍒&quot; -&gt; &quot;RED&quot;<br>        else -&gt; &quot;OTHER&quot;<br>    } <br>}<br><br>println(associateWith) <br>// Output =&gt; {<br>// Fruit(id=1, name=Banana, emoji=🍌)=OTHER, <br>// Fruit(id=2, name=Cherry, emoji=🍒)=RED, <br>// Fruit(id=3, name=Apple, emoji=🍎)=RED, <br>// Fruit(id=4, name=Date, emoji=🌴)=OTHER<br>// }<br></pre><ul><li>Sorting, Shuffling, and Reversed</li></ul><pre>// Fruits sorted by name<br>val sortedByName = fruits.sortedBy { it.name }<br><br>println(sortedByName) <br>/* output =&gt;<br>[<br> Fruit(id=3, name=Apple, emoji=🍎), <br> Fruit(id=1, name=Banana, emoji=🍌), <br> Fruit(id=2, name=Cherry, emoji=🍒), <br> Fruit(id=4, name=Date, emoji=🌴)<br>]<br>*/<br><br><br>// Reversed items<br>println(fruits.reversed())<br>/* output =&gt;<br>[<br> Fruit(id=4, name=Date, emoji=🌴)<br> Fruit(id=3, name=Apple, emoji=🍎),<br> Fruit(id=2, name=Cherry, emoji=🍒),<br> Fruit(id=1, name=Banana, emoji=🍌) <br>]<br>*/<br><br>println(fruits.asReversed())<br>/* output =&gt;<br>[<br> Fruit(id=4, name=Date, emoji=🌴)<br> Fruit(id=3, name=Apple, emoji=🍎),<br> Fruit(id=2, name=Cherry, emoji=🍒),<br> Fruit(id=1, name=Banana, emoji=🍌) <br>]<br>*/<br><br>// Shuffled items<br>println(fruits.shuffled())<br>/* output =&gt;<br>[<br>  Fruit(id=3, name=Apple, emoji=🍎), <br>  Fruit(id=4, name=Date, emoji=🌴), <br>  Fruit(id=2, name=Cherry, emoji=🍒), <br> Fruit(id=1, name=Banana, emoji=🍌)<br>]<br>*/<br></pre><ul><li>Distinct and Partitioning</li></ul><pre><br>val randomNumbers = listOf(10, 5, 20, 15, 1, 9, 3)<br><br>println(randomNumbers.distinct())<br>// Output =&gt; [10, 5, 20, 15, 1, 9, 3]<br><br>println(randomNumbers.distinctBy { it % 2 })<br>// Output =&gt; [10, 5]<br><br>val (even, odd) = randomNumbers.partition { it % 2 == 0 }<br>println(even)<br>// Output =&gt; [10, 20]<br><br>println(odd)<br>// Output =&gt; [5, 15, 1, 9, 3]<br><br>// Unique by first letter<br>val distinctNames = fruits.distinctBy { it.name.first() }<br><br>println(distinctNames)<br>/* output =&gt;<br>[<br> Fruit(id=3, name=Apple, emoji=🍎), <br> Fruit(id=1, name=Banana, emoji=🍌), <br> Fruit(id=2, name=Cherry, emoji=🍒), <br> Fruit(id=4, name=Date, emoji=🌴)<br>]<br>*/<br><br><br>val (fruitsMoreThanFiveChars, restFruits) = fruits.partition { it.name.length &gt; 5}<br><br>println(fruitsMoreThanFiveChars)<br>// output =&gt; [Fruit(id=1, name=Banana, emoji=🍌), Fruit(id=2, name=Cherry, emoji=🍒)]<br><br>println(restFruits)<br>// output =&gt; [Fruit(id=3, name=Apple, emoji=🍎), Fruit(id=4, name=Date, emoji=🌴)]</pre><ul><li>Joining and Chunking</li></ul><pre>// Joining<br>println(fruits.joinToString (<br>    separator = &quot;, and &quot;,<br>    prefix = &quot;fruit list: &quot;,<br>    limit = 5<br>) {<br>    &quot;${it.name}&quot;<br>})<br>// Output =&gt; fruit list: Banana, and Cherry, and Apple, and ...<br><br><br>// Chunking<br>val chunkedLists = fruits.chunked(2)<br><br>println(chunkedLists)<br>// Output =&gt; [<br>// [Fruit(id=1, name=Banana, emoji=🍌), Fruit(id=2, name=Cherry, emoji=🍒)], <br>// [Fruit(id=3, name=Apple, emoji=🍎), Fruit(id=4, name=Date, emoji=🌴)]<br>// ]<br><br><br>val reversedChunkedLists = fruits.chunked(2) { it.reversed() }<br><br>println(reversedChunkedLists)<br>// Output =&gt; [<br>// [Fruit(id=2, name=Cherry, emoji=🍒), Fruit(id=1, name=Banana, emoji=🍌)], <br>// [Fruit(id=4, name=Date, emoji=🌴), Fruit(id=3, name=Apple, emoji=🍎)]<br>// ]<br><br>// windowed<br><br>val windowedLists = fruits.windowed(2) <br><br>println(windowedLists)<br>// Output =&gt; [<br>// [Fruit(id=1, name=Banana, emoji=🍌), Fruit(id=2, name=Cherry, emoji=🍒)], <br>// [Fruit(id=2, name=Cherry, emoji=🍒), Fruit(id=3, name=Apple, emoji=🍎)], <br>// [Fruit(id=3, name=Apple, emoji=🍎), Fruit(id=4, name=Date, emoji=🌴)]<br>// ]<br><br>val partialWindowsLists = fruits.windowed(3, 2, partialWindows = true) <br><br>println(partialWindowsLists)<br>// Output =&gt; [<br>// [Fruit(id=1, name=Banana, emoji=🍌), Fruit(id=2, name=Cherry, emoji=🍒), Fruit(id=3, name=Apple, emoji=🍎)], <br>// [Fruit(id=3, name=Apple, emoji=🍎), Fruit(id=4, name=Date, emoji=🌴)]<br>// ]<br><br>val reversedPartialWindowsLists = fruits.windowed(3, 2, partialWindows = true) { it.reversed() }<br><br>println(reversedPartialWindowsLists)<br>// Output =&gt; [<br>// [Fruit(id=3, name=Apple, emoji=🍎), Fruit(id=2, name=Cherry, emoji=🍒), Fruit(id=1, name=Banana, emoji=🍌)], <br>// [Fruit(id=4, name=Date, emoji=🌴), Fruit(id=3, name=Apple, emoji=🍎)]<br>// ]</pre><ul><li>Lazy Operations</li></ul><pre>println(fruits.take(2)) <br>// Output =&gt; [Fruit(id=1, name=Banana, emoji=🍌), Fruit(id=2, name=Cherry, emoji=🍒)]<br><br>println(fruits.takeWhile { it.id % 2 != 0 }) <br>// Output: [Fruit(id=1, name=Banana, emoji=🍌)]<br><br>println(fruits.drop(1)) <br>// Output: [Fruit(id=2, name=Cherry, emoji=🍒), Fruit(id=3, name=Apple, emoji=🍎), Fruit(id=4, name=Date, emoji=🌴)]<br><br><br>println(fruits.drop(10)) <br>// Output: []<br><br>println(fruits.dropWhile { it.id &lt; 3 }) <br>// Output: [Fruit(id=3, name=Apple, emoji=🍎), Fruit(id=4, name=Date, emoji=🌴)]</pre><ul><li>Flattening</li></ul><pre>val nestedFruits = listOf(listOf(&quot;Apple&quot;, &quot;Banana&quot;), listOf(&quot;Cherry&quot;))<br><br>println(nestedFruits.flatten()) <br>// Output =&gt; [Apple, Banana, Cherry]<br><br><br>val nestedFruitsLists = listOf(<br>    listOf(Fruit(1, &quot;Apple&quot;, &quot;🍎&quot;), Fruit(2, &quot;Banana&quot;, &quot;🍌&quot;)),<br>    listOf(Fruit(3, &quot;Cherry&quot;, &quot;🍒&quot;))<br>)<br><br>val flattened = nestedFruitsLists.flatMap { it.map { fruit -&gt; fruit.name } }<br><br>println(flattened) <br>// Output =&gt; [Apple, Banana, Cherry]<br><br>val flatIndexed = nestedFruitsLists.flatMapIndexed { index, sublist -&gt; <br>    sublist.map { &quot;${index + 1}-${it.name}&quot; }<br>}<br><br>println(flatIndexed) <br>// Output =&gt; [&quot;1-Apple&quot;, &quot;1-Banana&quot;, &quot;2-Cherry&quot;]</pre><ul><li>1.2 Advanced List Manipulations</li></ul><pre>// Powerful Transformations<br>val uppercaseFruits = fruitNames.map { it.uppercase() }<br><br>println(uppercaseFruits)<br>// output =&gt; [BANANA, CHERRY, APPLE, DATE]<br><br>// Filtering with Precision<br>val longNameFruits = fruitNames.filter { it.length &gt; 5 }<br><br>println(longNameFruits)<br>// output =&gt; [Banana, Cherry]<br><br>// Complex Transformations<br>val fruitDetails = fruitNames.map { fruit -&gt;<br>    mapOf(<br>        &quot;name&quot; to fruit,<br>        &quot;length&quot; to fruit.length<br>    )<br>}<br><br>println(fruitDetails)<br>/* output =&gt; [<br> {name=Banana, length=6}, <br> {name=Cherry, length=6}, <br> {name=Apple, length=5}, <br> {name=Date, length=4}<br>] */<br><br>// Flat Mapping<br>val nestedFruits = listOf(<br>    listOf(&quot;🍎&quot;, &quot;🍌&quot;),<br>    listOf(&quot;🍇&quot;, &quot;🍊&quot;)<br>)<br><br>println(nestedFruits)<br>// output =&gt; [[🍎, 🍌], [🍇, 🍊]]<br><br>val flattenedFruits = nestedFruits.flatten()<br><br>println(flattenedFruits)<br>// output =&gt; [🍎, 🍌, 🍇, 🍊]<br><br>// Map fruits by their ID for quick access.<br>val fruitMap = fruits.associateBy { it.id }<br><br>println(fruitMap)<br>// output =&gt; {1=Fruit(id=1, name=Banana, emoji=🍌), 2=Fruit(id=2, name=Cherry, emoji=🍒), 3=Fruit(id=3, name=Apple, emoji=🍎), 4=Fruit(id=4, name=Date, emoji=🌴)}<br><br>println(fruitMap[1]?.name) <br>// Output =&gt; Banana<br><br>// Use groupBy to categorize fruits based on the length of their names.<br>val groupedFruits = fruits.groupBy { it.name.length }<br><br>println(groupedFruits)<br>// Output =&gt; {6=[Fruit(id=1, name=Banana, emoji=🍌), Fruit(id=2, name=Cherry, emoji=🍒)], 5=[Fruit(id=3, name=Apple, emoji=🍎)], 4=[Fruit(id=4, name=Date, emoji=🌴)]}<br><br>// Filter fruits whose name starts with &quot;A&quot; and transform them into a list of names with emojis<br>val filteredFruits = fruits<br>    .filter { it.name.startsWith(&quot;A&quot;) }<br>    .map { &quot;${it.name} ${it.emoji}&quot; }<br><br>println(filteredFruits) <br>// Output =&gt; [Apple 🍎]<br><br>// Pair fruit names and emojis into a combined string.<br>val paired = fruitNames.zip(fruitEmojis) { name, emoji -&gt; &quot;$name: $emoji&quot; }<br><br>println(paired) <br>// Output =&gt; [Banana: 🍌, Cherry: 🍒, Apple: 🍎, Date: 🌴]<br><br>// Zipping fruit names to emojis.<br>val ziped = fruitNames.zip(fruitEmojis) { name, emoji -&gt; name to emoji }<br><br>// we can also call the zip function using infix notation:<br>println(fruitNames zip fruitEmojis)<br>// Output =&gt; [(Banana, 🍌), (Cherry, 🍒), (Apple, 🍎), (Date, 🌴)]<br><br>println(ziped) <br>// Output =&gt; [(Banana, 🍌), (Cherry, 🍒), (Apple, 🍎), (Date, 🌴)]<br><br>val (names, emojis) = ziped.unzip()<br><br>println(names) <br>// Output =&gt; [Banana, Cherry, Apple, Date]<br><br>println(emojis) <br>// Output =&gt; [🍌, 🍒, 🍎, 🌴]<br><br><br>val randomNumbers = listOf(10, 5, 20, 15, 1, 9, 3)<br><br>println(randomNumbers.zipWithNext())<br>// Output =&gt; [(10, 5), (5, 20), (20, 15), (15, 1), (1, 9), (9, 3)]<br><br><br>// Sort fruits by their name alphabetically.<br>val sortedFruits = fruits.sortedBy { it.name }<br><br>println(sortedFruits.map { it.name }) <br>// Output =&gt; [Apple, Banana, Cherry, Date]<br><br>// Suppose you want to display fruits whose name is longer than 5 characters and represent them with a string.<br>val longNameFruits = fruits<br>    .filter { it.name.length &gt; 5 }<br>    .joinToString { &quot;${it.name} ${it.emoji}&quot; }<br><br>println(longNameFruits)<br>// Output =&gt; Banana 🍌, Cherry 🍒</pre><h3>1.3 Powerful Reduction Operations</h3><pre>// Reducing Lists<br>val fruitCount = fruitNames.fold(0) { acc, _ -&gt; acc + 1 }<br><br>println(fruitCount)<br>// output =&gt; 4<br><br>val newNumberList = listOf(1, 2, 3, 4, 5)<br><br>val sum = newNumberList.fold(0) { acc, number -&gt; acc + number }<br>println(sum) <br>// Output =&gt; 15<br><br>val product = newNumberList.reduce { acc, number -&gt; acc * number }<br>println(product) <br>// Output =&gt; 120<br><br><br>// Finding Aggregates<br>val longestFruit = fruitsByName.maxByOrNull { it.length }<br>val shortestFruit = fruitsByName.minByOrNull { it.length }<br><br>println(longestFruit)<br>// output =&gt; banana<br>println(shortestFruit)<br>// output =&gt; apple<br><br>// Grouping and Counting<br>val fruits = listOf(&quot;🍎&quot;, &quot;🍌&quot;, &quot;🍎&quot;, &quot;🍇&quot;)<br>val fruitFrequency = fruits.groupingBy { it }.eachCount()<br><br>println(fruits)<br>// output =&gt; [🍎, 🍌, 🍎, 🍇]<br>println(fruitFrequency)<br>// output =&gt; {🍎=2, 🍌=1, 🍇=1}<br></pre><h3>🍋 Chapter 2: Arrays — Performance and Precision</h3><h3>2.1 Array Creation Strategies</h3><pre>// Standard Array Creation<br>val fruitArray = arrayOf(&quot;🍎&quot;, &quot;🍌&quot;, &quot;🍇&quot;)<br><br>// Specialized Array Initialization<br>val sizedArray = Array(5) { &quot;🍎&quot; }<br><br>// Primitive Arrays for Performance<br>val intFruits = intArrayOf(1, 2, 3, 4, 5)</pre><h3>2.2 Array Transformations</h3><pre>// Converting Between Collections<br>val fruitList = fruitArray.toList()<br>val fruitSet = fruitArray.toSet()<br><br>// In-place Sorting<br>val sortedFruits = fruitArray.apply { sort() }</pre><h3>🍇 Chapter 3: Maps — Key-Value Powerhouses</h3><h3>3.1 Map Creation and Manipulation</h3><pre>// Immutable Map Creation<br>val fruitColors = mapOf(<br>    &quot;🍎&quot; to &quot;Red&quot;,<br>    &quot;🍌&quot; to &quot;Yellow&quot;,<br>    &quot;🍇&quot; to &quot;Purple&quot;<br>)<br><br>//output =&gt; {🍎=Red, 🍌=Yellow, 🍇=Purple}<br><br>// Mutable Map Operations<br>val mutableFruitColors = mutableMapOf&lt;String, String&gt;()<br>mutableFruitColors[&quot;🍊&quot;] = &quot;Orange&quot;<br><br>// output =&gt; {🍊=Orange}<br><br>// Safe Access<br>val appleColor = fruitColors[&quot;🍎&quot;] ?: &quot;Unknown&quot;<br><br>// output =&gt; Red</pre><h3>3.2 Advanced Map Techniques</h3><pre>// Transforming Maps<br>val uppercaseColorMap = fruitColors.mapValues { it.value.uppercase() }<br><br>// output =&gt; {🍎=RED, 🍌=YELLOW, 🍇=PURPLE}</pre><h3>🍓 Chapter 4: Sets — Unique Collection Guardians</h3><h4>4.1 Set Creation and Operations</h4><pre>// Immutable Set Creation<br>val uniqueFruits = setOf(&quot;apple&quot;, &quot;banana&quot;, &quot;cherry&quot;, &quot;apple&quot;)<br><br>println(uniqueFruits)<br>//output =&gt; [apple, banana, cherry]<br><br>// Set Mathematical Operations<br>val tropicalFruits = setOf(&quot;apple&quot;, &quot;banana&quot;)<br>val mixedFruits = setOf(&quot;cherry&quot;, &quot;apple&quot;)<br><br>println(tropicalFruits)<br>// output =&gt; [apple, banana]<br><br>println(mixedFruits)<br>// output =&gt; [cherry, apple]<br><br>val commonFruits = tropicalFruits intersect mixedFruits<br>val allUniqueFruits = tropicalFruits union mixedFruits<br><br>println(commonFruits)<br>// output =&gt; [apple]<br><br>println(allUniqueFruits)<br>// output =&gt; [apple, banana, cherry]</pre><h4>4.2 Advanced Set Manipulations</h4><pre>// Efficient Membership Testing<br>val hasBanana = &quot;banana&quot; in mixedFruits<br><br>println(hasBanana)<br>// output =&gt; false<br><br>// Converting Sets<br>val fruitList = mixedFruits.toList()<br><br>println(fruitList)<br>// output =&gt; [cherry, apple]</pre><h3>🥝 Chapter 5: Performance and Best Practices</h3><h4>5.1 Sequence Operations for Lazy Evaluation</h4><pre>// Lazy Transformations<br>val processedFruits = fruits.asSequence()<br>    .filter { it.length &gt; 5 }<br>    .map { it.uppercase() }<br>    .toList()<br><br>println(processedFruits)<br>// output =&gt; [BANANA, CHERRY]<br><br>// Showcase the use of sequences for large data sets to avoid unnecessary intermediate collections<br>val numbers = (1..1_000_000).toList()<br>val evenNumbers = numbers.asSequence()<br>    .filter { it % 2 == 0 }<br>    .take(10)<br>    .toList()<br><br>println(evenNumbers)<br>// Output =&gt; [2, 4, 6, 8, 10, 12, 14, 16, 18, 20]</pre><h3>🍍 Conclusion: Mastering Kotlin Collections</h3><h3>Key Insights:</h3><ul><li>Choose the right collection for your use case</li><li>Leverage functional programming techniques</li><li>Prioritize immutability</li><li>Use sequences for large data processing</li><li>Always consider performance implications</li></ul><h3>Performance Cheat Sheet:</h3><ul><li>Lists: Ordered, allow duplicates</li><li>Sets: Unique elements, fast lookup</li><li>Maps: Key-value associations</li><li>Arrays: Fixed size, primitive performance</li></ul><h3>Pro Tips:</h3><ol><li>Always use listOf() for immutable lists</li><li>Prefer mutableListOf() over direct mutation</li><li>Use getOrDefault() for safe map access</li><li>Leverage groupBy() for complex categorizations</li></ol><h3>Common Pitfalls to Avoid:</h3><ul><li>Unnecessary type casting</li><li>Modifying collections during iteration</li><li>Ignoring lazy evaluation benefits</li><li>Overusing mutable collections</li></ul><h3>Wrap up with actionable advice and further resources:</h3><ul><li>Suggest using Kotlin’s <a href="https://kotlinlang.org/docs/collections-overview.html#set">official documentation</a>.</li><li>Highlight the importance of practicing these techniques in real-world projects.</li></ul><h3><strong>📊 Complexity Matrix Overview</strong></h3><h4><strong>Time Complexity Quick Reference</strong></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/760/1*sQkbkLIxzNnlmQG9fbOIOw.png" /></figure><p><strong>Happy Kotlin Coding! 🚀👩‍💻👨‍💻</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cc2190fa1207" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Mastering Micro-Frontends: Advanced Tutorial with Module Federation and Vite]]></title>
            <link>https://medium.com/@youssefmoti_91796/mastering-micro-frontends-advanced-tutorial-with-module-federation-and-vite-77ee543eab8e?source=rss-dc7aed43be77------2</link>
            <guid isPermaLink="false">https://medium.com/p/77ee543eab8e</guid>
            <category><![CDATA[micro-frontends]]></category>
            <category><![CDATA[module-federation]]></category>
            <category><![CDATA[react]]></category>
            <dc:creator><![CDATA[youssef moti]]></dc:creator>
            <pubDate>Mon, 30 Dec 2024 23:36:33 GMT</pubDate>
            <atom:updated>2025-01-04T17:43:22.169Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zcX4EBLXu5ig-cJzUjG5zQ.png" /></figure><p>Micro-frontends have revolutionized modern web development, enabling teams to build modular, scalable, and maintainable applications by dividing large frontend projects into independently deployable units. In this advanced tutorial, we’ll explore <strong>micro-frontends</strong> in detail, from their architecture to implementation, focusing on <strong>Module Federation</strong> with <strong>Vite</strong> and best practices.</p><h4>What Are Micro-Frontends?</h4><p>Micro-frontends are an architectural approach where a web application is built by combining smaller, independent applications (micro-apps). This concept extends the principles of microservices to the front end.</p><h4>Core Principles of Micro-Frontends</h4><ol><li><strong>Independence</strong>: Each micro-frontend is independently developed, deployed, and owned by separate teams.</li><li><strong>Technology Agnostic</strong>: Different micro-frontends can use different frameworks or libraries.</li><li><strong>Team Autonomy</strong>: Teams can work on different micro-frontends without conflicts.</li><li><strong>Incremental Migration</strong>: Enables gradual migration of legacy applications to modern tech stacks.</li></ol><h4>Benefits of Micro-Frontends</h4><ol><li><strong>Independent Deployment</strong><br>Each micro-frontend can be deployed independently, reducing the need for synchronized releases across teams.</li><li><strong>Scalability</strong><br>Teams can work on separate parts of the application concurrently, accelerating development.</li><li><strong>Technology Agnostic</strong><br>Different micro-frontends can use different frameworks (React, Angular, Vue, etc.), allowing teams to use the best tools for their specific needs.</li><li><strong>Code Reusability</strong><br>Shared components, utilities, and business logic can be easily exposed and reused across multiple micro-frontends.</li><li><strong>Improved Maintainability</strong><br>Modularizing the application reduces complexity in each micro-frontend, making maintenance easier.</li><li><strong>Dynamic Updates</strong><br>Module Federation allows loading remote modules dynamically, enabling runtime updates without requiring a full application rebuild</li></ol><h4>Challenges with Micro-Frontends</h4><ol><li><strong>TypeScript Sharing Problems: <br></strong>Loss of type safety when transpiling TypeScript to JavaScript.<br><br><strong><em>Issue:</em></strong> <br>Types are not available in host apps unless manually defined or shared explicitly.<br><br><strong><em>Solution Ideas:<br></em></strong>-<strong><em> </em></strong>Use a <strong>shared type library</strong> published to an NPM registry or as part of a monorepo.<br>- Generate and distribute .d.ts files from remote apps to host apps automatically.<br>- Use tools like dts-bundle or tsup or vite-plugin-dts to create a single .d.ts file for all exported types in the remote app.</li><li><strong>Unit Testing Challenges</strong><br>Remote modules or functions might not be available during unit tests in the host app.<br><br><strong><em>Issue</em>:</strong> <br>This can make testing dependent components difficult without mocking.<br><br><strong><em>Solution Ideas:<br></em></strong>-<strong><em> </em></strong>Use <strong>mock implementations</strong> for remote modules in unit tests, such as vi.mock or jest.mock<br>- Provide local fallbacks for remote modules during development and testing.<br>- Use contract testing to validate interfaces between remote and host apps.</li><li><strong>Runtime Crashes</strong><br>Runtime errors can occur if remote modules change in a way that breaks compatibility with the host app.<br><br><strong><em>Issue</em>:</strong> <br>No compile-time guarantees ensure compatibility between host and remote.<br><br><strong><em>Solution Ideas:<br>- </em></strong>Enforce versioning policies for shared modules and dependencies.<br>- Implement <strong>runtime compatibility checks</strong> to validate APIs and contracts.<br>- Use <strong>semantic versioning</strong> to signal breaking changes explicitly.</li><li><strong>Increased Complexity</strong><br>Managing multiple repositories, shared dependencies, and runtime module resolution can introduce additional complexity.<br><br><strong><em>Solution Ideas:<br>- </em></strong>Use a monorepo for better dependency and module management.<br>- Centralize shared configuration and tooling to reduce duplication.</li><li><strong>Dependency Duplication</strong><br>Different micro-frontends might bundle the same dependencies, increasing the overall application size.<br><br><strong><em>Solution Ideas:<br>- </em></strong>Use shared configuration in Module Federation to avoid loading duplicate libraries.<br>- Regularly audit dependencies to ensure consistency.</li><li><strong>Initial Load Time</strong><br>Dynamically loading micro-frontends at runtime can increase the initial load time of the host app.<br><br><strong><em>Solution Ideas:<br>- </em></strong>Use lazy loading and code splitting to load micro-frontends only when needed.<br>- Optimize shared dependencies and cache strategies.</li><li><strong>Styling Conflicts</strong><br>CSS conflicts may arise if styles are not properly scoped.<br><br><strong><em>Solution Ideas:<br>- </em></strong>Use CSS Modules or CSS-in-JS solutions like Emotion or Styled Components.<br>- Ensure consistent theming across micro-frontends.</li></ol><h3>When to Use Micro-Frontends</h3><p><strong>Micro-frontends are best suited for:</strong></p><ul><li>Large applications with multiple teams working in parallel.</li><li>Applications requiring incremental migration from monolith to modular architecture.</li><li>Systems where parts of the UI need to be updated independently and frequently.</li></ul><p><strong>Avoid micro-frontends for:</strong></p><ul><li>Small or simple applications where the added complexity isn’t justified.</li></ul><h3>Module Federation: The Key Enabler of Micro-Frontends</h3><p><strong>Module Federation</strong> is a feature in <strong>Webpack 5</strong> that allows JavaScript applications to share dynamically and load modules between apps at runtime. It simplifies the implementation of micro-frontends by providing:</p><ol><li><strong>Runtime Sharing</strong>: Modules are shared dynamically, reducing redundancy.</li><li><strong>Independent Deployments</strong>: Applications can deploy independently without breaking dependencies.</li><li><strong>Cross-Framework Support</strong>: Enables integration of React, Angular, Vue, etc., in one project.</li></ol><h3>Building Micro-Frontends with Vite and Module Federation</h3><p><strong>Vite</strong> is a modern build tool optimized for speed and simplicity. While Module Federation was originally designed for Webpack, Vite’s @originjs/vite-plugin-federation plugin makes it a powerful choice for micro-frontends.</p><h4>Steps to Build Micro-Frontends</h4><p>We’ll create two micro-frontends:</p><ol><li><strong>Remote App</strong>: Exposing a Button component.</li><li><strong>Host App</strong>: Consuming the Button component.</li></ol><pre>npm create vite@latest remote-app -- --template react-ts<br>npm create vite@latest host-app -- --template react-ts</pre><h4>Step 1: Install Dependencies</h4><p>Install dependencies for both Host and Remote apps.</p><pre>cd remote-app &amp;&amp; npm install @originjs/vite-plugin-federation<br>cd ../host-app &amp;&amp; npm install @originjs/vite-plugin-federation</pre><h4>Step 2: Remote App Configuration</h4><p>Folder Structure:</p><pre>remote-app/<br>├── src/<br>│   ├── components<br>│   │   ├── Button<br>│   │       ├── Button.tsx<br>│   │       ├── button.module.css<br>│   │       ├── types.ts<br>│   │       ├── index.ts<br>│   ├── main.tsx<br>├── vite.config.ts</pre><pre>// src/components/Button/Button.tsx<br>import { FC, useState } from &#39;react&#39;;<br>import { TButtonProps } from &#39;./types&#39;;<br><br>import style from &#39;./button.module.css&#39;<br><br>const Button: FC&lt;TButtonProps&gt; = ({ text }) =&gt; {<br>  const [count, setCount] = useState(0);<br><br>  return (<br>    &lt;button className={style.btn} onClick={() =&gt; setCount((n) =&gt; n + 1)}&gt;<br>      {`${text} ${count}`}<br>    &lt;/button&gt;<br>  );<br>};<br><br>export default Button;</pre><pre>/* src/components/Button/button.module.css */<br>:root {<br>  --button-bg: #007bff;<br>  --button-hover-bg: #0056b3;<br>  --button-text-color: white;<br>  --button-padding: 10px 20px;<br>  --button-border-radius: 4px;<br>}<br><br>.btn {<br>  background-color: var(--button-bg);<br>  color: var(--button-text-color);<br>  border: 1px solid var(--button-bg);<br>  border-radius: var(--button-border-radius);<br>  padding: var(--button-padding);<br>  font-size: 16px;<br>  font-weight: 600;<br>  cursor: pointer;<br>  transition: all 0.2s ease-in-out;<br>  &amp;:hover {<br>    background-color: var(--button-hover-bg);<br>  }<br>}</pre><pre>// src/components/Button/types.ts<br>export type TButtonProps = {<br>  text: string;<br>};</pre><pre>// src/components/Button/index.ts<br>export { default } from &#39;./Button&#39;<br>export * from &#39;./types&#39;</pre><pre>// src/main.tsx<br>import { StrictMode } from &#39;react&#39;<br>import { createRoot } from &#39;react-dom/client&#39;<br>import Button from &#39;./components/Button&#39;<br><br>createRoot(document.getElementById(&#39;root&#39;)!).render(<br>  &lt;StrictMode&gt;<br>    &lt;Button text=&#39;Click me&#39; /&gt;<br>  &lt;/StrictMode&gt;,<br>)</pre><pre>// vite.config.ts<br>import { defineConfig } from &#39;vite&#39;<br>import react from &#39;@vitejs/plugin-react&#39;<br>import  federation  from &quot;@originjs/vite-plugin-federation&quot;;<br><br><br>// https://vite.dev/config/<br>export default defineConfig({<br>  plugins: [<br>    react(),<br>    federation({<br>      name: &quot;remoteApp&quot;,<br>      filename: &quot;remoteEntry.js&quot;,<br>      exposes: {<br>        &quot;./Button&quot;: &quot;./src/components/Button&quot;,<br>      },<br>      shared: [&quot;react&quot;, &quot;react-dom&quot;],<br>    })<br>  ],<br>  build: {<br>    modulePreload: false,<br>    target: &quot;esnext&quot;,<br>    minify: false,<br>    cssCodeSplit: false<br>  },<br>  preview: {<br>    port: 3000,<br>    strictPort: true,<br>    cors: true<br>  }<br>})</pre><p>Run the Remote App:</p><pre>npm run build<br><br>npm run preview</pre><h4>Step 3: Host App Configuration</h4><p>Folder Structure:</p><pre>host-app/<br>├── src/<br>│   ├── App.jsx<br>│   ├── main.jsx<br>├── vite.config.js</pre><pre>// App.tsx<br>import React, { Suspense } from &#39;react&#39;;<br><br>// Import the remote component using dynamic import<br>const RemoteButton = React.lazy(() =&gt; import(&#39;remoteApp/Button&#39;));<br>function App() {<br>  return (<br>    &lt;div&gt;<br>      &lt;h1&gt;Host App&lt;/h1&gt;<br>      &lt;Suspense fallback={&lt;div&gt;Loading Remote Button...&lt;/div&gt;}&gt;<br>        &lt;RemoteButton text=&quot;click remote button&quot; /&gt;<br>      &lt;/Suspense&gt;<br>    &lt;/div&gt;<br>  );<br>}<br>export default App;</pre><pre>// main.tsx<br>import { StrictMode } from &#39;react&#39;<br>import { createRoot } from &#39;react-dom/client&#39;<br>import App from &#39;./App.tsx&#39;<br><br><br>createRoot(document.getElementById(&#39;root&#39;)!).render(<br>  &lt;StrictMode&gt;<br>    &lt;App /&gt;<br>  &lt;/StrictMode&gt;,<br>)</pre><pre>// vite.config.ts<br>import { defineConfig } from &#39;vite&#39;<br>import react from &#39;@vitejs/plugin-react&#39;<br>import federation from &quot;@originjs/vite-plugin-federation&quot;;<br><br>// https://vite.dev/config/<br>export default defineConfig({<br>  plugins: [<br>    react(),<br>    federation({<br>      name: &quot;hostApp&quot;,<br>      remotes: {<br>        remoteApp: &quot;http://localhost:3000/assets/remoteEntry.js&quot;,<br>      },<br>      shared: [&quot;react&quot;, &quot;react-dom&quot;],<br>    }),<br>  ],<br>  build: {<br>    modulePreload: false,<br>    target: &quot;esnext&quot;,<br>    minify: false,<br>    cssCodeSplit: false,<br>  }<br>})</pre><p>You may encounter challenges with TypeScript support when using Module Federation, as TypeScript does not natively recognize remote modules. To address this, you’ll need to manually declare remote modules in each host app by creating a remote.d.ts file in the src directory. This file will serve as a type declaration for the remote modules, ensuring proper type checking and autocompletion during development.</p><pre>// remote.d.ts<br>declare module &#39;remoteApp/Button&#39; {  <br>  export interface TButtonProps {<br>    text: string;<br>  }<br>  <br>  const Button: React.FC&lt;TButtonProp&gt;;<br>  export default Button;<br>}</pre><p>If you want to avoid declaring remote modules manually in each host app, you can leverage a shared <strong>type declaration package</strong> or generate TypeScript declarations dynamically.</p><p>Run the Host App:</p><pre>npm run dev</pre><h4>Step 4: Test the Setup</h4><ol><li>Start the Remote App on port <strong>3000</strong>.</li><li>Navigate to (http://localhost:3000/assets/remoteEntry.js), and you should see the <strong>JavaScript file</strong> (the <strong>remote entry file</strong>) that the <strong>remote micro-frontend</strong> exposes for sharing its modules with the host application.</li><li>Start the Host App on any port.</li><li>Navigate to the Host App (http://localhost:&lt;host port&gt;), and you should see the Remote Button dynamically loaded.</li></ol><h3>Best Practices for Micro-Frontends</h3><h4>1. Design and Architecture</h4><p><strong>a. <em>Define Clear Boundaries</em></strong></p><ul><li>Divide applications into self-contained domains, ensuring that each micro-frontend owns specific features or functionality.</li><li>Avoid overlapping responsibilities between teams to reduce interdependencies.</li></ul><p><strong><em>b. Use Independent Deployments</em></strong></p><ul><li>Each micro-frontend should have its own build and deployment pipeline to avoid coupling.</li><li>Implement versioning strategies to ensure backward compatibility when making changes.</li></ul><p><strong><em>c. Avoid Hard Dependencies</em></strong></p><ul><li>Use shared utilities and libraries via tools like <strong>Module Federation</strong> or package managers but minimize runtime dependencies to reduce coupling.</li></ul><h4>2. Module Federation and TypeScript</h4><p><strong><em>a. Centralize TypeScript Type Management</em></strong></p><ul><li>Use a dedicated repository for shared TypeScript types or auto-generate .d.ts files in remote apps and distribute them to host apps.</li><li>Use tools like vite-plugin-dts or dts-bundle to create bundled type definitions.</li></ul><p><strong><em>b. Lazy Load Dependencies</em></strong></p><ul><li>Ensure each micro-frontend loads only the dependencies it requires.</li><li>Use dynamic imports to reduce the initial load time of the host application.</li></ul><p><strong><em>c. Namespace Shared Modules</em></strong></p><ul><li>Avoid version conflicts by using tools like @originjs/vite-plugin-federation with proper namespace handling for shared libraries (e.g., React, Vue).</li></ul><h4>3. Communication Between Micro-Frontends</h4><p><strong><em>a. Minimize Direct Communication</em></strong></p><ul><li>Design micro-frontends to operate independently. Use shared events or a central event bus for communication when necessary.</li><li>Consider technologies like <strong>Redux Toolkit Query</strong> for state synchronization in React apps.</li></ul><p><strong><em>b. Use Standardized Contracts</em></strong></p><ul><li>For cross-micro-frontend communication, establish and enforce clear API contracts (e.g., REST APIs or GraphQL).</li></ul><p><strong><em>c. Decouple Navigation Logic</em></strong></p><ul><li>Let each micro-frontend handle its navigation. Use a shared router only for global-level navigation.</li></ul><h4>4. Performance Optimization</h4><p><strong><em>a. Reduce Shared Code</em></strong></p><ul><li>Minimize the size of shared libraries by analyzing and splitting dependencies where possible.</li><li>Use tools like <strong>Webpack Bundle Analyzer</strong> or <strong>Rollup Plugin Visualizer</strong>.</li></ul><p><strong><em>b. Code Splitting</em></strong></p><ul><li>Employ code-splitting strategies for each micro-frontend, ensuring efficient chunk delivery.</li></ul><p><strong><em>c. Cache Shared Modules</em></strong></p><ul><li>Use long-term caching for shared modules, and ensure all micro-frontends use the same version of shared libraries when possible.</li></ul><h4>5. Testing and Quality Assurance</h4><p><strong><em>a. Independent Unit Tests</em></strong></p><ul><li>Write independent unit tests for each micro-frontend to ensure they work correctly in isolation.</li><li>Mock remote modules during tests if they are unavailable at runtime.</li></ul><p><strong><em>b. Contract Tests</em></strong></p><ul><li>Test interactions between host and remote apps using API contract testing tools (e.g., Pact.js).</li></ul><p><strong><em>c. Automated Integration Testing</em></strong></p><ul><li>Test the entire application flow to verify seamless integration between micro-frontends.</li></ul><h4>6. Developer Experience</h4><p><strong><em>a. Standardize Tooling</em></strong></p><ul><li>Use the same build tools (e.g., Vite, Webpack) and language (e.g., TypeScript) across all micro-frontends to reduce complexity.</li><li>Set up shared ESLint, Prettier, and TypeScript configurations.</li></ul><p><strong><em>b. Improve Local Development</em></strong></p><ul><li>Use Module Federation to dynamically load remote apps during local development without building them.</li><li>Mock remote modules when developing individual micro-frontends.</li></ul><p><strong><em>c. Documentation</em></strong></p><ul><li>Maintain updated documentation on shared modules, APIs, and contracts to align teams.</li></ul><h4>7. Deployment and Maintenance</h4><p><strong><em>a. Use CI/CD Pipelines</em></strong></p><ul><li>Automate the build and deployment processes for each micro-frontend.</li><li>Ensure consistent testing and release strategies for all micro-frontends.</li></ul><p><strong><em>b. Backward Compatibility</em></strong></p><ul><li>Use feature flags to manage the rollout of new features without disrupting existing functionality.</li></ul><p><strong>c. Monitor and Rollback</strong></p><ul><li>Implement monitoring tools (e.g., Datadog, New Relic) to detect runtime errors.</li><li>Have a robust rollback strategy in case of runtime crashes.</li></ul><h4>Github repos:</h4><p><strong>Remote-app: </strong><a href="https://github.com/youssef103/mf-remote-app">https://github.com/youssef103/mf-remote-app</a></p><p><strong>Host-app</strong>: <a href="https://github.com/youssef103/mf-host-app">https://github.com/youssef103/mf-host-app</a></p><h4>Conclusion</h4><p>Micro-frontends with Module Federation provide a powerful way to build scalable and maintainable applications. By combining the speed of <strong>Vite</strong> with the flexibility of <strong>Module Federation</strong>, teams can easily develop independently deployable micro-apps across different frameworks.</p><p>With best practices in place, this architecture can unlock unparalleled productivity and maintainability for large-scale applications.</p><p>Happy micro-frontend development! 🚀</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=77ee543eab8e" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>