<?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 CodeHero on Medium]]></title>
        <description><![CDATA[Stories by CodeHero on Medium]]></description>
        <link>https://medium.com/@codehero?source=rss-6c595310fb60------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*m32qfh12g0oZmh7w</url>
            <title>Stories by CodeHero on Medium</title>
            <link>https://medium.com/@codehero?source=rss-6c595310fb60------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 16 Nov 2026 11:20:30 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@codehero/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[Gallery]]></title>
            <link>https://medium.com/@codehero/gallery-eeaeac5dda39?source=rss-6c595310fb60------2</link>
            <guid isPermaLink="false">https://medium.com/p/eeaeac5dda39</guid>
            <dc:creator><![CDATA[CodeHero]]></dc:creator>
            <pubDate>Tue, 04 Apr 2023 09:39:35 GMT</pubDate>
            <atom:updated>2023-04-04T09:46:20.660Z</atom:updated>
            <content:encoded><![CDATA[<blockquote>A picture speaks a thousand words, and this one perfectly captures my passions: traveling, photography, and food! 🌍✈️🍲 I’ll be using this stunning photo to introduce myself and looking forward to connecting with like-minded friends on Twitter! 🤗</blockquote><h3>2023</h3><h4>April 2nd, Guomao, Beijing</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*cPmf63GJ4qGIq2mM.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*mqImQzhJLQen48g8.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*dEU_sMzH9Npqj9VD.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ekuig5Tx-qJfizSd.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ryASrD0CilfuC_Mz.png" /></figure><h4>March 26th, Olympic Forest Park, Beijing</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*G7zF0qLPTjV5Mfcd.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Xt91XEqZGmhgBqu5.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*JeHPrF-u_S-Cr-SV.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*UD57ctgIy3_WM7cw.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=eeaeac5dda39" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A few must-learn JavaScript hacks]]></title>
            <link>https://blog.devgenius.io/a-few-must-learn-javascript-hacks-50c84dfb5010?source=rss-6c595310fb60------2</link>
            <guid isPermaLink="false">https://medium.com/p/50c84dfb5010</guid>
            <category><![CDATA[front-end-development]]></category>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[vuejs]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[react]]></category>
            <dc:creator><![CDATA[CodeHero]]></dc:creator>
            <pubDate>Fri, 29 Jul 2022 03:46:19 GMT</pubDate>
            <atom:updated>2022-07-29T08:58:59.643Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*K9qQNeavgtmPXbsa" /><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>Reduce if… .else noodle code</h3><ul><li>As soon as we get to writing more than two if… .else functions it’s time to think about whether there’s a better way to optimize them.</li><li>For example, if we need to calculate the price of food at McDonald’s based on the name, you might do so.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rqF_lEDBQ5b-RRUQSkhNDA.png" /></figure><ul><li>This way of writing will make the function body has a lot of conditional judgment statements, and when we want to add a product next time we need to modify the logic within the function to add an if… . . else statement, which to some extent also violates the principle of open and closed, when we need to add a logic to try to extend the software entity to solve the requirements of the change, rather than by modifying the existing code to complete the change.</li><li>This is a very classical way of optimization, we can use a similar Map structure of data to save all the goods, here we directly create an object to store.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aV0offFsTxhvK0pvB4UIOQ.png" /></figure><ul><li>So that the next time we need to add a commodity will not need to change the logic of getPrice, of course, here in fact, more people like to use foodMap directly in the place directly, I just gave a simple example here to express this idea.</li><li>Then this time there are students will ask, if I do not want to key only with string it, this time you can use new Map, the idea is similar, an additional extension of an entity to store changes.</li></ul><h3>Pipeline operations instead of redundant loops</h3><ul><li>There is such a McMuffin food list</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*juEqpyAHvs8T7J63V6erxg.png" /></figure><ul><li>If you wanted to find the food that belongs to package 1, how would you find it?</li><li>The above method is the one we used to use, obviously we replace it with using filter and map instead of for loop not only to make the code more concise, but also to make the semantics clearer, so we can see at once that it is filtering the array first and then reorganizing it.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*W3WtiH4IpWlyoe17S018gA.png" /></figure><h3>find replaces redundant loops</h3><ul><li>As in the example above, find is useful if we want to find a specific food in this array of food objects by property value.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uQhbQ7h-SvCTiwkDqhA99g.png" /></figure><h3>includes replaces redundant loops</h3><ul><li>Similar to the above two details, these are existing functions, that is, we do not have to rewrite the built-in functions, use it wisely will save a lot of time.</li><li>As we all know, a bowl of Kang Mou Fu Lao Tan pickled vegetables and beef noodles has pickled vegetables, noodles, beef grain, cigarette and foot skin, then we want to use the function to confirm whether the noodles have foot skin inside how we write it will be more concise?</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WxjYtY1rws_cPWAkA_ra-A.png" /></figure><ul><li>Similarly, it’s not just Kang Moufu’s pickled beef noodles that can be juggled this way; all similar operations to find a specific element inside an array can be called using the includes function.</li></ul><h3>result return value</h3><ul><li>We usually write some functions with return values when often to return value variable naming and tangled, and even for some long functions do not use variables but directly return, such a habit is actually bad, because the next time we refer to the code also need to re-clear the logic.</li><li>Usually, in a small function, we can use result as the return value.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CfMjzKWRBLY-K0QlXdzHOA.png" /></figure><h3>Returning early</h3><ul><li>However, the above use of result as the return value does not apply to all cases, there are often times when we need to end the function body early to avoid redundant reading of the program by colleagues later.</li><li>The following example when we selectedKey does not exist should immediately return, so that you do not have to continue to read the following code, otherwise the face of more complex functions will increase the cost of reading a lot.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vHGMFq0pe9Ekrd4G66dWTg.png" /></figure><h3>Keep the object intact</h3><ul><li>Often when we get the data returned by the backend through the request will be processed according to some of the properties, if the number of properties to be processed is small, many students will be used to use the first method.</li><li>But in fact, this habit is not good, because when you can not determine whether the function later need to add dependent properties should keep the object intact, as I mentioned in the previous article, learn to embrace change, if getDocDetail not only to use icon and content, there may be title, date and other attributes, so we might as well directly pass the The full object is passed in, which not only adds a shorter list of parameters but also makes the code more readable.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xivAqyOossE6cX3yJ0gJCg.png" /></figure><h3>Using Operators</h3><ul><li>When we need to create a new variable, sometimes we need to check if the variable referenced for its value is null or undefined, so we can use the easy way to write it.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PfzHfTkofpZ9Jyl9ONrMWA.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=50c84dfb5010" width="1" height="1" alt=""><hr><p><a href="https://blog.devgenius.io/a-few-must-learn-javascript-hacks-50c84dfb5010">A few must-learn JavaScript hacks</a> was originally published in <a href="https://blog.devgenius.io/">Dev Genius</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[What is the difference between a cookie and a Token?]]></title>
            <link>https://medium.com/@codehero/what-is-the-difference-between-a-cookie-and-a-token-ea7c43246892?source=rss-6c595310fb60------2</link>
            <guid isPermaLink="false">https://medium.com/p/ea7c43246892</guid>
            <category><![CDATA[front-end-development]]></category>
            <category><![CDATA[cookies]]></category>
            <category><![CDATA[token]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[nodejs]]></category>
            <dc:creator><![CDATA[CodeHero]]></dc:creator>
            <pubDate>Wed, 27 Jul 2022 16:42:40 GMT</pubDate>
            <atom:updated>2022-07-27T16:42:40.279Z</atom:updated>
            <content:encoded><![CDATA[<h3>cookie 和 Token 有什么区别？</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UQKJwBttY8H1QmjruKRIjQ.png" /></figure><h3>曲奇饼</h3><p>Cookies，有时是复数形式，是一些网站为了识别用户和进行会话跟踪而存储在用户本地终端（通常是加密的）上的小型文本文件，由用户的客户端计算机临时或永久存储。让我们解释一下原理。</p><h4>为什么我们需要 cookie？</h4><p>我们都知道一般的接口是通过HTTP协议来交换数据的，而HTTP协议的特点是无状态的，工作前通过三次握手建立连接，工作完成后立即通过四次挥手断开连接，每个连接都是独立，没有状态会被请求串联成一个整体，所以每次都需要重新验证身份，即消耗性能，也给黑客的攻击留下隐患。</p><p>那么cookie的作用是什么，它是为了弥补HTTP无状态的问题，cookie可以作为状态机保存用户的相关登录状态，当第一次认证通过时，服务器可以set-cookie这样客户端会保存自己的cookie，下次再次发送请求时，当服务器检测到客户端发送的cookie与其保存的cookie值一致时，直接信任该连接，不再进行任何认证操作。</p><h3>令牌</h3><p>Token, token, represents the right to perform certain operations of the object, look at the concept of my white, or a good introduction to it. token, in short, is similar to a cookie authentication information, the client through the login authentication, the server will return to the client an encrypted token, and then when the client initiates a connection to the server again, bring Then when the client connects to the server again, it will bring the token with it, and the server will check the token directly to complete the permission verification.</p><h4>Why do you need a Token when you have a cookie?</h4><p>Cookies, as the HTTP specification, have a long history, so there are some historical problems, such as cross-domain restrictions, and cookies as the content of the HTTP specification, there is a default storage and default sending behavior, there is a certain security problem. Compared to cookies, tokens need to be stored and sent by themselves without cross-domain restrictions, so Token is more flexible and does not have as much “historical baggage” as cookies, and can be more optimized in terms of security.</p><h4>Token Transfer Process</h4><p>The process of passing the Token is similar to that of a cookie, which is still validated and returned, and then stored in the client, carrying the validation information for quick validation when the next request is made.</p><h4>What are the advantages of Token?</h4><p>From the above analysis of Token and Cookie, we know that Cookie stores only 4kb of memory space, so it stores mainly a user id, and other user information is stored in the server’s Session, while Token has no memory limit, user information can be stored in Token and returned to the user for storage, so we can see that Therefore, it can be seen that if cookies are used, all users need to store the corresponding user information in the server’s Session, so if the number of users is very large, this will be a very big performance pressure for the server, while Token returns the user information to the client for storage, which completely avoids this problem.</p><h3>Summary</h3><p>虽然 Token 作为一种更现代的存储方式被广泛采用，但 Cookie 仍然是一种非常重要的认证方式，因此，我们不仅要掌握 Token 认证方式，还要掌握 Cookie，通过比较两种方式，了解它们的区别和优势和弊端，我们可以更好的理解客户端认证的方式，也为我们学习和分析相关的安全问题提供了很好的底层原理支持！</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ea7c43246892" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Why is Nodejs so fast?]]></title>
            <link>https://blog.devgenius.io/why-is-nodejs-so-fast-fd4a606c4300?source=rss-6c595310fb60------2</link>
            <guid isPermaLink="false">https://medium.com/p/fd4a606c4300</guid>
            <category><![CDATA[vuejs]]></category>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[front-end-development]]></category>
            <category><![CDATA[react]]></category>
            <dc:creator><![CDATA[CodeHero]]></dc:creator>
            <pubDate>Sat, 16 Jul 2022 16:27:00 GMT</pubDate>
            <atom:updated>2022-07-17T18:41:57.742Z</atom:updated>
            <content:encoded><![CDATA[<h3>What makes Node.js so fast?</h3><p>When talking about Node.js, the first thing that comes to mind is the speed of execution. So, in this section, we’ll try to figure out why Node.js is faster than others. First, it is important to understand what is meant by “execution speed”.<br>Execution speed can mean anything from computing the Fibonacci sequence to searching a database.<br>Execution speed in the context of Web services is everything it takes to process a request and generate a response to the client. It is the time it takes to process a request, starting with the first connection and ending when the client receives a response.<br>Take a look at a few aspects that help figure out why Node.js is so fast.</p><ul><li>Node.js is single-threaded and asynchronous: this means that all I/O activity does not interfere with other processes, and it is possible to send emails, read and write files, query databases, and so on, all at the same time.</li><li>Each request to the web server does not have a different Node.js process. However, one Node.js process will always be running, listening for connections. All JavaScript code runs in the main thread of the process, and all other I/O activities run in a different thread with little to no latency.</li><li>The virtual machine in Node.js (V8), which is responsible for executing JavaScript, is compiled using JIT. At runtime, the virtual machine can take the source code and compile it into machine code. This means that all frequently used “hot” functions can be compiled to machine code, which speeds up execution.</li></ul><h3>About Asynchronous</h3><p>With the help of the example, we will try to grasp the concept of asynchronous processing.</p><p>Suppose that at the top of a mountain there are 100 balls around. The goal is to get all the balls to the bottom of the mountain in the shortest possible time. Obviously, you can’t press all the balls at once, so you have to press one at a time. At this point there are two options.</p><p>In the first method, you can push a ball and wait for it to reach the bottom before moving on to the next one. However, this method takes a long time to push all the balls to the bottom.</p><p>In the second method, it is possible to push the balls one by one without waiting for them to reach the bottom. Using this method, all 100 balls can be pushed in the shortest possible time.</p><p>The first method is executed synchronously, while the second method is executed asynchronously in this case. The previous example demonstrates how much faster asynchronous execution is than synchronous operation.</p><p>Now that you have sort of mastered the basics of asynchronous programming, let’s see how it can help web server performance.</p><p>Assume that each ball corresponds to a database query. So, if the data is processed synchronously for a large project with many aggregations, searches, etc., code execution will block.</p><p>However, if it is processed asynchronously, all queries can be run simultaneously and then the results collected.<br>On the backend, Node.js is combined with Angular, React, React Native, and Vue.js to provide lightning-fast processing and rendering.</p><h3>Event Loop</h3><p>An event loop is a mechanism responsible for scheduling events in a program that always runs asynchronously with the message initiator.</p><p>When using Node.js, it holds the callback assigned to the operation while the I/O operation is executed, thus allowing to continue processing other events. Once all the necessary data has been collected, the callback is invoked.</p><p>The web server sends all requests to the event loop, which registers operations in the thread pool and assigns callbacks to them.</p><p>Once the request is processed, the callback is invoked. Other demanding activities, such as searching a database, can be executed using callbacks.</p><h3>The role of V8 in optimizing code</h3><p>V8 consists of two types of compilers.</p><ul><li>Complete compilers</li><li>Crankshaft compiler</li></ul><p>The whole compiler is known for its speed and ability to generate generic code. It also converts the abstract syntax tree (AST) of JavaScript functions into generic native code. At this level, it performs only one optimization: inline caching.</p><p>V8 starts a parser thread during code execution and compiles functions to determine which ones are hot and which ones are not. In addition, it captures type feedback, which helps V8 keep track of the types of data being passed through it.</p><p>After identifying “hot” functions and collecting feedback on certain types, V8 attempts to perform an enhanced AST by optimizing the compiler, sometimes called the “Crankshaft” compiler.</p><p>The Crankshaft compiler is slower, but it tries to generate efficient code. It consists of two elements: hydrogen and lithium.</p><p>The Hydrogen compiler works by creating a control flow graph (CFG) from the AST file. The resulting graph is displayed as a static single assignment (SSA) graph.</p><p>With the SSA form and the simple structure of the high-level intermediate representation, the compiler can perform many optimizations, such as method<br>inlining, constant folding, etc.</p><p>The main goal of the Lithium compiler is to convert the optimized HIR into an LIR, which is very similar to machine code, except that it is platform-independent.</p><p>After that, the old, unoptimized code is replaced with optimized code. This helps to execute the code faster.</p><h3>Several best application scenarios</h3><p>In addition to speed, Node.js includes many features that developers can use in a range of applications. Take a look at some of the top Node.js application scenarios.</p><h3>Real-Time Applications</h3><p>When asked, “What is the best application scenario for Node.js?” Real-time applications are the best solution. This is one application that Node.js excels at. Why Node.js is so popular in real-time applications.</p><ul><li>Node.js supports reuse and sharing of Node.js packages used to store library code.</li><li>It leads to fast data synchronization between the server and the client.</li><li>It can easily cope with multiple client requests.</li></ul><p>In short, if real-time data processing and scalability are two important considerations for a project, then Node.js is the best technology to use.</p><p>Not only that, there are many other reasons why Node.js should be used for real-time application development. So, if anyone is wondering why Node.js was chosen to develop real-time applications, this is why.</p><h3>Event-based servers</h3><p>Multiple real-time users must be handled in real-time applications. This is where Node.js comes in handy, as it can handle event-based server responses, enabling non-blocking functionality.</p><h3>Data synchronization</h3><p>Node.js developers use non-blocking I/O functionality. It also allows for fast data transfer between the client and the server.</p><h3>Proxy servers</h3><p>Node.js is ideal whenever an intermediary administrator is needed. To use Node.js as a proxy server, developers must write 20 lines of code. After that, the application will be perfect for streaming data from many sources.</p><h3>Application Monitoring Dashboard</h3><p>Another popular Node.js application is to track website visitors and visualize all real-time activity.</p><p>Real-time statistics about users can be gathered here, and furthermore, targeted interactions with customers can be made by simply opening communication channels when consumers arrive at a specific stage in the channel.</p><p>This is very beneficial to any company because it allows them to see in real time what their consumers or visitors are doing. It also allows them to see their interactions in real time. This data is crucial and companies can use it to improve their services. Thanks to Node.js’ real-time and bi-directional sockets, this is all possible.</p><h3>System Monitoring Dashboard</h3><p>Turning now to the infrastructure side, consider a SaaS provider that wants to provide users with a service monitoring site similar to the GitHub status page.</p><p>The Node.js event loop allows for the creation of a powerful web-based dashboard that can monitor the state of a service asynchronously. With the support of WebSockets, it also pushes data to the client.</p><p>This technology can be used to report the status of public and internal services in real time.</p><p>Consider Network Operations Center (NOC) monitoring applications for financial institutions, telecom operators, or cloud/network/hosting providers, all running on an open Web stack using WebSockets and Node.js rather than Java or Java Applet.</p><h3>Video Streaming</h3><p>Streaming is the process of sending large amounts of data in small batches rather than large batches. For designing video streaming applications, Node.js is a good choice. It is ideal because it comes with a built-in video streaming module.</p><p>It also allows creating writable and readable data streams. You can also manipulate files as they are uploaded using Node.js.</p><p>Node.js is also used by Netflix, the world’s largest streaming service with operations in over 190 countries.</p><p>Netflix’s entire user interface is built on Node.js technology, and Netflix soon chose to use it on several other stack layers because it was so effective.<br>The main goal of Netflix’s development team in adopting Node.js was to create a lightweight software that could render high performance. The new node-based application sped up the loading process by 70%. In addition to this, it led to the following results.</p><ul><li>Improved performance</li><li>Reduced build time</li><li>Enabling user customization</li></ul><h3>Highly Scalable Applications</h3><p>Node.js has become the platform of choice for all applications and platforms with steadily growing user bases. Companies such as Walmart, PayPal, Uber, Netflix, LinkedIn, and many others use Node.js because it allows seamless scaling.</p><p>The cutting-edge technology of Node.js includes features such as clustering modules. It provides load balancing across multiple CPU cores, making it easier to deliver the desired results with smaller modules without running out of RAM.</p><p>Not only that, but Node.js also has a non-blocking event loop system that allows servers to process requests in real time.</p><p>On the development side, Node.js allows for the use of microservices, which further allows for the decomposition of applications into smaller components.</p><p>By efficiently defining and distributing tasks among different teams, the development, deployment, and maintenance of each component of an application can be accelerated.</p><p>With Node.js, modern applications can be scaled up and down as needed. It can also help organizations achieve higher performance with fewer resources.</p><h3>Online Chat</h3><p>Chat applications are the most common scenario for real-time and multi-user applications. Because it is a data-intensive, high-traffic, and lightweight application running across multiple distributed devices, chat applications are one of the biggest scenarios for Node.js.</p><p>Consider the following scenario: There is a separate chat room on the website where individuals can come and exchange messages. Assume that there are three people on the site who have access to the message board.<br>In this case, the server-side Express.js application would implement the following two functions.</p><ul><li>A request handler to serve the web page GET / consisting of a message board and a “send” button to initialize new message input</li><li>The WebSockets server listens to all new messages sent by the WebSocket client.</li></ul><p>On the client side, we have an HTML page with some handlers set up. One of them is the “Send” button click event, which is responsible for getting the incoming message and sending it to the WebSocket. another one is used to listen for new incoming messages sent to the WebSocket client.</p><h3>Summary</h3><p>With its lightning-fast execution, Node.js has proven to be a lifesaver for many developers and enterprises, and many large companies have taken advantage of this feature of Node.js.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fd4a606c4300" width="1" height="1" alt=""><hr><p><a href="https://blog.devgenius.io/why-is-nodejs-so-fast-fd4a606c4300">Why is Nodejs so fast?</a> was originally published in <a href="https://blog.devgenius.io/">Dev Genius</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A Few Useful JavaScript Optimization Hacks That You Can Learn at a Glance]]></title>
            <link>https://javascript.plainenglish.io/a-few-useful-javascript-optimization-hacks-that-you-can-learn-at-a-glance-e57d5ff90143?source=rss-6c595310fb60------2</link>
            <guid isPermaLink="false">https://medium.com/p/e57d5ff90143</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[front-end-development]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[web-development]]></category>
            <dc:creator><![CDATA[CodeHero]]></dc:creator>
            <pubDate>Tue, 29 Mar 2022 10:40:35 GMT</pubDate>
            <atom:updated>2022-04-05T08:23:28.579Z</atom:updated>
            <content:encoded><![CDATA[<h4>Simple but useful hacks to help optimize your JavaScript code.</h4><h3>Reduce if…else noodle code</h3><ul><li>As soon as we get to writing more than two if…else functions, it’s time to think about whether there’s a better way to optimize them.</li><li>For example, if we need to calculate the price of food at McDonald’s based on the name, you might have to use a better way.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Jex-j_59EZCHuWeXH4Yvfw.png" /></figure><ul><li>The way of writing, as shown above, will have a lot of conditional statements in the code body, and when we want to add a product next time we will need to modify the logic within the function to add another if…else statement, which to some extent also violates the principle of open and closed when we need to add logic to try to extend the software entity to solve the requirements of the change, rather than by modifying the existing code to complete the change.</li><li>This is a very classical way of optimization, we can use a similar Map institution data to save all the goods, here we directly create an object to store.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6MIdaSRuYMxBJSG8lYNeGQ.png" /></figure><ul><li>So that the next time we need to add a commodity we will not need to change the logic of getPrice, of course, here, in fact, most people like to use foodMap directly in the place, I just gave a simple example here to express this idea.</li><li>Then this time there are students who will ask, if I do not want to key only string it, this time you can use the new Map, the idea is a similar, additional expansion of an entity to store changes.</li></ul><h3>Pipeline operations instead of redundant loops</h3><ul><li>There is such a Mcdonald&#39;s food list.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Y2_2s75XHy--tUITy2JXZA.png" /></figure><ul><li>If you wanted to find the food belonging to group 1, how would you find it?</li><li>The above method is the one we used to use, obviously we replace it with using filter and map instead of for loop not only to make the code more concise but also to make the semantics clearer so that we can see at once that it is filtering the array first and then reorganizing it.</li></ul><h3>find replaces redundant loops</h3><ul><li>As in the example above, find is useful if we want to find a specific food in this array of food objects by the property value.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TSlAsTALS8wfaFwAbec4uQ.png" /></figure><h3>Includes replaces redundant loops</h3><ul><li>And the above two details are similar to these are existing functions, that is, we do not have to rewrite the built-in function, use it wisely it will save a lot of time.</li><li>As we all know, a bowl of Kang Mou Fu Lao Dan pickled vegetables and beef noodles has pickled vegetables, noodles, beef grain, cigarette and foot skin, then we want to use the function to confirm whether the noodles have foot skin inside how we write it will be more concise?</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OGRZLmaDQeeCLTVmpEgHhA.png" /></figure><ul><li>Similarly, it’s not just Kang Moufu’s pickled beef noodles that can be juggled this way; all similar operations to find a specific element inside an array can be called using the includes function.</li></ul><h3>Result return value</h3><p>We usually write some functions with return values often to return value variable naming and tangled, and even for some long functions do not use variables but directly return, such a habit is actually bad, because the next time we refer to the code also needs to re-clear the logic.</p><p>Usually, in a small function, we can use result as the return value.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6zWnMYnDI_wJLFDJ0zI4Pg.png" /></figure><h3>Early return</h3><ul><li>However, the above use of result as the return value does not apply to all cases, and there are often times when we need to end the function body early to avoid redundant reading of the program by colleagues later.</li><li>The following example when selectedKey does not exist should immediately return, so that you do not have to continue to read the following code, otherwise, the face of more complex functions will increase the cost of reading a lot.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nKG3s8TTV17ERRqolNBc2Q.png" /></figure><h3>Keeping objects intact</h3><ul><li>Often in the request, we get the data returned by the back-end that will be processed according to some of the properties, if the need to deal with fewer properties when many students will be used to use the first method.</li><li>But in fact, this habit is not good, because when you can not determine whether the function later needs to add dependent properties should keep the object intact, as I mentioned in the previous article, learn to embrace change, if getDocDetail not only to use icon and content, there may be title, date and other attributes, so we might as well directly pass the complete object is passed in, which not only adds a shorter list of parameters but also makes the code more readable.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*u51eto91yrpDYZD6Kmv07w.png" /></figure><h3>Using operators in a smart way</h3><ul><li>When we need to create a new variable, sometimes we need to check if the variable referenced for its value is null or undefined, so we can use the easy way to write it.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KGHL-bum-BaRrAUecvsI5g.png" /></figure><p>And there you have it. Thank you for reading.</p><p><em>More content at </em><a href="https://plainenglish.io/"><strong><em>PlainEnglish.io</em></strong></a><em>. Sign up for our </em><a href="http://newsletter.plainenglish.io/"><strong><em>free weekly newsletter</em></strong></a><em>. Follow us on </em><a href="https://twitter.com/inPlainEngHQ"><strong><em>Twitter</em></strong></a><em> and </em><a href="https://www.linkedin.com/company/inplainenglish/"><strong><em>LinkedIn</em></strong></a><em>. Join our </em><a href="https://discord.gg/GtDtUAvyhW"><strong><em>community Discord</em></strong></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e57d5ff90143" width="1" height="1" alt=""><hr><p><a href="https://javascript.plainenglish.io/a-few-useful-javascript-optimization-hacks-that-you-can-learn-at-a-glance-e57d5ff90143">A Few Useful JavaScript Optimization Hacks That You Can Learn at a Glance</a> was originally published in <a href="https://javascript.plainenglish.io/">JavaScript in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[5 Killer JavaScript Functions for Efficient Development]]></title>
            <link>https://javascript.plainenglish.io/5-javascript-killer-functions-for-efficient-development-f9d2400f1df7?source=rss-6c595310fb60------2</link>
            <guid isPermaLink="false">https://medium.com/p/f9d2400f1df7</guid>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[react]]></category>
            <dc:creator><![CDATA[CodeHero]]></dc:creator>
            <pubDate>Mon, 28 Feb 2022 03:40:21 GMT</pubDate>
            <atom:updated>2022-02-28T13:57:20.385Z</atom:updated>
            <content:encoded><![CDATA[<h4>Use these killer JavaScript functions for speeding up your development process.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*b8R3oCn50Sbet9hi" /><figcaption>Photo by <a href="https://unsplash.com/@juanjodev02?utm_source=medium&amp;utm_medium=referral">Juanjo Jaramillo</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>JavaScript is the most critical part of Web development, and speeding up JS development means speeding up off-duty.</p><p><em>The article contains code snippets that do not have any side effects and can be copied and used safely.</em></p><h3>1. Verify that an element is within the visible area</h3><p>When developing web pages, it is often necessary to know whether an element is in the viewport, i.e. whether the user can see it or not. This can be done using the <strong>IntersectionObserver</strong> API.</p><pre>const callback = (entries) =&gt; {<br>  entries.forEach((entry) =&gt; {<br>    if (entry.isIntersecting) {<br>      // `entry.target` 是 dom 元素<br>      console.log(`${entry.target.id} is visible`);<br>    }<br>  });<br>};</pre><pre>const options = {<br>  threshold: 1.0,<br>};</pre><pre>const observer = new IntersectionObserver(callback, options);</pre><pre>const btn = document.getElementById( btn );<br>const bottomBtn = document.getElementById( bottom-btn );</pre><pre>observer.observe(btn);<br>observer.observe(bottomBtn);</pre><p>The <strong>options</strong> parameter customizes the behavior of the Observer. threshold property is generally used and defines the percentage of elements that need to be visible in the visible area when the Observer is triggered.</p><h3>2. Identification devices</h3><p>We usually use window.navigator.userAgent to get the details of the current device for identification</p><pre>onst detectDeviceType = () =&gt;<br>  /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(<br>    navigator.userAgent<br>  )<br>    ?  Mobile <br>    :  Desktop ;</pre><pre>console.log(detectDeviceType());</pre><h3>3. Hidden elements</h3><p>There are two usual methods for CSS to hide elements.</p><ol><li>The visibility of the element can be toggled using style.visibility.</li><li>If you want to remove the element from the entire rendering stream, use the style.display property.</li></ol><pre>const hideElement = (element, removeFromFlow = false) =&gt; {<br>  removeFromFlow<br>    ? (element.style.display =  none )<br>    : (element.style.visibility =  hidden );<br>};</pre><p>If you don’t remove elements from the rendering stream and just hide visibility, the elements will still be drawn and take up view space.</p><p>When rendering long lists, use the style.display property to hide elements that are not in the visible area, in conjunction with the IntersectionObserver API above, can greatly improve rendering performance.</p><h3>4. Get the query parameter on the URL</h3><p>It is recommended to use the URL object. The URL interface is used to parse, construct, normalize and encode URLs, and it is easy to get the query parameters on the links.</p><pre>const url = new URL(window.location.href);<br>const paramValue = url.searchParams.get( paramName );<br>console.log(paramValue);</pre><h3>5. Simple deep copy</h3><pre>const deepCopy = (obj) =&gt; JSON.parse(JSON.stringify(obj));</pre><p>And there you have it. Thank you for reading.</p><p><em>More content at </em><a href="https://plainenglish.io/"><strong><em>PlainEnglish.io</em></strong></a><em>. Sign up for our </em><a href="http://newsletter.plainenglish.io/"><strong><em>free weekly newsletter</em></strong></a><em>. Follow us on </em><a href="https://twitter.com/inPlainEngHQ"><strong><em>Twitter</em></strong></a><em> and </em><a href="https://www.linkedin.com/company/inplainenglish/"><strong><em>LinkedIn</em></strong></a><em>. Join our </em><a href="https://discord.gg/GtDtUAvyhW"><strong><em>community Discord</em></strong></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f9d2400f1df7" width="1" height="1" alt=""><hr><p><a href="https://javascript.plainenglish.io/5-javascript-killer-functions-for-efficient-development-f9d2400f1df7">5 Killer JavaScript Functions for Efficient Development</a> was originally published in <a href="https://javascript.plainenglish.io/">JavaScript in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[What is the significance of Suspense for React?]]></title>
            <link>https://blog.devgenius.io/what-is-the-significance-of-suspense-for-react-3b98b341a311?source=rss-6c595310fb60------2</link>
            <guid isPermaLink="false">https://medium.com/p/3b98b341a311</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[react-native]]></category>
            <category><![CDATA[hooks]]></category>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[react]]></category>
            <dc:creator><![CDATA[CodeHero]]></dc:creator>
            <pubDate>Thu, 24 Feb 2022 10:39:55 GMT</pubDate>
            <atom:updated>2022-02-24T18:39:33.728Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*y6C4nSvy2Woe0m7bWEn4BA.png" /></figure><p>Many of you may not have used <strong>Suspense</strong> in your projects, but Suspense is a very important part of React’s future development.</p><p>This article will explain the significance of Suspense for React.</p><h3>React’s an iterative process</h3><p><strong>React</strong> has undergone three major changes in its main features from v16 to v18:</p><ul><li>v16：Async Mode</li><li>v17：Concurrent Mode</li><li>v18：Concurrent Render</li></ul><p>The main feature of React from v16 to v18 has undergone three major changes: to understand the significance of these three changes, you need to first understand a very confusing concept in React — <strong>render</strong>.</p><p>The render function of a ClassComponent is called render when it is executed：</p><pre>class App extends Component {<br>  render() {<br>    // <br>  }<br>}</pre><p>And the process of rendering the result of render to the page is called commit.</p><p>The purpose of Async Mode is to make rendering asynchronous and interruptible.</p><p>The purpose of Concurrent Mode is to make commit concurrent in the user’s perception.</p><p>Since Concurrent Mode includes breaking change, v18 proposes Concurrent Render to reduce the cost of migration for developers.</p><p>So what does “making commit concurrent in user’s perception” mean?</p><h3>The meaning of “concurrency”</h3><p>When it comes to “concurrency”, we have to mention Suspense. consider the following code:</p><pre>const App = () =&gt; {<br>  const [count, setCount] = useState(0);<br>  useEffect(() =&gt; {<br>    setInterval(() =&gt; {<br>      setCount(count =&gt; count + 1);<br>    }, 1000);<br>  }, []);<br>  return (<br>    &lt;&gt;<br>      &lt;Suspense fallback={&lt;div&gt;loading...&lt;/div&gt;}&gt;<br>        &lt;Sub count={count} /&gt;<br>      &lt;/Suspense&gt;<br>      &lt;div&gt;count is {count}&lt;/div&gt;<br>    &lt;/&gt;<br>  );<br>};</pre><ul><li>An update will be triggered every second, updating the state count to count =&gt; count + 1</li><li>In Sub, an asynchronous request is initiated, and before the request returns, the Suspense wrapping Sub renders the fallback</li></ul><p>Assuming the request returns in three seconds, ideally, the page before and after the request is initiated will be displayed in order as:</p><pre>// Before the request is initiated within Sub<br>&lt;div class=“sub”&gt;I am sub, count is 0&lt;/div&gt;<br>&lt;div&gt;count is 0&lt;/div&gt;</pre><pre>// The first second of request initiation within Sub<br>&lt;div&gt;loading...&lt;/div&gt;<br>&lt;div&gt;count is 1&lt;/div&gt;</pre><pre>// Sub request initiated in the 2nd second<br>&lt;div&gt;loading...&lt;/div&gt;<br>&lt;div&gt;count is 2&lt;/div&gt;</pre><pre>// Request initiated in Sub at 3 seconds<br>&lt;div&gt;loading...&lt;/div&gt;<br>&lt;div&gt;count is 3&lt;/div&gt;</pre><pre>// After a successful request within Sub<br>&lt;div class=“sub”&gt;I am sub, request success, count is 4&lt;/div&gt;<br>&lt;div&gt;count is 4&lt;/div&gt;</pre><p>From the user’s point of view, there are two tasks being performed ‘concurrently’ on the page.</p><ol><li>The task of requesting a Sub (observing the change of the first div)</li></ol><p>2. The task of changing the count (observing the change of the second div)</p><p>Suspense brings the feeling of “concurrent execution of multiple tasks in a page”, which is what Concurrent means in React.</p><p>In fact, Suspense is already supported in Async Mode, but the above code behaves as follows in an Async Mode page:</p><pre>// Before the request is initiated within Sub<br>&lt;div class=“sub”&gt;I am sub, count is 0&lt;/div&gt;<br>&lt;div&gt;count is 0&lt;/div&gt;</pre><pre>// The first second of request initiation within Sub<br>&lt;div&gt;loading...&lt;/div&gt;<br>&lt;div&gt;count is 0&lt;/div&gt;</pre><pre>// Sub request initiated in the 2nd second<br>&lt;div&gt;loading...&lt;/div&gt;<br>&lt;div&gt;count is 0&lt;/div&gt;</pre><pre>// Request initiated in Sub at 3 seconds<br>&lt;div&gt;loading...&lt;/div&gt;<br>&lt;div&gt;count is 0&lt;/div&gt;<br><br>// After a successful request within Sub<br>&lt;div class=“sub”&gt;I am sub, request success, count is 4&lt;/div&gt;<br>&lt;div&gt;count is 4&lt;/div&gt;</pre><p>From the user’s point of view, when the “task to request Sub” is executed, the “task to change count” is frozen.</p><p>This is why it is called Async instead of Concurrent.</p><h3><strong>The meaning of Suspense</strong></h3><p>As you can see, for Concurrent, Suspense is an essential part.</p><p>Suspense can be thought of as “dividing the part of the page that needs to be rendered concurrently”.</p><p>For example, in the above example, Suspense divides the “task of requesting Sub” from the “task of changing count” and visually executes concurrently.</p><p>Once the meaning of Suspense is clear, you will see that the next thing React is doing is to keep expanding the Suspense scenarios (that is, to include more scenarios in the scope of concurrent rendering).</p><p>For example, the currently available:</p><ul><li>React.lazy</li><li>Asynchronous requests transformed by the fetch library provided by React</li><li>useTransition</li><li>useDeferredvalue</li></ul><p>To be added in the future:</p><ul><li>Server Component</li><li>Selective Hydration</li></ul><h3>Summary</h3><p>React has evolved from “synchronous” to “asynchronous” and then to “concurrent”.</p><p>Once concurrency is implemented, the next step is to expand the number of scenarios where concurrency can be used, and the role of Suspense is to “divide the parts of the page that need to be rendered concurrently”. The role of Suspense is to “divide the parts of the page that require concurrent rendering”.</p><p>This development path has been decided since the beginning of React, because architecturally speaking, React relies heavily on runtime, and in order to optimize performance, “concurrency” is the optimal development direction under this architecture.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3b98b341a311" width="1" height="1" alt=""><hr><p><a href="https://blog.devgenius.io/what-is-the-significance-of-suspense-for-react-3b98b341a311">What is the significance of Suspense for React?</a> was originally published in <a href="https://blog.devgenius.io/">Dev Genius</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Svelte Principle Analysis and Review]]></title>
            <link>https://blog.devgenius.io/svelte-principle-analysis-and-review-bdf3a50d1258?source=rss-6c595310fb60------2</link>
            <guid isPermaLink="false">https://medium.com/p/bdf3a50d1258</guid>
            <category><![CDATA[react]]></category>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[svelte]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[CodeHero]]></dc:creator>
            <pubDate>Wed, 23 Feb 2022 10:12:02 GMT</pubDate>
            <atom:updated>2022-02-23T19:39:49.124Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3zARWQEUVqY8mn2T5BEEYQ.png" /></figure><h3>Introduction</h3><p>Svelte is a tool for building web applications, similar to JavaScript frameworks like React and Vue, with a heart for making it easier to build interactive user interfaces.</p><p>But there’s one key difference: Svelte converts your application into the ideal JavaScript application during the <strong>build/compile</strong> phase, rather than interpreting the application code during the run phase. This means you don’t pay for the performance consumed by the framework, and there’s no additional loss when the application first loads.</p><p>You can use Svelte to build your entire application, or you can gradually blend it into your existing code. You can also deliver components as standalone packages anywhere, and without the additional overhead of traditional frameworks.</p><h3>Features</h3><h4>Clean code</h4><ul><li>Using svelte, the code is as follows.</li></ul><pre>&lt;script&gt;<br><br>  let animal = &#39;dog&#39;;<br><br>  const showModal = () =&gt; {<br><br>    alert(`My favorite animal is ${animal}`);<br><br>  };<br><br>&lt;/script&gt;<br><br><br><br>&lt;input type=&quot;text&quot; bind:value={animal} /&gt;<br><br>&lt;button on:click={showModal}&gt;弹出&lt;/button&gt;</pre><ul><li>react</li></ul><pre>export default function App() {<br><br>  const [animal, setAnimal] = useState(&#39;dog&#39;);<br><br>  const showModal = () =&gt; {<br><br>    alert(`My favorite animal is ${animal}`);<br><br>  };<br><br>  return (<br><br>    &lt;&gt;<br><br>      &lt;input<br><br>        type=&quot;text&quot;<br><br>        value={animal}<br><br>        onChange={() =&gt; {<br><br>          setAnimal(animal);<br><br>        }}<br><br>      /&gt;<br><br>      &lt;button onClick={showModal}&gt;弹出&lt;/button&gt;<br><br>    &lt;/&gt;<br><br>  );<br><br>}</pre><ul><li>vue</li></ul><pre>&lt;template&gt;<br><br>  &lt;div&gt;<br><br>    &lt;input type=&quot;text&quot; v-model=&quot;animal&quot; /&gt;<br><br>    &lt;button @click=&quot;showModal&quot;&gt;弹出&lt;/button&gt;<br><br>  &lt;/div&gt;<br><br>&lt;/template&gt;<br><br><br><br>&lt;script&gt;<br><br>import { defineComponent, ref } from &#39;vue&#39;;<br><br><br><br>export default defineComponent({<br><br>  setup() {<br><br>    const animal = ref(&#39;dog&#39;);<br><br>    const showModal = () =&gt; {<br><br>      alert(`My favorite animal is ${animal.value}`);<br><br>    };<br><br><br><br>    return {<br><br>      animal,<br><br>      showModal,<br><br>    };<br><br>  },<br><br>});<br><br>&lt;/script&gt;</pre><h4>No virtual dom</h4><p>Svelte is able to compile code into small, framework-independent plain js code, making the application fast both to start and run.</p><p><strong>Better performance</strong></p><p>Many students learning react or vue may have heard comments such as “virtual dom is fast”, so when they see this they wonder why svelte is faster without virtual dom?</p><p>This is actually a misunderstanding, react and vue and other frameworks to achieve the main purpose of virtual dom is not performance, but to cover the underlying dom operations, so that users can build our applications through a declarative, state-driven UI-based way to improve the maintainability of the code.</p><p>Also what react or vue mean by good performance of virtual dom is that the framework can still provide good performance guarantees without any special optimizations to the page. For example, in the following scenario, we re-render the list every time we receive data from the server, and if we do not do special optimizations through ordinary dom operations, we will re-render all the list items every time, and the performance consumption is relatively high. Frameworks such as react mark the list items by key and only re-render the list items that have changed, so the performance is improved.</p><p>Thinking about the above scenario, if we also mark the list items when manipulating the real dom, and only re-render the list items that have changed, eliminating the need for virtual dom diff, then the performance is even higher than the virtual dom.</p><p>svelte then implements this optimization by mapping the data to the real dom, calculating and saving it at compile time through ast, and updating the dom directly when the data changes, which is very fast when initializing and updating since it does not rely on the virtual dom.</p><h4>The real reactivity</h4><p>Svelte adds responsiveness to JavaScript itself without the need for a complex state management library. The responsive implementation of svelte is explained later in the source code interpretation section.</p><h3>Development Trends</h3><p>Svelte is Rich Harris(rollup author), and svelte started open-sourcing in 2016 and began to attract more widespread attention in 2019.</p><p>Svelte on Github is now 49.9k stars.</p><p>The weekly downloads of svelte on Npm are around 15w.</p><p>Although it is still far behind react, vue and angular in terms of star count and downloads, it is understandable given its relatively late debut. Moreover, according to the framework’s research , its user satisfaction and interest are the highest in the past two years, and its use and popularity are increasing rapidly.</p><p>Overall, the future looks promising!</p><h3>Summary</h3><p>Overall, svelte following the front-end three major frameworks to push the new, a new way of thinking to achieve responsive, because the start time is not very long, at present its ecology is not complete, the application in large projects is still to be examined, but in some simple pages such as event pages, static pages and other scenarios feel very suitable at present, personal optimism about its future development.</p><p>Because of its simple syntax and similar characteristics with vue syntax, the start-up cost is very small, we are interested in a little time to understand, to enrich their arsenal.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bdf3a50d1258" width="1" height="1" alt=""><hr><p><a href="https://blog.devgenius.io/svelte-principle-analysis-and-review-bdf3a50d1258">Svelte Principle Analysis and Review</a> was originally published in <a href="https://blog.devgenius.io/">Dev Genius</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Why is the EventLoop for Browsers and Node.js Designed This Way?]]></title>
            <link>https://medium.com/bitsrc/why-is-the-eventloop-for-browsers-and-node-js-designed-this-way-f7f794696c?source=rss-6c595310fb60------2</link>
            <guid isPermaLink="false">https://medium.com/p/f7f794696c</guid>
            <category><![CDATA[react]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[vuejs]]></category>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[web-development]]></category>
            <dc:creator><![CDATA[CodeHero]]></dc:creator>
            <pubDate>Tue, 22 Feb 2022 07:53:13 GMT</pubDate>
            <atom:updated>2025-03-05T11:31:14.790Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*G-LmVEGXlj-UqyARy7wNjg.png" /></figure><p>Event Loop is a basic concept in JavaScript, and it is a must-ask in interviews and often talked about in general.</p><p>Let’s explore the reasons today.</p><h3>The Event Loop for Browsers</h3><p>JavaScript is used to implement web interaction logic, involving DOM operations, if multiple threads operate at the same time need to do synchronous mutually exclusive processing, in order to simplify the design to single-threaded, but if single-threaded, encounter timing logic, network requests and blocked. What can we do?</p><p>We can add a layer of scheduling logic. Encapsulate the JS code into a task queue, and the main thread will keep fetching tasks to execute.</p><p>Each time a task is fetched, a new call stack is created.</p><p>Among them, timers and network requests are actually executed in other threads, and a task is placed in the task queue after execution to tell the main thread that it is ready to move on.</p><p>Because these asynchronous tasks are executed in other threads and then notified to the next main thread through the task queue, it is an event mechanism, so this loop is called Event Loop.</p><p>These asynchronous tasks executed in other threads include timers (setTimeout, setInterval), UI rendering, network requests (XHR or fetch).</p><p>However, the current Event Loop has a serious problem, there is no concept of priority, it is only executed in order, so if there is a high priority task will not be executed in a timely manner. So, we have to design a set of queuing mechanism.</p><p>Then get a high-priority task queue on the good, every execution of a common task, go to all high-priority tasks to finish, and then go to the execution of common tasks.</p><p>With a queueing mechanism in place, high priority tasks can be executed in a timely manner. This is the browser Event Loop.</p><p>The common task is called MacroTask and the high priority task is called MicroTask.</p><p><strong><em>MacroTask includes: </em></strong><strong><em>setTimeout, </em></strong><strong><em>setInterval, </em></strong><strong><em>requestAnimationFrame, Ajax, fetch, script tag code.</em></strong></p><p><strong><em>MicroTask includes: </em></strong><strong><em>Promise.then, </em></strong><strong><em>MutationObserver, </em></strong><strong><em>Object.observe.</em></strong></p><figure><a href="https://bit.cloud/"><img alt="Build in AI speed — Compose enterprise-grade applications, features, and components" src="https://cdn-images-1.medium.com/max/1024/1*yX0vq3scSudyT61IuWFuEg.png" /></a><figcaption>Build in AI speed — Compose enterprise-grade applications, features, and components</figcaption></figure><h4>How to understand the division of macro micro-tasks?</h4><p>Timers, network requests like these are ordinary asynchronous logic that notifies the main thread after other threads have run, so they are all macro tasks.</p><p>MutationObserver and Object.observe are listening to the change of an object, the change is a very instantaneous thing, we must respond immediately, otherwise it may change again, Promise is the organization of the asynchronous process, asynchronous end call then is also very high quality.</p><p>This is the design of the Event Loop in the browser: <strong>the Loop mechanism and Task queue were designed to support asynchrony and solve the problem of logic execution blocking the main thread, and the insertion mechanism of the MicroTask queue was designed to solve the problem of early execution of high performance tasks.</strong></p><p>But later, JS execution environment is not only a browser, there is also Node.js, it also to solve these problems, but it is designed out of the Event Loop more detailed.</p><h3>The Event Loop for Node.js</h3><p>Node.js is a new JS runtime environment that also has to support asynchronous logic, including timers, IO, network requests, and, obviously, Event Loop.</p><p>But the browser set of Event Loop is designed for the browser, and that design is still a bit crude for a high-performance server.</p><h4>What’s crude about it?</h4><p>The browser’s Event Loop is divided into only two levels of priority, one for macro tasks and one for micro tasks. But there is no further prioritization between macro tasks, and no further prioritization between micro tasks.</p><p>For example, the logic of timer Timer has higher priority than the logic of IO, because it involves time, the earlier the more accurate; and the logic of close resource processing has low priority, because not close at most more memory and other resources, the impact is not significant.</p><h4><strong>So the macro task queue was split into five priorities: Timers, Pending, Poll, Check, Close.</strong></h4><p>To explain the five macro tasks.</p><p><strong>Timers Callback:</strong> Involving time, definitely the earlier the execution, the more accurate, so this has the highest priority is easy to understand.</p><p><strong>Pending Callback: </strong>Callback when dealing with network, IO and other exceptions, some *niux systems will wait for the occurrence of errors to be reported, so have to deal with.</p><p><strong>Poll Callback: </strong>Handle IO data, network connection, the server mainly deals with this.</p><p><strong>Check Callback: </strong>The callback to execute setImmediate, characterized by the callback just after the execution of IO.</p><p><strong>Close Callback: </strong>The callback to close the resource, which is executed later and has no impact, and has the lowest priority.</p><p>So, the Event Loop of Node.js is run like this.</p><p>There is one more difference to note in particular.</p><p>Instead of executing one macro task at a time and then executing all the micro-tasks, the Node.js Event Loop executes a certain number of Timers macro tasks, then goes on to execute all the micro-tasks, then executes a certain number of Pending macro tasks, then goes on to execute all the micro-tasks, and the remaining Poll, Check, Close macro tasks.</p><h4>Why is this so?</h4><p>In fact, it is easy to understand by priority.</p><p>Assume that the priority of the macro tasks in the browser is 1, so they are executed sequentially, that is, a macro task, all the micro tasks, then a macro task, then all the micro tasks.</p><p><strong>The Node.js macro tasks are also prioritized, so the Node.js Event Loop runs all the current priority macro tasks one at a time before running the micro tasks and then the next priority macro task.</strong></p><p>That is, a certain number of Timers macrotasks, then all microtasks, then a certain number of Pending Callback macrotasks, then all microtasks.</p><h4>Why do you say a certain number?</h4><p>Because if there are too many macro tasks in one phase, the next phase will not be executed, so there is an upper limit, and the remaining ones will continue to be executed in the next Event Loop.</p><p>In addition to macro tasks with priority, micro-tasks are also divided into priorities, with one more process.nextTick high priority micro-task to run before all the ordinary micro-tasks.</p><p>So, the complete flow of the Event Loop in Node.js is as follows.</p><ul><li><strong>Timers phase: </strong>execute a certain number of timers, i.e. setTimeout, — setInterval callbacks, too many for next execution</li><li><strong>Micro-tasks: </strong>Execute all nextTick micro-tasks, and then execute other common micro-tasks</li><li><strong>Pending phase: </strong>Execute a certain number of IO and network exception callbacks, save them for next time if too many<br>Micro-tasks: Execute all micro-tasks of nextTick, and then execute other normal micro-tasks</li><li><strong>Idle/Prepare phase: </strong>a phase for internal use<br>Micro-task: Execute all micro-tasks of nextTick, and then execute other normal micro-tasks</li><li><strong>Poll phase:</strong> Execute a certain number of data callbacks for files, connection callbacks for network, and save them for next time if there are too many. If there are no IO callbacks and no timers, check phase callbacks to handle, block here and wait for IO events</li><li><strong>Microtasks: </strong>Execute all nextTick microtasks, then execute other normal microtasks</li><li><strong>Check phase: </strong>Execute a certain number of setImmediate callbacks, save them for next execution if too many.</li><li><strong>Micro-task: </strong>execute all micro-tasks of nextTick, and then execute other normal micro-tasks</li><li><strong>Close phase:</strong> execute a certain number of close event callbacks, save them for next execution if there are too many.<br>Micro-task: Execute all the micro-tasks of nextTick, and then execute other normal micro-tasks.</li></ul><p>Compared with the Event Loop in the browser, it is obviously much more complicated, but after our previous analysis, we can understand.</p><p>Node.js prioritizes macro tasks, from high to low, Timers, Pending, Poll, Check, Close, and micro-tasks, i.e., nextTick micro-tasks and other micro-tasks.</p><p>The execution process is to execute a certain number of macrotasks of the current priority (the rest are left for the next loop), then execute the microtasks of process.nextTick, then execute the normal microtasks, and then execute a certain number of macrotasks of the next priority.</p><p>This is a continuous loop. There is also an Idle/Prepare phase for Node.js internal logic, so don’t worry about it.</p><p>It changes the way of executing one macro task at a time in the browser Event Loop, so that high priority macro tasks can be executed earlier, but also sets an upper limit to avoid not being executed in the next phase.</p><p>There is also a special point to note, that is, the poll phase: if the execution reaches the poll phase and finds that the poll queue is empty and the timers queue and check queue have no tasks to execute, then it blocks and waits for IO events, instead of idling. This design is also because the server is mainly dealing with IO, blocking here can respond to IO earlier.</p><p>The overall design of the Event Loop for both JS runtimes is similar, except that the Node.js Event Loop has a more fine-grained division between macro and micro tasks, which is easy to understand because, after all, the Node.js environment is different from the browser, and more importantly, the server side has higher performance requirements.</p><h3>Summary</h3><p>JavaScript was first used to write web interaction logic, and was designed to be single-threaded to avoid the synchronization problem of multiple threads modifying dom at the same time. To solve the blocking problem of single-threaded, a layer of scheduling logic was added, namely Loop loops and Task queues, which put the blocking logic into other threads to run, thus supporting asynchrony. Then to support high-priority task scheduling, a micro-task queue was introduced, which is the browser’s Event Loop mechanism: <strong>one macro task is executed at a time, and then all micro-tasks are executed.</strong></p><p>Node.js is also a JS runtime environment, and it also uses Event Loop to support asynchronous, but the server-side environment is more complex and requires higher performance, so Node.js has a finer-grained prioritization of macros and microtasks.</p><p>Node.js has 5 types of macrotasks, namely Timers, Pending, Poll, Check, Close, and 2 types of microtasks, namely process.nextTick and other microtasks.</p><p>The Event Loop process in Node.js executes a certain number of macrotasks in the current phase (the remaining ones are executed in the next loop), and then executes all microtasks in 6 phases: Timers, Pending, Idle/Prepare, Poll, Check, Close. (Revision: this was the case before node 11, but after node 11, all micro-tasks are executed for each macro task)</p><p>The Idle/Prepare phase is used internally by Node.js, so don’t worry about it.</p><p><strong>Pay special attention to the Poll phase, if the poll queue is If the poll queue is empty and the timers and check queues are also empty, it will block here and wait for IO until the timers and check queues have callbacks and then continue the loop.</strong></p><p>The Event Loop is a set of scheduling logic designed by JS to support asynchronous and task prioritization, with different designs for different environments such as browsers and Node.js (mainly the granularity of task prioritization is different).</p><h3>Build composable web applications</h3><p>Don’t build web monoliths. Use <a href="https://bit.dev/">Bit</a> to create and compose decoupled software components — in your favorite frameworks like React or Node. Build scalable and modular applications with a powerful and enjoyable dev experience.</p><p>Bring your team to <a href="https://bit.cloud/">Bit Cloud</a> to host and collaborate on components together, and greatly speed up, scale, and standardize development as a team. Start with composable frontends like a Design System or Micro Frontends, or explore the composable backend. <a href="https://bit.dev/"><strong>Give it a try →</strong></a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*ctBUj-lpq4PZpMcEF-qB7w.gif" /></figure><h4>Learn More</h4><ul><li><a href="https://blog.bitsrc.io/how-we-build-micro-front-ends-d3eeeac0acfc">How We Build Micro Frontends</a></li><li><a href="https://blog.bitsrc.io/how-we-build-our-design-system-15713a1f1833">How we Build a Component Design System</a></li><li><a href="https://blog.bitsrc.io/the-composable-enterprise-a-guide-609443ae1282">The Composable Enterprise: A Guide</a></li><li><a href="https://blog.bitsrc.io/7-tools-for-faster-frontend-development-in-2022-43b6f663c607">7 Tools for Faster Frontend Development in 2022</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f7f794696c" width="1" height="1" alt=""><hr><p><a href="https://medium.com/bitsrc/why-is-the-eventloop-for-browsers-and-node-js-designed-this-way-f7f794696c">Why is the EventLoop for Browsers and Node.js Designed This Way?</a> was originally published in <a href="https://medium.com/bitsrc">Bits and Pieces</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Top 10 Algorithms to Improve your JavaScript Skills ]]></title>
            <link>https://javascript.plainenglish.io/top-10-algorithms-improve-your-javascript-skills-21507c25ff7?source=rss-6c595310fb60------2</link>
            <guid isPermaLink="false">https://medium.com/p/21507c25ff7</guid>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[software-development]]></category>
            <dc:creator><![CDATA[CodeHero]]></dc:creator>
            <pubDate>Tue, 15 Feb 2022 09:08:08 GMT</pubDate>
            <atom:updated>2022-04-28T06:16:44.858Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/738/1*poemZplwp-3MU-twHJ-mBw@2x.png" /></figure><h3>1. Find the missing number in the array</h3><blockquote>Input: [1, 2, 3, 4, 6, 7, 8, 9, 10] <br>Output: 5</blockquote><pre>const find_missing = function(input) {<br>  let n = input.length + 1;</pre><pre>let sum = 0;<br>  for (let i in input) {<br>    sum += input[i];<br>  }</pre><pre>return Math.floor((n * (n + 1)) / 2) - sum;<br>};</pre><h3>2. Inverting integers</h3><blockquote>Input: num = 123<br>Output: 321<br>Input: num = -123<br>Output: -321</blockquote><pre>const reverse = function(num) {<br>    let result = 0;<br>    while (num !== 0) {<br>      result = result * 10 + num % 10;<br>      // Math.trunc() method will remove the fractional part of the number and keep only the integer part<br>      num = Math.trunc(num / 10);<br>    }</pre><pre>if (result &gt; 2**31 || result &lt; -(2**31)) return 0;<br>    return result;<br>};</pre><h3>3.Array alignment</h3><blockquote>Input: [1,2,3]<br>Output: [[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1]]</blockquote><pre>const permute = function(nums) {<br>    let results = [];</pre><pre>let go = (current) =&gt; {<br>      if (current.length === nums.length){<br>        results.push(current);<br>        return;<br>      }<br>      nums.forEach(n =&gt; {<br>        if (!current.includes(n)){<br>          go([...current, n]);<br>        }<br>      });<br>    }<br>    go([]);<br>    return results;<br>};</pre><h3>4.Alignment in strings</h3><blockquote>Input: s1 = “ab”, s2 = “eidbao”<br>Output: true<br>Input: s1 = “aa”, s2 = “eidbao”<br>Output: false</blockquote><pre>const checkPermutation = function(s1, s2) {<br>  const len1 = s1.length, len2 = s2.length;<br>  if (len1 &gt; len2) return false;</pre><pre>const count = Array(26).fill(0);<br>  for (let i = 0; i &lt; len1; i++) {<br>      count[s1.charCodeAt(i)-97]++;<br>      count[s2.charCodeAt(i)-97]--;<br>  }<br>  if (!count.some(e =&gt; e !== 0)) return true;</pre><pre>for (let i = len1; i &lt; len2; i++) {<br>      count[s2.charCodeAt(i)-97]--;<br>      count[s2.charCodeAt(i-len1)-97]++;<br>      if (!count.some(e =&gt; e !== 0)) return true;<br>  }<br>  return false;<br>};</pre><h3>5.Longest valid brackets</h3><blockquote>Input: “(()”<br>Output: 2<br>Input: “)()())”<br>Output: 4</blockquote><pre>const longestValidParentheses = function(S) {<br>  let stack = [-1], ans = 0;<br>  for (let i = 0; i &lt; S.length; i++)<br>    if (S[i] === &#39;(&#39;) stack.push(i)<br>    else if (stack.length === 1) stack[0] = i<br>    else stack.pop(), ans = Math.max(ans, i - stack[stack.length-1])<br>  return ans<br>};</pre><h3>6.4Sum</h3><pre>const fourSum = function(nums, target) {<br>  let result = [];<br>  let length = nums.length;<br>  if (length &lt; 4) return result; <br>  nums = nums.sort((a, b) =&gt; a - b );</pre><pre>for (let i = 0; i &lt; length - 3; i++) {<br>    if (nums[i] === nums[i - 1]) continue;<br>    for (let j = i + 1; j &lt; length - 2; j++) {<br>      if (j &gt; i + 1 &amp;&amp; nums[j] === nums[j - 1]) continue;</pre><pre>let k = j + 1;<br>      let l = length - 1;</pre><pre>while (k &lt; l) {<br>        const sum = nums[i] + nums[j] + nums[k] + nums[l];</pre><pre>if (sum === target) {<br>          result.push([nums[i], nums[j], nums[k], nums[l]])<br>        }</pre><pre>if (sum &lt;= target) {<br>          k += 1;<br>          while (nums[k] === nums[k - 1]) {<br>            k += 1;<br>          }<br>        }</pre><pre>if (sum &gt;= target) {<br>          l -= 1;<br>          while (nums[l] === nums[l + 1]) {<br>            l -= 1;<br>          }<br>        }<br>      }<br>    }<br>  }</pre><pre>return result;<br>};</pre><h3>7.String multiplication</h3><blockquote>Input: num1 = “2”, num2 = “3”<br>Output: “6”</blockquote><pre>const multiply = function(num1, num2) {<br> if (num1 == 0 || num2 == 0) return ‘0’;<br> const result = [];</pre><pre>for (let a = num1.length — 1; a &gt;= 0; a — ) {<br> for (let b = num2.length — 1; b &gt;= 0; b — ) {<br> const p1 = a + b;<br> const p2 = a + b + 1;<br> const sum = (result[p2] ?? 0) + num1[a] * num2[b];</pre><pre>result[p1] = (result[p1] ?? 0) + Math.floor(sum / 10);<br> result[p2] = sum % 10;<br> }<br> }<br> result[0] == 0 &amp;&amp; result.shift();<br> return result.join(‘’);<br>};</pre><h3>8.Shortest Reply</h3><blockquote>Input: s = “aacecaaa”<br>Output: “aaacecaaa”<br>Input: s = “abcd”<br>Output: “dcbabcd”</blockquote><pre>const shortestPalindrome = function(s) {<br>  let index = 0;<br>  for (let i = s.length - 1; i &gt;= 0; i--) {<br>    if (s[i] === s[index]) index++;<br>  }<br>  if (index === s.length) return s;<br>  let remainingRev = s.substring(index, s.length);<br>  console.log(remainingRev);<br>  remainingRev = reverse(remainingRev);</pre><pre>return remainingRev + shortestPalindrome(s.substring(0, index)) + s.substring(index);<br>};</pre><pre>function reverse(string) {<br>  let myString = &#39;&#39;;<br>  for (let i = string.length - 1; i &gt;= 0; i--) {<br>    myString = myString + string[i];<br>  }<br>  return myString;<br>};</pre><h3>9.Integers to English words</h3><blockquote>Input: num = 123<br>Output: “One Hundred Twenty Three”<br>Input: num = 1234567<br>Output: “One Million Two Hundred Thirty Four Thousand Five Hundred Sixty Seven”</blockquote><pre>const numberToWords = function(num) {<br>  let result = toHundreds(num % 1000);<br>  const bigNumbers = [&quot;Thousand&quot;, &quot;Million&quot;, &quot;Billion&quot;];<br>  for (let i = 0; i &lt; 3; ++i) {<br>    num = Math.trunc(num / 1000);<br>    result = num % 1000 !== 0 ? [toHundreds(num % 1000), bigNumbers[i], result].filter(Boolean).join(&quot; &quot;) : result;<br>  }<br>  return result.length === 0 ? &quot;Zero&quot; : result;<br>}</pre><pre>function toHundreds(num) {<br>  const numbers = [&quot;&quot;, &quot;One&quot;, &quot;Two&quot;, &quot;Three&quot;, &quot;Four&quot;, &quot;Five&quot;, &quot;Six&quot;, &quot;Seven&quot;, &quot;Eight&quot;, &quot;Nine&quot;, &quot;Ten&quot;,<br>    &quot;Eleven&quot;, &quot;Twelve&quot;, &quot;Thirteen&quot;, &quot;Fourteen&quot;, &quot;Fifteen&quot;, &quot;Sixteen&quot;, &quot;Seventeen&quot;, &quot;Eighteen&quot;, &quot;Nineteen&quot;];<br>  const tens = [&quot;&quot;, &quot;&quot;, &quot;Twenty&quot;, &quot;Thirty&quot;, &quot;Forty&quot;, &quot;Fifty&quot;, &quot;Sixty&quot;, &quot;Seventy&quot;, &quot;Eighty&quot;, &quot;Ninety&quot;];<br>  const result = Array(3).fill(&quot;&quot;);<br>  let a = Math.trunc(num / 100), b = num % 100, c = num % 10;<br>  result[0] = a &gt; 0 &amp;&amp; `${numbers[a]} Hundred`;<br>  result[1] = b &lt; 20 ? numbers[b] : tens[Math.trunc(b / 10)]<br>  result[2] = b &gt;= 20 &amp;&amp; `${numbers[c]}`;<br>  return result.filter(Boolean).join(&quot; &quot;);<br>}</pre><h3>10.Ransom note</h3><blockquote>Input: ransomNote = “aa”, magazine = “ab”<br>Output: false<br>Input: ransomNote = “aa”, magazine = “aab”<br>Output: true</blockquote><pre>const canConstruct = function(ransomNote, magazine) {<br> if (ransomNote.length &gt; magazine.length) return false;<br> let magMap = new Map();</pre><pre>for(let char of magazine) {<br> magMap.set(char, (magMap.get(char) || 0 ) + 1);<br> }</pre><pre>for(let note of ransomNote) {<br> let counter = magMap.get(note);<br> if (!counter) return false;</pre><pre>magMap.set(note, — counter);<br> }<br> return true;<br>};</pre><p><em>More content at </em><a href="http://plainenglish.io/"><strong><em>plainenglish.io</em></strong></a><em>. Sign up for our </em><a href="http://newsletter.plainenglish.io/"><strong><em>free weekly newsletter</em></strong></a><em>. Get exclusive access to writing opportunities and advice in our </em><a href="https://discord.gg/GtDtUAvyhW"><strong><em>community Discord</em></strong></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=21507c25ff7" width="1" height="1" alt=""><hr><p><a href="https://javascript.plainenglish.io/top-10-algorithms-improve-your-javascript-skills-21507c25ff7">Top 10 Algorithms to Improve your JavaScript Skills🚀 🦄</a> was originally published in <a href="https://javascript.plainenglish.io/">JavaScript in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>