<?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 Michal Ševčík on Medium]]></title>
        <description><![CDATA[Stories by Michal Ševčík on Medium]]></description>
        <link>https://medium.com/@melkornemesis?source=rss-38e2acf2fbbd------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*6HrwGrGxBxjTxzPUp8cAhQ.png</url>
            <title>Stories by Michal Ševčík on Medium</title>
            <link>https://medium.com/@melkornemesis?source=rss-38e2acf2fbbd------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 16 Nov 2026 22:00:47 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@melkornemesis/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[Top 11 Remote Job Boards to Score Your Next Developer Gig in 2024]]></title>
            <link>https://melkornemesis.medium.com/top-11-remote-job-boards-to-score-your-next-developer-gig-in-2024-d544a3f3779a?source=rss-38e2acf2fbbd------2</link>
            <guid isPermaLink="false">https://medium.com/p/d544a3f3779a</guid>
            <category><![CDATA[remote-work]]></category>
            <category><![CDATA[jobs]]></category>
            <category><![CDATA[hiring]]></category>
            <category><![CDATA[remote-working]]></category>
            <category><![CDATA[software-development]]></category>
            <dc:creator><![CDATA[Michal Ševčík]]></dc:creator>
            <pubDate>Wed, 18 Sep 2024 13:39:09 GMT</pubDate>
            <atom:updated>2024-09-18T13:39:09.605Z</atom:updated>
            <content:encoded><![CDATA[<h4>Imagine working from anywhere in the world, spending more time with family, and enjoying the freedom to design your own schedule.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qXCzUNCorU9q-MfdpAYWZw.jpeg" /></figure><h3>A Decade of Remote Work: My Personal Experience</h3><p>🌍 For the past 10 years, I’ve had the privilege of working remotely. This flexibility has not only allowed me to spend more time with my family, watching my kids grow, but also given me the freedom to live life on my own terms.</p><p>Remote work is more accessible than ever, thanks to fast internet connections, video conferencing tools, and countless resources that make working from anywhere easier.</p><h3>Issues with Existing Remote Job Platforms</h3><p>Having been part of the remote work community for so long, I’ve seen numerous job boards come and go. Over the years, several recurring issues with these platforms have frustrated me.</p><p>That frustration led me to take matters into my own hands.</p><p>Here are a few things that I found challenging with current job boards:</p><p>🚫 Many positions labeled as “remote” are actually hybrid or even on-site.<br>🚫 Limited opportunities for developers, DevOps, Data Engineers, and similar roles.<br>🚫 Job boards are filled with outdated listings, many of which are no longer active.<br>🚫 Access to job details is often hidden behind a paywall.</p><h3>The Motivation Behind Building RemoteYeah</h3><p>This is why my twin brother and I co-founded <a href="https://remoteyeah.com/">RemoteYeah</a>. Our platform is designed to:</p><p>✅ Offer a wide range of remote jobs specifically for software developers.<br>✅ Source jobs from all corners of the internet, beyond the usual LinkedIn or standard job boards.<br>✅️ Continuously update the job listings throughout the day.<br>✅ Use AI to vet every job posting, ensuring it’s fully remote — no hybrid or on-site roles.<br>✅️ Organize roles by areas of expertise such as Front-End, Back-End, DevOps, Data Science, Mobile, Blockchain, and more.<br>✅️ Automatically remove expired listings, keeping the board current.<br>✅️ Stay free for job seekers, with no hidden fees.</p><p>Our mission is to simplify the process for developers seeking remote opportunities. We truly believe remote work is the future, and we’re eager to help as many people as possible find jobs that allow them to work from wherever they choose.</p><p>After a decade of working remotely, we’ve accumulated plenty of knowledge about the remote work lifestyle. We’re excited to share what we’ve learned with you — but we also need your help in spreading the word about RemoteYeah!</p><p>We’re working on the platform during evenings and weekends, and we absolutely love it. If you have any feedback, suggestions, or advice, particularly around SEO or marketing, we’d love to hear from you.</p><h3>11 Remote Job Boards Every Developer Should Know</h3><p>While we’re proud of what we’ve built with RemoteYeah, we also recognize that other fantastic job boards exist, which helped inspire us. If you’re a developer looking for remote opportunities, check out these platforms as well:</p><ol><li><a href="https://weworkremotely.com/">We Work Remotely</a></li><li><a href="https://empllo.com/">empllo</a></li><li><a href="https://cryptojobslist.com/">Crypto Jobs List</a></li><li><a href="https://web3.career/">Web3 Career</a></li><li><a href="https://cryptocurrencyjobs.co/">CryptoCurrencyJobs</a></li><li><a href="https://jsremotely.com/">Js Remotely</a></li><li><a href="https://rubyonremote.com/">RubyOnRemote</a></li><li><a href="https://justremote.co/">JustRemote</a></li><li><a href="https://sveltejobs.com/">SvelteJobs</a></li><li><a href="https://vuejobs.com/">VueJobs</a></li><li><a href="https://remotewoman.com/">RemoteWoman</a></li></ol><p>I hope you find this list useful in your search for a remote job, and I wish you the best in landing your ideal role!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d544a3f3779a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[HTTP Status Code Decoded: A Guide to Understanding 200, 201, 202, and 204]]></title>
            <link>https://melkornemesis.medium.com/http-status-code-decoded-a-guide-to-understanding-200-201-202-and-204-c08904e7f0fe?source=rss-38e2acf2fbbd------2</link>
            <guid isPermaLink="false">https://medium.com/p/c08904e7f0fe</guid>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[http-request]]></category>
            <category><![CDATA[rest]]></category>
            <category><![CDATA[web]]></category>
            <category><![CDATA[rest-api]]></category>
            <dc:creator><![CDATA[Michal Ševčík]]></dc:creator>
            <pubDate>Thu, 29 Dec 2022 19:23:40 GMT</pubDate>
            <atom:updated>2022-12-29T19:28:26.865Z</atom:updated>
            <content:encoded><![CDATA[<h4>Are you confused about the differences between HTTP status codes 200, 201, 202, and 204? You’re not alone! These codes may seem similar, but they actually indicate very different things to web servers and clients. In this article, we’ll break down the nuances of each code and give you some guidelines for when to use them.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mL3VU26j9m_b8criwhDvcQ.jpeg" /></figure><p>HTTP status codes are an important part of the communication process between web servers and clients. These codes provide a standard way for servers to communicate the status of a request to the client, whether it be a web browser, a mobile app, or a server-to-server API call.</p><p>There are many different HTTP status codes, each with its own specific meaning. In this article, we’ll focus on four codes that are often used in web development: 200, 201, 202, and 204.</p><h3>HTTP Status Code 200: OK</h3><p>The HTTP status code 200 is the most common status code and indicates that the request was successful. When a client sends a request to a server, the server responds with a status code to let the client know whether the request was successful or not. A status code of 200 means that the request was successful and that the server was able to fulfill it.</p><p>For example, if a client sends a GET request to a server to retrieve details of a user, the server might respond with a status code of 200 and the user&#39;s details in a JSON format. This tells the client that the request was successful.</p><h4>Request</h4><pre>GET /users/123 HTTP/1.1<br>Host: example.com</pre><h4>Response</h4><pre>HTTP/1.1 200 OK<br>Content-Type: application/json<br><br>{<br>  &quot;id&quot;: 123,<br>  &quot;name&quot;: &quot;John Smith&quot;,<br>  &quot;email&quot;: &quot;john@example.com&quot;<br>}</pre><h3>HTTP Status Code 201: Created</h3><p>The HTTP status code 201 is used to indicate that a request has been fulfilled and that a new resource has been created as a result. This code is typically used in response to a POST request that creates a new resource on the server.</p><p>For example, if a client sends a POST request to create a new user account on a server, the server might respond with a status code of 201 and the new user account information. This tells the client that the request was successful and that the new resource has been created.</p><h4>Request</h4><pre>POST /users HTTP/1.1<br>Host: example.com<br>Content-Type: application/json<br><br>{<br>  &quot;name&quot;: &quot;Jane Doe&quot;,<br>  &quot;email&quot;: &quot;jane@example.com&quot;<br>}</pre><h4>Response</h4><pre>HTTP/1.1 201 Created<br>Content-Type: application/json<br>Location: /users/124<br><br>{<br>  &quot;id&quot;: 124,<br>  &quot;name&quot;: &quot;Jane Doe&quot;,<br>  &quot;email&quot;: &quot;jane@example.com&quot;<br>}</pre><h3>HTTP Status Code 202: Accepted</h3><p>The HTTP status code 202 is used to indicate that a request has been accepted for processing, but the processing has not yet been completed. This code is often used when a server is processing a request asynchronously and does not have an immediate response.</p><p>For example, if a client sends a request to a server to perform a long-running task, such as generating a report, the server might respond with a status code of 202 to indicate that the request has been accepted and is being processed. The client can then check back later to see the status of the task.</p><h4>Request</h4><pre>POST /reports/generate HTTP/1.1<br>Host: example.com<br>Content-Type: application/json<br><br>{<br>  &quot;start_date&quot;: &quot;2022-01-01&quot;,<br>  &quot;end_date&quot;: &quot;2022-01-31&quot;<br>}</pre><h4>Response</h4><pre>HTTP/1.1 202 Accepted<br>Content-Type: application/json<br>Location: /reports/123<br><br>{<br>  &quot;id&quot;: 123,<br>  &quot;status&quot;: &quot;processing&quot;<br>}</pre><p>The Location header is used to provide a URL that the client can use to check the status of the asynchronous task that was requested. The value of the Location header (/reports/123) is simply a unique identifier for the task and does not necessarily have to correspond to a specific resource on the server.</p><p>The Location header is simply a way for the server to provide the client with a way to track the progress of the task. The client can send a request to the URL provided in the Location header to check the status of the task and get any additional information that may be available.</p><p>It’s important to note that the Location header is optional in a response with a status code of 202. The server is not required to provide a Location header, but it can be useful in cases where the client needs to track the progress of the task.</p><h3>HTTP Status Code 204: No Content</h3><p>The HTTP status code 204 is used to indicate that a request was successful, but there is no content to send back to the client. This code is often used in response to a DELETE request, where the server successfully deletes a resource, but there is no content to return to the client.</p><p>For example, if a client sends a DELETE request to delete a user account on a server, the server might respond with a status code of 204 to indicate that the request was successful and the resource was deleted.</p><h4>Request</h4><pre>DELETE /users/123 HTTP/1.1<br>Host: example.com</pre><h4>Response</h4><pre>HTTP/1.1 204 No Content</pre><h3>When to Use These Codes</h3><p>Here are some guidelines for when to use each of these HTTP status codes:</p><ul><li>Use HTTP status code 200 for successful requests that retrieve or update a resource.</li><li>Use HTTP status code 201 for successful requests that create a new resource on the server.</li><li>Use HTTP status code 202 for requests that have been accepted for processing but the processing has not yet been completed.</li><li>Use HTTP status code 204 for successful requests that delete a resource or do not have any content to return.</li></ul><p>It’s important to use the appropriate HTTP status code for each type of request to ensure that clients can correctly interpret the server’s response and take the appropriate action.</p><p>In summary, HTTP status codes 200, 201, 202, and 204 all indicate that a request was successful, but each has specific meanings and should be used in different circumstances. By understanding the differences between these codes, you can effectively communicate the status of a request to clients and build robust and reliable web applications.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c08904e7f0fe" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Mocks vs. Stubs: Choosing the Right Tool for the Job]]></title>
            <link>https://melkornemesis.medium.com/mocks-vs-stubs-choosing-the-right-tool-for-the-job-dbdbc19cf0c5?source=rss-38e2acf2fbbd------2</link>
            <guid isPermaLink="false">https://medium.com/p/dbdbc19cf0c5</guid>
            <category><![CDATA[testing]]></category>
            <category><![CDATA[unit-testing]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[code-quality]]></category>
            <dc:creator><![CDATA[Michal Ševčík]]></dc:creator>
            <pubDate>Wed, 21 Dec 2022 17:01:28 GMT</pubDate>
            <atom:updated>2022-12-21T17:06:44.322Z</atom:updated>
            <content:encoded><![CDATA[<h4>Understanding the Key Differences and Uses of Mocks and Stubs in Unit Testing</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*n3R8SXlj3EoVR7TAPf5cKw.png" /></figure><p>Mock and stub are tools used in unit testing, a type of software testing that involves testing individual units or components of a software application to verify that they are working as expected. A stub is a dummy implementation of a method or object that is used as a placeholder in a test, while a mock is a fake implementation of a method or object that is used to simulate its behavior in a test.</p><p>The main difference between mock and stub is that a stub is used to <strong>provide a specific response to a method call</strong> in order to control the flow of the test, while a mock is used to <strong>verify the behavior of the code under test</strong> by checking whether the correct methods were called and whether they were called with the correct arguments.</p><p>This means that a stub is used to control the test, while a mock is used to assert the behavior of the code under test.</p><p>In general, <strong>stubs are used to replace real implementations of methods or objects in order to simplify the test</strong>, while <strong>mocks are used to verify the behavior of the code under test</strong>. This allows developers to write more focused and more efficient tests, which can help them find and fix defects in their code more quickly and easily.</p><h3>Stub</h3><p>Here is an example of using a stub in a unit test in JavaScript:</p><pre>export class UserService {<br>  constructor(userRepository) {<br>    this.userRepository = userRepository;<br>  }<br><br>  find(userId) {<br>    try {<br>      return this.userRepository.get(userId);<br>    } catch (err) {<br>      return null;<br>    }<br>  }<br>}</pre><pre>import { UserService  } from &quot;./UserService&quot;;<br><br>describe(&#39;UserService&#39;, () =&gt; {<br>  // This is a unit test<br>  test(&#39;returns the user on success&#39;, () =&gt; {<br>    // Create a stub for the user repository<br>    const userRepositoryStub = { get: jest.fn() }<br>    // Set the stub to return a specific value<br>    userRepositoryStub.get.mockReturnValue({ id: 1, role: &#39;admin&#39; });<br>    // Use the stub in the code under test<br>    const sut = new UserService(userRepositoryStub);<br>    // Call the method under test<br>    const user = sut.find(1);<br>    // Verify that the code under test did what it was supposed to do<br>    expect(user).toEqual({ id: 1, role: &#39;admin&#39; })<br>  });<br><br>  // This is a unit test<br>  test(&#39;returns null on failure&#39;, () =&gt; {<br>    const userRepositoryStub = { get: jest.fn() }<br>    // Set the stub to return a specific value<br>    userRepositoryStub.get.mockImplementation(() =&gt; { throw new Error });<br>    // Use the stub in the code under test<br>    const sut = new UserService(userRepositoryStub);<br>    // Call the method under test<br>    const user = sut.find(1);<br>    // Verify that the code under test did what it was supposed to do<br>    expect(user).toEqual(null)<br>  });<br>})</pre><p>In this example, the stub controls the test flow by providing a specific value to the code under test.</p><h3>Mock</h3><p>Here is an example of using a mock in a unit test in JavaScript:</p><pre>export class EmailService {<br>  constructor(mailClient) {<br>    this.mailClient = mailClient;<br>  }<br><br>  sendWelcomeEmail() {<br>    this.mailClient.send(&quot;john@doe.com&quot;, &quot;Welcome&quot;, &quot;Lorem ipsum.&quot;);<br>  }<br>}</pre><pre>import { EmailService } from &#39;./EmailService&#39;<br><br>describe(&#39;EmailService&#39;, () =&gt; {<br>  // This is the unit test<br>  test(&#39;sends welcome email&#39;, () =&gt; {<br>    // Create a mock for the mail client<br>    const mailClientMock = { send: jest.fn() }<br>    // Use the mock in the code under test<br>    const sut = new EmailService(mailClientMock);<br>    // Call the method under test<br>    sut.sendWelcomeEmail();<br>    // Verify that the code under test called the mock with the correct arguments<br>    expect(mailClientMock.send).toHaveBeenCalledWith(&quot;john@doe.com&quot;, &quot;Welcome&quot;, &quot;Lorem ipsum.&quot;)<br>  });<br>})</pre><p>In this example, the mock is used to assert the code&#39;s behavior under test by verifying that it called the send() method on the mailClientMock object with the correct arguments.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=dbdbc19cf0c5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Exploring the Power and Flexibility of the JavaScript Proxy Object. With examples.]]></title>
            <link>https://melkornemesis.medium.com/javascript-proxy-objects-and-why-you-should-care-with-examples-f9773662e779?source=rss-38e2acf2fbbd------2</link>
            <guid isPermaLink="false">https://medium.com/p/f9773662e779</guid>
            <category><![CDATA[proxy]]></category>
            <category><![CDATA[clean-code]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Michal Ševčík]]></dc:creator>
            <pubDate>Fri, 09 Dec 2022 09:35:41 GMT</pubDate>
            <atom:updated>2022-12-09T10:15:59.963Z</atom:updated>
            <content:encoded><![CDATA[<h4>Are you tired of writing boring and repetitive code? The JavaScript Proxy object is here to help! With the power of interception and customization, you can write smarter and more flexible code that can adapt to changing data and requirements. Learn how to use the Proxy object and unlock the full potential of your objects!</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Plunt771n9ql8LIa91iB4g.jpeg" /></figure><p>The JavaScript Proxy object is a powerful and versatile tool that allows you to intercept and customize interactions with objects in your code. In this article, we will explore what the Proxy object is, what problems it solves, and how it can contribute to cleaner, more maintainable code.</p><h3>What is the JavaScript Proxy object?</h3><p>At its core, the JavaScript Proxy object is a way to intercept and modify interactions with objects in your code. It acts as a “proxy” for other objects, allowing you to intercept and customize operations like property access, assignment, and method calls.</p><p>For example, let’s say you have an object that represents a user in your application, with properties like name, email, and age. With the Proxy object, you can intercept access to these properties and validate their values before they are assigned or returned. This can be useful for ensuring that data is valid and consistent, and can help prevent errors and bugs in your code.</p><p>Another common use case for the Proxy object is to provide virtualization or “lazy loading” of object properties. This means that you can define default values or behavior for properties that don’t exist yet, and only create or load the actual values when they are needed. This can be useful for optimizing performance and memory usage, especially in large or complex applications.</p><h3>How does the JavaScript Proxy object work?</h3><p>To use the Proxy object, you first need to create a new Proxy instance and pass in the object that you want to proxy, as well as a handler object that defines the custom behavior for the proxy. The handler object can contain methods like get(), set(), and apply() that are called whenever the corresponding operation is performed on the proxied object.</p><p>Here’s a simple example of how to create a Proxy for an object:</p><pre>const user = { name: &quot;John Doe&quot;, email: &quot;john@doe.com&quot;, age: 30 };<br><br>const userProxy = new Proxy(user, {<br>  get: (target, prop) =&gt; {<br>    // intercept property access<br>    console.log(`Getting property &quot;${prop}&quot;`);<br>    return target[prop];<br>  },<br>  set: (target, prop, value) =&gt; {<br>    // intercept property assignment<br>    console.log(`Setting property &quot;${prop}&quot; to &quot;${value}&quot;`);<br>    target[prop] = value;<br>  }<br>});</pre><p>In this example, the userProxy object is a Proxy for the user object, and it intercepts and logs any access or assignment to the user object&#39;s properties.</p><p>Once you have created a Proxy object, you can use it just like you would use the original object. The Proxy object will automatically intercept and handle any operations that you define in the handler object, while still allowing you to access and modify the proxied object’s properties and methods.</p><p>Here’s an example of how to use the userProxy object from the previous example:</p><pre>// access the &quot;name&quot; property of the user object<br>console.log(userProxy.name); // logs &quot;Getting property &quot;name&quot;&quot;, then returns &quot;John Doe&quot;<br><br>// assign a new value to the &quot;age&quot; property of the user object<br>userProxy.age = 35; // logs &quot;Setting property &quot;age&quot; to &quot;35&quot;&quot;</pre><p>As you can see, the userProxy object intercepts access and assignment to the user object&#39;s properties, and logs the corresponding operations before returning the values.</p><h3>What problems does the JavaScript Proxy object solve?</h3><p>The JavaScript Proxy object solves several problems related to object-oriented programming and metaprogramming in JavaScript. Some of the main problems that it solves are:</p><ol><li>Lack of interception and customization: By default, JavaScript objects do not allow you to intercept and customize operations like property access and method calls. This can make it difficult to implement certain design patterns and techniques, such as data validation, lazy loading, method interception, and object-oriented programming.</li><li>Lack of reflection and introspection: JavaScript objects do not provide built-in mechanisms for introspection or the ability to examine and manipulate their own structure and behavior. This can make it difficult to implement dynamic or adaptive code that can respond to changing data or requirements.</li><li>Lack of encapsulation and information hiding: JavaScript objects do not have built-in mechanisms for encapsulation and information hiding or the ability to protect their internal state and implementation details from external access and modification. This can make it challenging to implement modular and reusable code that can be easily maintained and extended.</li></ol><p>The JavaScript Proxy object provides a flexible and powerful solution to these problems. It allows you to intercept and customize operations on objects, reflect and introspect on their structure and behavior, and encapsulate and hide their internal state and implementation details. This can make your code more flexible, maintainable, and efficient and can support a wide range of programming paradigms and techniques.</p><h3>Examples</h3><p>Here are a few examples of good use cases for the JavaScript Proxy object:</p><h4>Data validation</h4><p>You can use the Proxy object to intercept access and assignment to an object’s properties, and validate the data before it is returned or assigned. This can be useful for ensuring that data is correct and consistent, and can help prevent errors and bugs in your code.</p><pre>const user = { name: &quot;John Doe&quot;, email: &quot;john@doe.com&quot;, age: 30 };<br><br>const userProxy = new Proxy(user, {<br>  get: (target, prop) =&gt; {<br>    // validate property values before returning them<br>    if (prop === &quot;name&quot; &amp;&amp; typeof target[prop] !== &quot;string&quot;) {<br>      throw new Error(&quot;Invalid name: must be a string&quot;);<br>    } else if (prop === &quot;email&quot; &amp;&amp; !target[prop].includes(&quot;@&quot;)) {<br>      throw new Error(&quot;Invalid email: must contain an @ symbol&quot;);<br>    } else if (prop === &quot;age&quot; &amp;&amp; (typeof target[prop] !== &quot;number&quot; || target[prop] &lt; 0)) {<br>      throw new Error(&quot;Invalid age: must be a non-negative number&quot;);<br>    }<br>    return target[prop];<br>  },<br>  set: (target, prop, value) =&gt; {<br>    // validate property values before assigning them<br>    if (prop === &quot;name&quot; &amp;&amp; typeof value !== &quot;string&quot;) {<br>      throw new Error(&quot;Invalid name: must be a string&quot;);<br>    } else if (prop === &quot;email&quot; &amp;&amp; !value.includes(&quot;@&quot;)) {<br>      throw new Error(&quot;Invalid email: must contain an @ symbol&quot;);<br>    } else if (prop === &quot;age&quot; &amp;&amp; (typeof value !== &quot;number&quot; || value &lt; 0)) {<br>      throw new Error(&quot;Invalid age: must be a non-negative number&quot;);<br>    }<br>    target[prop] = value;<br>  }<br>});<br><br>// try accessing and modifying the user object&#39;s properties<br>console.log(userProxy.name); // logs &quot;John Doe&quot;<br>console.log(userProxy.email); // logs &quot;john@doe.com&quot;<br>console.log(userProxy.age); // logs 30<br><br>userProxy.name = 123; // throws an error: &quot;Invalid name: must be a string&quot;<br>userProxy.email = &quot;johndoe.com&quot;; // throws an error: &quot;Invalid email: must contain an @ symbol&quot;<br>userProxy.age = -10; // throws an error: &quot;Invalid age: must be a non-negative number&quot;</pre><h4>Property virtualization</h4><p>You can use the Proxy object to provide virtualized or “lazy-loaded” properties for an object. This means that you can define default values or behavior for properties that don’t exist yet, and only create or load the actual values when they are needed. This can be useful for optimizing performance and memory usage, especially in large or complex applications.</p><pre>const user = { name: &quot;John Doe&quot;, email: &quot;john@doe.com&quot;, age: 30 };<br><br>const userProxy = new Proxy(user, {<br>  get: (target, prop) =&gt; {<br>    // create default values for non-existent properties<br>    if (!(prop in target)) {<br>      return `[${prop} not set]`;<br>    }<br>    return target[prop];<br>  }<br>});<br><br>// try accessing the user object&#39;s properties<br>console.log(userProxy.name); // logs &quot;John Doe&quot;<br>console.log(userProxy.email); // logs &quot;john@doe.com&quot;<br>console.log(userProxy.age); // logs 30<br>console.log(userProxy.gender); // logs &quot;[gender not set]&quot;<br>console.log(userProxy.phone); // logs &quot;[phone not set]&quot;</pre><h4>Method interception</h4><p>You can use the Proxy object to intercept calls to an object’s methods, and customize or enhance their behavior. For example, you could use a Proxy to log method calls, measure their performance, or add additional functionality to existing methods.</p><pre>const user = {<br>  name: &quot;John Doe&quot;,<br>  email: &quot;john@doe.com&quot;,<br>  age: 30,<br>  setName(name) {<br>    this.name = name;<br>  },<br>  setEmail(email) {<br>    this.email = email;<br>  }<br>};<br><br>const userProxy = new Proxy(user, {<br>  apply: (target, thisArg, args) =&gt; {<br>    // log method calls and their arguments<br>    console.log(`Called method &quot;${target.name}&quot; with args:`, args);<br>    return target.apply(thisArg, args);<br>  }<br>});<br><br>// try calling the user object&#39;s methods<br>userProxy.setName(&quot;Jane Doe&quot;); // logs &quot;Called method &quot;setName&quot; with args: [&quot;Jane Doe&quot;]&quot;<br>userProxy.setEmail(&quot;jane@doe.com&quot;); // logs &quot;Called method &quot;setEmail&quot; with args: [&quot;jane@doe.com&quot;]&quot;</pre><h4>Object-oriented programming</h4><p>You can use the Proxy object to implement design patterns and techniques from object-oriented programming, such as inheritance, polymorphism, and encapsulation. For example, you could use a Proxy to create a base class or interface for multiple objects, and customize their behavior without modifying the original objects.</p><pre>class Animal {<br>  constructor(name) {<br>    this.name = name;<br>  }<br>  speak() {<br>    return `${this.name} says...`;<br>  }<br>}<br><br>class Dog extends Animal {<br>  speak() {<br>    return `${this.name} barks!`;<br>  }<br>}<br><br>class Cat extends Animal {<br>  speak() {<br>    return `${this.name} meows!`;<br>  }<br>}<br><br>// create a Proxy for the Animal class<br>const AnimalProxy = new Proxy(Animal, {<br>  construct: (target, args, newTarget) =&gt; {<br>    // create a new Animal object<br>    const animal = new target(...args);<br><br>    // create a Proxy for the Animal object<br>    const animalProxy = new Proxy(animal, {<br>      get: (target, prop) =&gt; {<br>        // intercept calls to the &quot;speak&quot; method and customize it<br>        if (prop === &quot;speak&quot;) {<br>          return function() {<br>            return `${target.name} makes a noise...`;<br>          };<br>        }<br>        return target[prop];<br>      }<br>    });<br><br>    return animalProxy;<br>  }<br>});<br><br>// try creating Animal, Dog, and Cat objects<br>const a = new AnimalProxy(&quot;Animal&quot;);<br>const d = new Dog(&quot;Dog&quot;);<br>const c = new Cat(&quot;Cat&quot;);<br><br>// try calling the &quot;speak&quot; method on the Animal, Dog, and Cat objects<br>console.log(a.speak()); // logs &quot;Animal makes a noise...&quot;<br>console.log(d.speak()); // logs &quot;Dog barks!&quot;<br>console.log(c.speak()); // logs &quot;Cat meows!&quot;</pre><h4>Metaprogramming</h4><p>You can use the Proxy object to perform metaprogramming tasks, such as creating dynamic or reflective code that can adapt to changing data or requirements. For example, you could use a Proxy to create a flexible data structure that can grow or shrink based on the data it contains, or to implement a runtime code generation or evaluation system.</p><pre>const data = [<br>  { id: 1, name: &quot;John Doe&quot; },<br>  { id: 2, name: &quot;Jane Doe&quot; },<br>  { id: 3, name: &quot;Bob Smith&quot; }<br>];<br><br>const dataProxy = new Proxy(data, {<br>  get: (target, prop) =&gt; {<br>    // create dynamic properties based on the data<br>    if (Number.isInteger(parseInt(prop))) {<br>      // return the object with the specified id<br>      return target.find(obj =&gt; obj.id === parseInt(prop));<br>    }<br>    return target[prop];<br>  }<br>});<br><br>// try accessing the data array&#39;s properties and elements<br>console.log(dataProxy[0]); // logs { id: 1, name: &quot;John Doe&quot; }<br>console.log(dataProxy[1]); // logs { id: 2, name: &quot;Jane Doe&quot; }<br>console.log(dataProxy[2]); // logs { id: 3, name: &quot;Bob Smith&quot; }<br>console.log(dataProxy.length); // logs 3<br><br>// try accessing dynamic properties based on the data&#39;s id<br>console.log(dataProxy[1].name); // logs &quot;Jane Doe&quot;<br>console.log(dataProxy[3].name); // logs &quot;Bob Smith&quot;<br>console.log(dataProxy[5]); // logs undefined</pre><p>In this example, the dataProxy object is a Proxy for the data array, and it creates dynamic properties based on the id of each object in the array. This allows you to access the objects in the array using their id as the property name, and makes the data more flexible and easier to work with.</p><h3>Summary</h3><p>The JavaScript Proxy object is a powerful and versatile tool that allows you to intercept and customize interactions with objects in your code. This can be useful for implementing design patterns and techniques from object-oriented programming, such as data validation, lazy loading, and method interception, and object-oriented programming. The Proxy object can also be used for metaprogramming tasks, such as creating dynamic or reflective code that can adapt to changing data or requirements. Overall, the JavaScript Proxy object is a valuable and flexible tool that can improve the flexibility, maintainability, and performance of your code.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f9773662e779" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[5 Tips To Boost Your Development Productivity]]></title>
            <link>https://javascript.plainenglish.io/5-tips-to-boost-your-development-productivity-eb91223f2e24?source=rss-38e2acf2fbbd------2</link>
            <guid isPermaLink="false">https://medium.com/p/eb91223f2e24</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[productivity]]></category>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[inspiration]]></category>
            <dc:creator><![CDATA[Michal Ševčík]]></dc:creator>
            <pubDate>Mon, 22 Nov 2021 12:17:42 GMT</pubDate>
            <atom:updated>2021-12-15T08:36:21.243Z</atom:updated>
            <content:encoded><![CDATA[<h4>Avoid spending a lot of precious time on things that can be, for example, just a keyboard shortcut with these simple productivity tips.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Xem1rbG0Fa8DAhtez7mvsA.jpeg" /><figcaption>Source: <a href="https://unsplash.com/photos/BXOXnQ26B7o">https://unsplash.com/photos/BXOXnQ26B7o</a></figcaption></figure><p>Programming is what puts food on my table. And like most developers, I want to be as effective as possible. And it is that as a developer, I spend a lot of time not just writing code but also switching between apps, copy-pasting things, moving stuff around on the screen, and whatnot.</p><p>For example, switching from your code editor to your browser does not take much time. You most probably press <strong>CMD + Tab</strong> and then keep hitting the <strong>Tab </strong>key until you focus on the application you want to switch to.</p><p>The speed of selecting the correct application varies depending on how many apps you have currently open, but let’s say this takes 2 seconds on average. As a developer, you switch between applications what, 500 times a day? 1000 times a day? And the numbers add up. If you switch between code editor, browser, or terminal just 1000 times a day, it’s suddenly around 33 minutes.</p><p>Here are some tips and tricks on how to make your development flow more time-efficient. Please note that this article focused on macOS.</p><h3>1. Caps Lock as a Hyper Key</h3><p>A Hyper Key is a magical key that automatically presses all the standard modifiers — <strong>ctrl, shift, alt, opt</strong>. Why would you need a Hyper Key? Because a lot of easy to reach keyboard shortcuts are already taken by the macOS itself or some application.</p><p>Mapping Caps Lock to a Hyper Key makes room for tons of easy-to-access and easy-to-remember keyboard shortcuts.</p><p>There are several options for how you can turn your Caps Lock into a Hyper Key; off the top of my head, I can recommend:</p><ol><li>Using <strong>Karabiner Elements — </strong><a href="https://holmberg.io/hyper-key/">https://holmberg.io/hyper-key/</a>.</li><li>Using <strong>Better Touch Tool — </strong><a href="https://docs.folivora.ai/docs/1004_hyper_key.html">https://docs.folivora.ai/docs/1004_hyper_key.html</a>.</li></ol><p>I’ve been using <strong>Karabiner Elements,</strong> but it’s really about what works for you. Later in this article, you will see some examples of how I’m using the Hyper Key.</p><h3>2. Alfred App</h3><p>I’ve been using <strong>Alfred App</strong> for over two years now and can’t imagine going back. Alfred offers you a ton of features. I am going to mention just a few that I use the most.</p><h4>Clipboard History</h4><p>This feature saves me a great deal of time. As a developer, I often need to copy multiple things into my clipboard, and having just a single clipboard that gets rewritten is very limiting.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Jt-VYMl9djaAvhccTDAtbQ.png" /><figcaption>Alfred App — Clipboard History Settings</figcaption></figure><p>Pressing <strong>opt+cmd+c </strong>(your shortcut can be different)<strong> </strong>opens up a clipboard history manager where I can easily access all the content I copied with the standard system <strong>cmd+c </strong>shortcut.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VKHJxHVhUzSrZbXF8keGgg.png" /><figcaption>Alfred App — Clipboard History Manager</figcaption></figure><p>You can access not only text but also image screenshots taken with <strong>cmd+ctrl+shift+3</strong> or <strong>cmd+ctrl+shift+4</strong> shortcut.</p><p>There are other apps like <strong>Maccy</strong> or <strong>Clipy</strong> if you prefer something simpler.</p><ul><li>Maccy’s homepage <a href="https://maccy.app/">https://maccy.app/</a>.</li><li>Clipy’s homepage <a href="https://clipy-app.com/">https://clipy-app.com/</a>.</li></ul><h4>Workflows</h4><p>For Alfred features to work, you have to purchase the Alfred PowerPack — <a href="https://www.alfredapp.com/workflows/">https://www.alfredapp.com/workflows/</a>.</p><p>The Workflows can do magic for you. I have a ton of custom-made workflows that have a super simple purpose — open an application or bring the app into focus if it’s already open. Also, this is where I use the Caps Lock as a Hyper Key.</p><ul><li><strong>Caps Lock + W</strong> opens up an IntellJ WebStorm 🔥.</li><li><strong>Caps Lock + T</strong> opens up a terminal 🔥.</li><li><strong>Caps Lock + D</strong> opens up Google Chrome 🔥.</li><li><strong>Caps Lock + M</strong> opens up Facebook Messenger.</li><li><strong>Caps Lock + N </strong>opens up Notes.</li><li><strong>Caps Lock + P </strong>opens up 1Password.</li></ul><p>All in all, I have 16 of these shortcuts to access the applications quickly I use the most frequently. Switching between my IDE, browser, and terminal is a matter of super simple shortcuts. I no longer have to <strong>cmd+tab </strong>through the list of open applications to find the right one.</p><p>See the homepage of the app — <a href="https://www.alfredapp.com/">https://www.alfredapp.com/</a>.</p><h3>3. Window Management</h3><p>Resizing windows, snapping windows, moving windows to a different screen. None of this should be something you do with your mouse. There are a plethora of applications to help you manage your application windows. To name a few — BetterSnapTool, Magnet, Divvy.</p><p>But the one I’m using is <strong>Rectangle — </strong><a href="https://rectangleapp.com/">https://rectangleapp.com/</a>. The rectangle is a replacement for the no longer maintained app Spectacle. It offers the same features and some more.</p><p>I don’t use all of the Magnet options, but here are some of my bindings:</p><ul><li><strong>cmd+opt+ctrl+← </strong>Move application to left third/half/two-thirds of the screen 🔥.</li><li><strong>cmd+opt+ctrl+</strong>→<strong> </strong>Move application to right third/half/two-thirds of the screen 🔥.</li><li><strong>cmd+opt+ctrl+</strong>↑<strong> </strong>Move application to top third/half/two-thirds of the screen.</li><li><strong>cmd+opt+ctrl+</strong>↓<strong> </strong>Move application to bottom third/half/two-thirds of the screen.</li><li><strong>cmd+opt+ctrl+. </strong>Move application to the next screen 🔥.</li><li><strong>cmd+opt+ctrl+, </strong>Move application to the previous screen 🔥.</li><li><strong>cmd+opt+ctrl+enter </strong>Maximize the application’s window.</li></ul><p>All of my window management keyboard shortcuts start with <strong>cmd+opt+ctrl </strong>and then some other key. Super easy to remember, super easy accessible, super fast to use.</p><p>Links to the other window management applications:</p><ul><li><strong>BetterSnapTool — </strong><a href="https://folivora.ai/bettersnaptool">https://folivora.ai/bettersnaptool</a>.</li><li><strong>Magnet</strong> — <a href="https://magnet.crowdcafe.com/">https://magnet.crowdcafe.com/</a>.</li><li><strong>Divvy</strong> — <a href="https://mizage.com/windivvy/">https://mizage.com/windivvy/</a>.</li></ul><h3>4. Keyboard Shortcuts</h3><p>There’s already plenty of keyboard shortcuts available out of the box in macOS.</p><h4>macOS</h4><ul><li><strong>cmd+` </strong>Switch between windows of the focused application (e.g., switching between Google Chrome windows, if you have more)</li><li><strong>cmd+ctrl+space </strong>Open emoji selector. 🔥 😌</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/784/1*7XaMUl3jBMY5VL4D_IndIw.png" /><figcaption>macOS emoji selector</figcaption></figure><h4>Google Chrome</h4><p>Some of these also work in most of the other browsers like Mozilla Firefox or Safari.</p><ul><li><strong>cmd+t</strong> Open new browser tab.</li><li><strong>cmd+l</strong> Focus URL address bar 🔥.</li><li><strong>cmd+f</strong> Search for text in application.</li><li><strong>cmd+g</strong> Highlight next search occurence 🔥.</li><li><strong>cmd+shift+g</strong> Highlight previous search occurence 🔥.</li><li><strong>cmd+shift+[ </strong>or <strong>cmd+opt+←</strong> Go to previous tab.</li><li><strong>cmd+shift+[</strong> or <strong>cmd+opt+</strong>→<strong> </strong>Go to next tab.</li></ul><h4>Extra Tip 🔥🔥🔥</h4><p>Like most developers, I have an external monitor. I find myself very often opening a new tab in the browser, typing an address in (usually youtube.com), and then wanting to grab just that tab to the other monitor and maximizing it.</p><p><strong>Magnet</strong> app (and my keyboard shortcuts) can help me move the window to another screen and maximize it. But I didn’t know how to move the currently selected Google Chrome tab to a new window that I could then move.</p><p>After some Googling, I found a solution. You have to open your Keyboard Preferences, go to the Shortcuts tab and add Google Chrome.app through the <strong>+</strong> button. You create a shortcut for the action, and in the “Menu Title” input, you have to put the same action (case sensitive) from Google Chrome’s menu bar you want to perform. In this case <strong>Move Tab to New Window.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Bnw9YoqHTUJsKqKw8feItA.png" /><figcaption>macOS Keyboard Shortcuts</figcaption></figure><p>So now, the whole process is a matter of just three keyboard shortcuts.</p><ol><li><strong>Caps Lock + ↑</strong> Move the active tab to a new window.</li><li><strong>cmd+opt+ctrl+,</strong> Move to previous display (or . to go to the next display).</li><li><strong>cmd+opt+ctrl+enter</strong> Maximize the browser window.</li></ol><h3>5. More Screen Real Estate</h3><p>These tips are helpful when you work without an external monitor. You want as most screen real estate as possible.</p><h4>Hide macOS Menu Bar and Dock</h4><p>You can get some extra space by hiding the top Menu Bar and the Dock. If you move your mouse to the top edge of the screen, the Menu Bar will reveal. If you move your mouse to the bottom edge of the screen, the Dock will show.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5w9Mtuah4pqPIPrZyk_lDw.png" /><figcaption>macOS hide Menu Bar and Dock</figcaption></figure><h4>Dock Reveal Animation Speed</h4><p>The Dock reveal animation feels too slow. The Dock is hidden to give me some extra space, but when I need it, I need it as fast as possible.</p><p>Disable the animation altogether with this command:</p><pre>defaults write com.apple.dock autohide-time-modifier -int 0;killall Dock<br>defaults write com.apple.dock autohide-delay -float 0;killall Dock</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0b2JoGs0SaDNLXusdVEn4A.gif" /><figcaption>macOS Dock reveal without animation</figcaption></figure><p>If you want the reveal animation to last for a split second, use this:</p><pre>defaults write com.apple.dock autohide-time-modifier -float 0.15;killall Dock</pre><p>To revert back to the default state:</p><pre>defaults delete com.apple.dock autohide-time-modifier;killall Dock<br>defaults delete com.apple.dock autohide-delay;killall Dock</pre><h3>The end</h3><p>I hope that any of these tips will make you work faster on your computer. Feel free to leave a comment with any of your productivity tips and tricks.</p><p>Until next time.</p><p><em>More content at </em><a href="http://plainenglish.io/"><strong><em>plainenglish.io</em></strong></a><em>. Sign up for our</em><strong><em> </em></strong><a href="http://newsletter.plainenglish.io/"><strong><em>free weekly newsletter here</em></strong></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=eb91223f2e24" width="1" height="1" alt=""><hr><p><a href="https://javascript.plainenglish.io/5-tips-to-boost-your-development-productivity-eb91223f2e24">5 Tips To Boost Your Development Productivity</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[JavaScript:  How To Intercept Function and Method Calls]]></title>
            <link>https://javascript.plainenglish.io/javascript-how-to-intercept-function-and-method-calls-b9fd6507ff02?source=rss-38e2acf2fbbd------2</link>
            <guid isPermaLink="false">https://medium.com/p/b9fd6507ff02</guid>
            <category><![CDATA[design-patterns]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[front-end-development]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Michal Ševčík]]></dc:creator>
            <pubDate>Wed, 17 Feb 2021 07:17:54 GMT</pubDate>
            <atom:updated>2021-02-18T06:20:40.013Z</atom:updated>
            <content:encoded><![CDATA[<h4>JavaScript Alpha Guide</h4><h3>JavaScript: How To Intercept Function and Method Calls</h3><h4>Intercepting function or method invocation in JavaScript. Monkey-patching or proxies. Let’s talk about that.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FnH0shEKgBEACEkEtbTQsw.jpeg" /></figure><p>The other day I had an object and needed to know when any of its methods were invoked. There were many methods on that object, and these methods were invoked throughout a lot of files. So it seemed impractical to add an extra line of code after every invocation to get a notification of the invocation.</p><h3>The problem</h3><p>Let’s consider the following object:</p><pre>let myObj = {<br>  multiply(x, y) {<br>    return x * y;<br>  },<br>  squared(x) {<br>    return x ** x;<br>  }<br>};</pre><p>Now every time you call myObj.multiply(x, y) or myObj.squared(x) you want to know that a method was invoked on the myObj object. And in the ideal world, you would like to know which method it was and what arguments it was invoked with. Something like this.</p><pre>interceptMethodCalls(myObj, (fnName, fnArgs) =&gt; { ... });</pre><h3>Monkey-patching</h3><blockquote>“Monkey patching is a technique to add, modify, or suppress the default behavior of a piece of code at runtime without changing its original source code.” <br>https://www.audero.it/blog/2016/12/05/monkey-patching-javascript</blockquote><p>So <strong>monkey-patching</strong> is basically a dynamic replacement of attributes at runtime. How can we go about our problem with monkey-patching?</p><pre>function interceptMethodCalls(obj, fn) {<br>  Object.keys(obj).forEach(key =&gt; { // <strong>(A)</strong><br>    const prop = obj[key];<br>    if (typeof prop === &#39;function&#39;) { // <strong>(B)</strong><br>      const origProp = prop;<br>      obj[key] = (...args) =&gt; { // <strong>(C)</strong><br>        fn(key, args); // <strong>(D)</strong><br>        return Reflect.apply(origProp, obj, args); // <strong>(E)</strong><br>      }<br>    }<br>  });<br>}</pre><p>On line (A), we go through the given object’s property names. On line (B) we check if the object’s property is a function. The magic happens on line (C), where we replace the original function with an anonymous function — this is the <strong>monkey-patching</strong> piece. That anonymous function calls the given fn function (D) with two arguments: 1. the name of the invoked function, 2. the arguments the function was invoked with (as an array). And finally, we’re invoking the original function, using Reflect API.</p><p>This works great 👍.</p><pre>const handleMethodCall = (fnName, fnArgs) =&gt;<br>  console.log(`${fnName} called with `, fnArgs);</pre><pre>interceptMethodCalls(myObj, handleMethodCall);</pre><pre>myObj.multiply(2, 7); // &quot;multiply called with [ 2, 7 ]&quot;<br>myObj.squared(2); // &quot;squared called with [ 2 ]&quot;</pre><p>But. There’s always a but️.</p><p><strong>What the monkey-patching does is that it changes the object in place.</strong> In our case the myObj. After calling interceptMethodCalls(myObj, handleMethodCall); all of the object methods are replaced with different ones — line (C).</p><p>And we don’t want that. There’s a better solution.</p><h3>Proxy</h3><blockquote>“The Proxy object enables you to create a proxy for another object, which can intercept and redefine fundamental operations for that object.”<br><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Proxy">https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Proxy</a></blockquote><p>A JavaScript <strong>Proxy</strong> wraps another object (the target) and allows you to intercept fundamental operations on the target object. Operations like getting a value, setting a value, calling a function. These operations are called <strong>traps</strong>. This sounds exactly like what we’re trying to achieve here.</p><h4>apply trap</h4><blockquote>“The <strong>handler.apply()</strong> method is a trap for a function call.” ~ <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Proxy/Proxy/apply">https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Proxy/Proxy/apply</a></blockquote><p>The apply trap could seem like a good fit. There’s a catch, though. Calling a method on an object is actually two operations.</p><ol><li>Retrieving the function - get trap</li><li>Calling the function - apply trap</li></ol><p>There’s no <strong>trap </strong>for a method call, so we will combine the get and apply traps.</p><p>The working solution is as follows:</p><pre>function interceptMethodCalls(obj, fn) {<br>  return new Proxy(obj, {<br>    get(target, prop) { // <strong>(A)</strong><br>      if (typeof target[prop] === &#39;function&#39;) {<br>        return new Proxy(target[prop], {<br>          apply: (target, thisArg, argumentsList) =&gt; { // <strong>(B)</strong><br>            fn(prop, argumentsList);<br>            return Reflect.apply(target, thisArg, argumentsList);<br>          }<br>        });<br>      } else {<br>        return Reflect.get(target, prop);<br>      }<br>    }<br>  });<br>}</pre><p>It’s a little longer than the monkey-patching solution, but it’s cleaner. <strong>We’re not, at any point, modifying the original object or its methods. We’re just wrapping them in a Proxy.</strong></p><p>On line (A) we set the get trap on the obj parameter. So when we access some method (e.g. myObj.multiply from the example before) this trap is triggered. It’s just a property on the object. And the property’s value is simply a function.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/669/1*4pI93lh_hF0tSBYw8kMUiA.png" /><figcaption>JavaScript Proxies When Intercepting Method Calls</figcaption></figure><p>Now we’re ready to create a proxied version of the retrieved function, which we can access through target[prop]. So we make a new <strong>Proxy</strong>, set up the apply trap, and return that <strong>Proxy</strong> instead of the original method.</p><p>So it’s basically a two-step process, but it’s worth it because you change neither the object nor its methods.</p><h3>Playground</h3><p>You can have a play with the code above at <a href="https://repl.it/@MelkorNemesis/Intercept-Method-Calls">https://repl.it/@MelkorNemesis/Intercept-Method-Calls</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b9fd6507ff02" width="1" height="1" alt=""><hr><p><a href="https://javascript.plainenglish.io/javascript-how-to-intercept-function-and-method-calls-b9fd6507ff02">JavaScript:  How To Intercept Function and Method Calls</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[How To Add Styles To React Components With Styled Components]]></title>
            <link>https://javascript.plainenglish.io/how-to-add-styles-to-react-components-with-styled-components-62a467c2a726?source=rss-38e2acf2fbbd------2</link>
            <guid isPermaLink="false">https://medium.com/p/62a467c2a726</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[styled-components]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[css]]></category>
            <dc:creator><![CDATA[Michal Ševčík]]></dc:creator>
            <pubDate>Sat, 13 Feb 2021 15:03:56 GMT</pubDate>
            <atom:updated>2021-02-13T15:03:56.348Z</atom:updated>
            <content:encoded><![CDATA[<h4>JavaScript Alpha Guide</h4><h4>Have a look at how you can add extra styles to a React component with styled-components or @emotion/css.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fH7-P5zOe7wpbJl1agNaKw.jpeg" /></figure><p>As a React Front-End developer, you sometimes need to take an existing React component and apply extra styles to it. It could be because you want to extend a 3rd party library component or simply because you want to make more variants of some component in your application.</p><p>Let’s see how we can go about it using <a href="https://github.com/styled-components/styled-components">styled-components</a> or <a href="https://github.com/emotion-js/emotion">@emotion/styled</a>.</p><h3>The result</h3><p>To make sure we’re on the same page, have a look at the following codesandbox. There are two buttons. The blue button is the base button. It could be a button coming from a 3rd party library or a component that comes from your repository. The red button is the alternative version of it. It extends the base button by applying extra styles to it.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fcodesandbox.io%2Fembed%2Fj5qz7&amp;display_name=CodeSandbox&amp;url=https%3A%2F%2Fcodesandbox.io%2Fs%2Fj5qz7&amp;image=https%3A%2F%2Fcodesandbox.io%2Fapi%2Fv1%2Fsandboxes%2Fj5qz7%2Fscreenshot.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=codesandbox" width="1000" height="500" frameborder="0" scrolling="no"><a href="https://medium.com/media/e92fe3aff438eb17a371238cac53151a/href">https://medium.com/media/e92fe3aff438eb17a371238cac53151a/href</a></iframe><h3>Applying Styles To React Component</h3><p>This shows how the MyButton component adds extra styles to the Button component. You take the styled function, and as an argument, you give it the component you want to extend.</p><pre>const MyButton = styled(Button)`<br>  font-weight: bold;<br>  background: red;<br>  border-radius: 10px;</pre><pre>  &amp;:hover {<br>    background: firebrick;<br>  }</pre><pre>  &amp;:active {<br>    background: darkred;<br>  }<br>`;</pre><p>For this to work, the Button component must pass the className prop onto the wrapping element inside.</p><p>The following code shows what the base component looks like.</p><pre>export const ButtonStyled = styled.button`<br>  padding: 20px 25px;<br>  ...<br>`;</pre><pre>export function Button({ children, ...props }) {<br>  return (<br>    &lt;ButtonStyled {...props}&gt; // <strong>(A)</strong><br>      {children}<br>    &lt;/ButtonStyled&gt;<br>  );<br>}</pre><blockquote>A good practice is to spread any non-destructured props onto the wrapping element.</blockquote><p>Here, on line (A) I’m passing the received props onto the wrapping element.</p><p>We need to do this because what styled(Button) does is that it creates a higher-order function that sends className property to the Button component. That className property has as its value a generated CSS class name that holds the definition of our CSS styles.</p><p>If we had a component defined like this, it would not work.</p><pre>export function Button({ children }) {<br>  return (<br>    &lt;ButtonStyled&gt;<br>      {children}<br>    &lt;/ButtonStyled&gt;<br>  );<br>}</pre><h3>Extend Component Not Using Styled Components</h3><p>You can also extend a component that is not based on styled-components.</p><pre>export function Button({ children, className, ...props }) {<br>  const cssClassName = [&quot;my-old-button&quot;, className].join(&quot; &quot;);</pre><pre>  return (<br>    &lt;button className={cssClassName} {...props}&gt;<br>      {children}<br>    &lt;/button&gt;<br>  );<br>}</pre><p>For such a use case, I recommend using an NPM package like <a href="https://www.npmjs.com/package/classnames">classnames</a>. We can then shorten the example to:</p><pre>import <strong>cx</strong> from &#39;classnames&#39;;</pre><pre>export function Button({ children, className, ...props }) {<br>  return (<br>    &lt;button className={<strong>cx(&quot;my-old-button&quot;, className)</strong>} {...props}&gt;<br>      {children}<br>    &lt;/button&gt;<br>  );<br>}</pre><h3>Always Spread Props</h3><p>For us to be able to extend the React component’s styles, we get by with passing through just the className property.</p><p>But I recommend you <strong>spread all of the props that the component receives</strong>.</p><p>There’s an infinite number of use cases where this comes in handy. Starting with little things like adding data-qa attributes for testing purposes. Or adding an <strong>event listener</strong> to the component that the author of the component did not consider.</p><h3>Resources</h3><ul><li><a href="https://styled-components.com/">styled-components</a></li><li><a href="https://emotion.sh/docs/introduction">Introduction</a></li><li><a href="https://www.npmjs.com/package/classnames">classnames</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=62a467c2a726" width="1" height="1" alt=""><hr><p><a href="https://javascript.plainenglish.io/how-to-add-styles-to-react-components-with-styled-components-62a467c2a726">How To Add Styles To React Components With Styled Components</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[Monads For JavaScript Developers]]></title>
            <link>https://javascript.plainenglish.io/monads-for-javascript-developers-af29819823c?source=rss-38e2acf2fbbd------2</link>
            <guid isPermaLink="false">https://medium.com/p/af29819823c</guid>
            <category><![CDATA[functional-programming]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[monads]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Michal Ševčík]]></dc:creator>
            <pubDate>Sun, 07 Feb 2021 17:44:58 GMT</pubDate>
            <atom:updated>2021-02-11T13:11:39.463Z</atom:updated>
            <content:encoded><![CDATA[<h4>JavaScript Alpha Guide</h4><h4>What is a Monad? You don’t have to be a category theory expert to understand. You have to know JavaScript Promises.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gA2dHvfpZEylFTBuiLiKxw.jpeg" /></figure><p>Like every other programmer, I wanted to know, what <strong>Monads</strong> are. But every time you search for Monads on the internet, you get flooded with category theory papers. And other resources don’t seem to make much sense either.</p><p>To learn what Monads are, I did it the hard way. I started learning Haskell. Only to realize, after few months, that people make too much of a fuss of Monads. If you’re a JavaScript developer, you’re most definitely using them daily. You’re just not aware of it.</p><p>We won’t be getting into much detail about the category theory or Haskell, but there’s one thing you need to know. When you search for Monads on the internet, you cannot miss this definition:</p><pre>(&gt;&gt;=) :: m a -&gt; (a -&gt; m b) -&gt; m b</pre><p>This is the definition of a bind operator in Haskell. Different languages have different names for this operation, but they all mean the same thing. Some of the alternative names are chain, bind, flatMap, then, andThen.</p><h3>Monadic Context</h3><pre>(&gt;&gt;=) :: m a -&gt; (a -&gt; m b) -&gt; m b</pre><pre>m    :: monadic context<br>a, b :: value inside the context (string, number, ..)</pre><p><strong>Monadic context</strong> is just a box that implements all that is needed for that box to be a Monad. A very simple (non-monadic) box could be something like this:</p><pre>const Box = val =&gt; ({ val }); <br>const foo = Box(&quot;John&quot;);</pre><p>This is a box—just a wrapped value. The box does not have any behavior because it does not have any methods.</p><blockquote>For something to be a Monad, you must make it behave like a Monad yourself.</blockquote><p>So let’s get back to the (&gt;&gt;=) :: m a -&gt; (a -&gt; m b) -&gt; m b. The (&gt;&gt;=) is used as an infix operator: m a &gt;&gt;= (a -&gt; m b). and the result of the (&gt;&gt;=) operation is m b.</p><h3>The Problem</h3><p>Have you noticed that we have m a, but the function takes a as an argument? That’s what Monads are about.</p><p>The (&gt;&gt;=) operation is about taking a value in a monadic context m a, unwrapping it, so we get just the a and pipelining that to the function (a -&gt; m b). And it’s not magic. You have to code that behavior yourself. We’ll see that later on.</p><h3>JavaScript Promises Are Similar To Monads</h3><p>Better said, they have <em>Monad-ish</em> behavior. For something to be a Monad, it also has to implement a <strong>Functor</strong> and <strong>Applicative</strong> interfaces. I’m mentioning this just for the sake of completeness, but we will not get any deeper into that.</p><p>JavaScript <strong>Promises</strong> implement the monadic interface with .then() method. Let’s see about that.</p><pre>// p :: m a :: Promise { 42 }<br>const p = Promise.resolve(42);</pre><p>This basically creates a box. We have a value 42, inside the <strong>Promise</strong>. <br>☝️ This is our m a.</p><p>Then we have a function that divides a number by two. The input is not wrapped in a <strong>Promise</strong>. But the returned function is wrapped in a <strong>Promise</strong>.</p><pre>// divideByTwo :: (a -&gt; m b)<br>const divideByTwo = val =&gt; Promise.resolve(val / 2);</pre><p>☝️ This is our (a -&gt; m b).</p><p>Again, notice that we have a value 42 inside a <strong>Promise</strong>, but the function divideByTwo accepts an unwrapped value. And we’re still able to chain these.</p><pre>// p :: m a :: Promise { 42 }<br>const p = Promise.resolve(42);<br>// p2 :: m a :: Promise { 21 }<br>const p2 = p.then(divideByTwo);<br>// p3 :: m a :: Promise { 10.5 }<br>const p3 = p2.then(divideByTwo);</pre><p>Or more obviously:</p><pre>// p :: m a :: Promise { 10.5 }<br>const p4 = p.then(divideByTwo).then(divideByTwo);</pre><p><strong>This is the most important feature of Monads.</strong></p><p>You have a value in a box — Promise { 42 }. You have a function that takes the unwrapped value — 42. The types don’t match — m a vs. a. And you’re still able to apply the function to the boxed value.</p><h4>How Is That Possible</h4><p>Because the <strong>Promise</strong> implements the then method to work that way. Most of the time, the code running inside a <strong>Promise</strong> is asynchronous. But the <strong>Promise’s</strong> monad-ish behavior makes it possible for chaining a sequence of functions anyway.</p><p><strong>Monads abstract away auxiliary data management, control flow, or side-effects. </strong>Turning a possibly complicated sequence of functions into a succinct pipeline.</p><h3>Custom Monad-ish Class</h3><p>I put together a very simple example of a monad-ish class in TypeScript. It does not perform any side-effect but allows for the chaining of functions.</p><pre>class Dummy&lt;T&gt; {<br>  constructor(private val: T) {}</pre><pre>  chain&lt;TResult&gt;(fn: (value: T) =&gt; Dummy&lt;TResult&gt;): Dummy&lt;TResult&gt; {<br>    return fn(this.val);<br>  }</pre><pre>  static unit&lt;T&gt;(val: T): Dummy&lt;T&gt; {<br>    return new Dummy(val);<br>  }<br>}</pre><pre>const d = new Dummy(41);<br>d.chain(val =&gt; new Dummy(val + 1))<br> .chain(val =&gt; new Dummy(&quot;The answer is: &quot; + val));</pre><h3><strong>Monad Laws</strong></h3><p>There’re some laws that a class with Monad behavior must follow.</p><ul><li>left identity</li><li>right identity</li><li>associativity</li></ul><p>You can read more about these on the internet. I’ll drop here a snippet of code proving that the Dummy class follows these rules.</p><pre>const m = Dummy.unit(1);<br>const f = (val: number) =&gt; new Dummy(val + 1);<br>const g = (val: number) =&gt; new Dummy(val + 2);</pre><pre>// 1. left identity<br>Dummy.unit(1).chain(f) ==== f(1)</pre><pre>// 2. right identity<br>m.chain(Dummy.unit) ==== m</pre><pre>// 3. associativity<br>const m1 = Dummy.unit(1);<br>m.chain(f).chain(g) ==== m.chain(val =&gt; f(val).chain(g)</pre><p>== or === won’t work here; the object references are different. For that purpose, I’m using ==== that does not exist, but understand it as comparing the inner value of the monad-ish object.</p><h3>Wrapping up</h3><p>I hope this sheds some light on what Monads are. If you’re a JavaScript developer, you’re using them daily. Feeding a value boxed in a <strong>Promise</strong> to a function expecting the unwrapped value. And returning a new value wrapped in the <strong>Promise</strong> again.</p><h3>Resources</h3><ul><li>(A) <a href="https://en.wikipedia.org/wiki/Monad_(functional_programming)">https://en.wikipedia.org/wiki/Monad_(functional_programming)</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=af29819823c" width="1" height="1" alt=""><hr><p><a href="https://javascript.plainenglish.io/monads-for-javascript-developers-af29819823c">Monads For JavaScript Developers</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[Haskell :: (.) . (.) Explained]]></title>
            <link>https://melkornemesis.medium.com/haskell-explained-3f91658a67d3?source=rss-38e2acf2fbbd------2</link>
            <guid isPermaLink="false">https://medium.com/p/3f91658a67d3</guid>
            <category><![CDATA[function-composition]]></category>
            <category><![CDATA[composition]]></category>
            <category><![CDATA[haskell]]></category>
            <category><![CDATA[functional-programming]]></category>
            <dc:creator><![CDATA[Michal Ševčík]]></dc:creator>
            <pubDate>Sun, 10 Jan 2021 19:13:46 GMT</pubDate>
            <atom:updated>2021-01-10T20:08:50.401Z</atom:updated>
            <content:encoded><![CDATA[<h3>Haskell: (.) . (.) Explained</h3><h4>Let’s Get a Grasp of Composition Equivalences in Haskell.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/768/1*7RFXnqGzwyuAgM2h6wTc_A.jpeg" /></figure><p>I’m a JavaScript developer by day and a Haskell fan by night. And just recently, I stumbled upon (.) . (.) in a Haskell. At first, I had no idea whatsoever what this is.</p><p>If you’re facing the same problem, you’ve come to the right place. Let’s see what it is and how do we get there.</p><h3>The dot (.) operator</h3><p>In a Haskell, the . operator is a function composition operator. It is defined as follows:</p><pre>(.) :: (b -&gt; c) -&gt; (a -&gt; b) -&gt; a -&gt; c<br>(.) f g = \x -&gt; f (g x)</pre><p>Most people use the operator as an infix operator, so (.) f g is just the same as f . g.</p><h3>(.) . (.) is f(g x y)</h3><p>Function composition plays well when functions take a single argument. But not so well when the inner function takes more than one argument. And that’s exactly what (.) . (.) is for.</p><p>It’s just a point-free version of f g x y = f(g x y). But how do we get from f g x y = f(g x y) to (.) . (.)?</p><p>First, let’s establish some ground rules.</p><h3>Composition Equivalences</h3><h4>Rule #1</h4><pre>f . g = f(g)</pre><h4>Rule #2</h4><p>Known also as <a href="https://wiki.haskell.org/Section_of_an_infix_operator">left section</a>.</p><pre>(f . ) g = f . g</pre><h4>Rule #3</h4><p>Known also as <a href="https://wiki.haskell.org/Section_of_an_infix_operator">right section</a>.</p><pre>( . g) f = f . g</pre><h4>Rule #4</h4><p>The prefix notation vs. the infix notation.</p><pre>(.) f g = f . g</pre><h4>Rule #5</h4><p>Factoring out a parameter.</p><pre>(f . (g x)) = ((f . ) . g) x</pre><h3>Eta conversion</h3><p>Besides the five rules, we will also need to know about eta conversion.</p><p>f x = abs x is the same as f = abs.</p><p>Going from the first to the second is <strong>eta reduction</strong>. Going from the second to the first would be <strong>eta abstraction.</strong></p><h3>Going from “f(g x y)” to “(.) . (.)”</h3><p>OK, so let’s apply what we’ve learned so far.</p><pre>f g x y = f(g x y)<br>f g x y = (f . (g x)) y // factor out parameter<br>f g x = (f . (g x)) // eta reduction<br>f g x = ((f .) . g)) x // factor out parameter<br>f g = ((f .) . g)) // eta reduction<br>f g = (.) (f .) g // infix notation to prefix notation<br>f = (.) (f .) // eta reduction<br>f = (.) ((.) f) // infix notation to prefix notation<br>f = (.) . (.) f // factor out parameter<br>(.) . (.) // eta reduction</pre><p>And that’s all there’s to it, really. I hope this helps you shed some light on the matter.</p><h3>Resources</h3><ul><li><a href="https://gist.github.com/cscalfani/30ff149a75fc5580d1f8aec61f8e5283">https://gist.github.com/cscalfani/30ff149a75fc5580d1f8aec61f8e5283</a></li><li><a href="https://wiki.haskell.org/Eta_conversion">https://wiki.haskell.org/Eta_conversion</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3f91658a67d3" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[JavaScript: The Power of Recursion]]></title>
            <link>https://javascript.plainenglish.io/javascript-the-power-of-recursion-f56effadf63b?source=rss-38e2acf2fbbd------2</link>
            <guid isPermaLink="false">https://medium.com/p/f56effadf63b</guid>
            <category><![CDATA[functional-programming]]></category>
            <category><![CDATA[recursion]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Michal Ševčík]]></dc:creator>
            <pubDate>Thu, 08 Oct 2020 13:37:10 GMT</pubDate>
            <atom:updated>2020-10-15T14:36:21.320Z</atom:updated>
            <content:encoded><![CDATA[<h4>JavaScript Alpha Guide</h4><h4>All you need is recursion — a small demonstration of how versatile concept recursion is.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4E9jMcPlNFmy-gZyw7_3Zw.jpeg" /></figure><blockquote>To understand recursion, one must first understand recursion.</blockquote><blockquote>— Stephen Hawking</blockquote><p>I couldn’t but notice that a lot of programmers have difficulty understanding recursion. Most of the time, it’s not that they don’t know how to write a recursive function, but more so about how to actually think recursively.</p><p>I will try to show you that it’s not a difficult concept. You have to keep in mind a few things, and we will have a look at these.</p><p>I will focus only on the concept of the recursion itself. PTC (Proper Tail Call), TCO (Tail Call Optimization), and STC (Syntactic Tail Call) will not be covered today. All of the examples will be a JavaScript or a TypeScript code, but the concept is applicable in every language.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/702/1*dwJuXAHygbSZF3fT3RRyfw@2x.png" /></figure><h3>What Is a Recursion</h3><p>Recursion is a useful programming pattern for tasks that can be split into several tasks of the same kind. But simpler.</p><p>It is a programming term that means <strong>calling a function from itself</strong>. When a function calls itself, that’s called a <strong>recursion step</strong>.</p><p><strong>Recursion is when a function calls itself. Until it does not.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/702/1*2SBCbFfmQQOsIt48FDz-tA@2x.png" /></figure><p>Recursion algorithms work well with <a href="https://en.wikipedia.org/wiki/Recursive_data_type">recursively-defined data structures</a>. A recursively-defined data structure is a data structure that can be defined using itself. Using TypeScript, it would look like this:</p><pre>interface List&lt;T&gt; {<br>    value: T,<br>    next: List&lt;T&gt; | null<br>}</pre><pre>const list: List&lt;number&gt; = {<br>    value: 1,<br>    next: {<br>        value: 2,<br>        next: {<br>            value: 3,<br>            next: null<br>        }<br>    }<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/702/1*2SBCbFfmQQOsIt48FDz-tA@2x.png" /></figure><p><strong>Recursive functions don’t necessarily have to return a value.</strong> An example of a recursive function returning a value are functions such as sum, fibonacci, map, filter, reverse.</p><p>But when you have a recursively-defined data structure or <a href="https://www.programiz.com/dsa/trees">tree data structure</a>, you could decide to perform some action when visiting a node. Usually, the recursive function has two arguments — the structure itself and a callback function that gets executed when visiting a node.</p><p>We will focus on recursive functions that return a value.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/702/1*dwJuXAHygbSZF3fT3RRyfw@2x.png" /></figure><h3>Two Cases of a Recursive Function</h3><p>Recursive functions have two cases:</p><ul><li>the edge case — oftentimes called a base case</li><li>the recursive case</li></ul><p>Let’s explain both of these on the following example of a function that sums the elements in a list:</p><pre>function sum(list) {<br>  if (list.length === 0) {<br><strong>    return 0; // (A)</strong><br>  }</pre><pre>  const [x, ...xs] = list;<br><strong>  return x + sum(xs); // (B)</strong><br>}</pre><pre>sum([1, 2, 3]); // 6</pre><p>Line (A) illustrates the edge case. <strong>The</strong> <strong>edge case is very important because that is the point where you stop the recursion.</strong> If you don’t identify an edge case, the recursion will never stop, and you run out of memory.</p><p>Line (B) illustrates the recursive case. <strong>At that point, it still makes sense to call the function itself. </strong>This call creates a new recursion step.</p><figure><img alt="recursive sum function" src="https://cdn-images-1.medium.com/max/1024/1*ILs2Wa8mNlc51-DQkn4rBw.jpeg" /><figcaption>Recursive sum function</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/702/1*dwJuXAHygbSZF3fT3RRyfw@2x.png" /></figure><h3>Finding The Edge Case</h3><p>So how to actually find the edge case? Try to find a solution to the simplest form of the problem. Given the sum function above, what list is the most simple list that you could want to sum? It’s the empty list.</p><blockquote><strong>An empty list is usually the edge case scenario when recursive function operates on a list.</strong></blockquote><p>An empty list is a scenario where a recursive application doesn’t make sense. If you’re dealing with trees, the edge case is usually a node that does not have any children.</p><p>Often the edge case turns out to be an identity. Think of identity as a <strong>neutral element</strong>. What’s a neutral element for an addition? It’s <strong>0</strong>. When you add 0 to something, you get that something back.</p><pre>1   + 0 =   1<br>42  + 0 =  42<br>256 + 0 = 256</pre><p>Similarly, when doing multiplication, the neutral element is <strong>1</strong>. When you multiply something by 1, you get that something back.</p><pre>0   * 1 =   1<br>42  * 1 =  42<br>256 * 1 = 256</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/702/1*dwJuXAHygbSZF3fT3RRyfw@2x.png" /></figure><h3>Heads And Tails</h3><p>When operating on a list, there seems to be a very common pattern. The list is broken to a <strong>head</strong> and a <strong>tail. </strong>You then use the recursive call on only one of them.</p><p>In the following example, the <strong>x</strong> is the <strong>head; </strong>the <strong>xs</strong> is the <strong>tail.</strong></p><pre>const list = [1, 2, 3, 4];<br>const [x, ...xs] = list;</pre><p>Sometimes you need to break the list to get all the elements but the last one, and then the last one separately. Purely functional languages have functions exactly for this, called <strong>init</strong> and <strong>last</strong>. JavaScript does not have a function for this out-of-the-box, so you have to create your own.</p><pre>const list = [1, 2, 3, 4];<br>init(list); // [1, 2, 3]<br>last(list); // [4]</pre><figure><img alt="head, tail, init, last" src="https://cdn-images-1.medium.com/max/1024/1*fcs5W7cnQZw6jmBBDPzjug.png" /><figcaption>head, tail, init, last</figcaption></figure><p>When you break the list to <strong>head </strong>and <strong>tail</strong>, you usually call the recursive function on the <strong>tail</strong>.</p><p>When you break the list to <strong>init</strong> and <strong>last, </strong>you usually call the recursive function on the <strong>init</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/702/1*dwJuXAHygbSZF3fT3RRyfw@2x.png" /></figure><h3>Examples</h3><h4>Product Of a List</h4><p>A product of a list is the first element of the list times the product of the rest of the list. The edge case is an empty list. The neutral element is <strong>1</strong>.</p><pre>function product(list) {<br>  if (list.length === 0) {<br>    return 1;<br>  }</pre><pre>  const [x, ...xs] = list;<br>  return x * product(xs);<br>}</pre><h4>Sum Of a List</h4><p>We’ve seen that one before, but let’s recap. A sum of a list is the first element of the list plus the sum of the rest of the list. The edge case is an empty list. The neutral element is <strong>0</strong>.</p><pre>function sum(list) {<br>  if (list.length === 0) {<br>    return 0;<br>  }</pre><pre>  const [x, ...xs] = list;<br>  return x + sum(xs);<br>}</pre><h4>Length Of a List</h4><p>The length of a list is basically the same as replacing all the list elements with <strong>1</strong> and then adding them up. The edge case is again an empty list. The neutral element is <strong>0.</strong></p><pre>function length(list) {<br>  if (list.length === 0) {<br>    return 0;<br>  }</pre><pre>  const [_, ...xs] = list;<br>  return 1 + length(xs);<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/702/1*2SBCbFfmQQOsIt48FDz-tA@2x.png" /></figure><p>Alright, that seems easy enough. How about map, filter, reduce or zip functions? Can they be implemented with a recursion? Of course.</p><h4>Mapping Over List</h4><p>Mapping over a list is basically 2 things:</p><ol><li>applying the mapping function fn to the first element of the list and putting that to an array</li><li>concatenating the result of step 1 with the map being applied to the rest (or a tail) of the list</li></ol><p>The edge case is an empty array. The neutral element is [], because [].concat([]) is [].</p><pre>function map(fn, list) {<br>  if (list.length === 0) {<br>    return [];<br>  }</pre><pre>  const [x, ...xs] = list;<br>  return [fn(x)].concat(map(fn, xs));<br>}</pre><p>filter and reduce functions are implemented in the same spirit.</p><h4>Filter a List</h4><p>The implementation is basically the same as for map. The only difference is when the predicate function returns false. In such a case, you don’t concatenate right away but rather delegate the value to be appended to the list to the next recursive step.</p><pre>function filter(predicate, list) {<br>  if (list.length === 0) {<br>    return [];<br>  }</pre><pre>  const [x, ...xs] = list;<br>  if (predicate(x)) {<br>    return [x].concat(filter(predicate, xs));<br>  } else {<br>    return filter(predicate, xs);<br>  }<br>}</pre><h4>Reduce a List</h4><p>If you look at the reduce function, it is even more similar to the map than filter is.</p><p>fn is the reducing function that combines the accumulated value with the next value in the list. acc is the reducer’s initial value on the first call and the accumulated value on the subsequent calls.</p><pre>function reduce(fn, acc, list) {<br>  if (list.length === 0) {<br>    return acc;<br>  }<br>  <br>  const [x, ...xs] = list;<br>  return reduce(fn, fn(acc, x), xs);<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/702/1*dwJuXAHygbSZF3fT3RRyfw@2x.png" /></figure><h3>Key Things to Remember</h3><p>When implementing a function that calls itself, always think about:</p><ul><li>what is the edge-case (sometimes called a base case)</li><li>what is the neutral element (sometimes called identity)</li><li>start implementing the function with the edge to cover the simplest form of the problem first</li></ul><p>When working with lists, think about which portion of the list you want to apply the recursive function — is it the tail or the init?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/702/1*2SBCbFfmQQOsIt48FDz-tA@2x.png" /></figure><p>I hope that you now feel a little more confident when it comes to implementing recursion. Keep in mind that I only wanted to demonstrate how to think when implementing functions recursively. Most of these functions already have equivalents in a programming languages of your choice and most probably are much more performant.</p><p>See you next time. <strong>🐺 Alpha, over and out.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/702/1*dwJuXAHygbSZF3fT3RRyfw@2x.png" /></figure><h3>Resources</h3><ul><li><a href="https://en.wikipedia.org/wiki/Recursive_data_type">https://en.wikipedia.org/wiki/Recursive_data_type</a></li><li><a href="http://learnyouahaskell.com/">http://learnyouahaskell.com</a></li><li><a href="https://javascript.info/recursion">https://javascript.info/recursion</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f56effadf63b" width="1" height="1" alt=""><hr><p><a href="https://javascript.plainenglish.io/javascript-the-power-of-recursion-f56effadf63b">JavaScript: The Power of Recursion</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>