<?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 Anirudh Eka on Medium]]></title>
        <description><![CDATA[Stories by Anirudh Eka on Medium]]></description>
        <link>https://medium.com/@anirudheka?source=rss-3e6a3c49e24------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*rFPhbxGvtaLptfmH.</url>
            <title>Stories by Anirudh Eka on Medium</title>
            <link>https://medium.com/@anirudheka?source=rss-3e6a3c49e24------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 16 Nov 2026 17:40:14 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@anirudheka/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[What is a Bug?]]></title>
            <link>https://medium.com/@anirudheka/what-is-a-bug-2085347abff4?source=rss-3e6a3c49e24------2</link>
            <guid isPermaLink="false">https://medium.com/p/2085347abff4</guid>
            <category><![CDATA[functional-programming]]></category>
            <dc:creator><![CDATA[Anirudh Eka]]></dc:creator>
            <pubDate>Thu, 17 Feb 2022 12:40:58 GMT</pubDate>
            <atom:updated>2022-02-17T12:43:36.156Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Zu5_bszJly5eaW7WTdL_Kg.png" /></figure><h4>Don’t blame the app, blame the user! — A strange argument for why all the other people that make up a software team</h4><p>For developers, there are two bugs:</p><ol><li>Application Bug</li><li>User Error</li></ol><p>The first one should be familiar to most people. It happens when an app doesn’t do what it’s supposed to do. The second one is a little harder to spot. It happens when a user doesn’t do what <em>they’re</em> supposed to do. For example, imagine an application that multiplies 2 to whatever input the user gives. Here’s the interface:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/959/1*LwxUfYWfn4koKNpMqXWYwg.png" /></figure><p>Now imagine, a user clicks on ‘calculate’ without putting anything into the input field. The app goes 💥!</p><p>Most people would say the application was not well designed, but we developers know the truth. The application’s not broken, the users are. Yet, for some odd reason, the world doesn’t seem to accept it. Why?</p><h3>A Classic Bug</h3><p>Let’s think of an even simpler issue with our application. Imagine you saw the interface above for the first time. Immediately, you might have some expectations of how the application will work. If you enter a number it will always return the number multiplied by two.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/683/1*e_3Ne6Kdmr4bQ9JKd1bucg.png" /></figure><p>The above illustration is a pure or deterministic function. This means given the same input the function will consistently return the same result. In this case, given a number it will always return two times it. You start playing with it.</p><p>You throw in a 2, you get back 4. Makes sense. Type in 9, you get back 18. Good. 13, you get back 13. What?! The program has a bug! Suddenly the function is no longer deterministic! Given a number, the function sometimes outputs twice the number and sometimes gives back the same number.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/662/1*CWXMJtjovChsGOAhVq-wOQ.png" /></figure><p>It’s almost like the application is doing whatever it wants to. It’s <em>choosing</em>.</p><p>A programmer is sent into the belly of the application to fix the problem. They finds this.</p><pre>const calculate = (userInput) =&gt; !isPrime(userInput) ? userInput * 2 : userInput</pre><p>Each time the user clicks ‘compute’, calculate is executed with what the user puts into the field. But some programmer decided that if the user inputs a prime number, calculate will not multiply two to it. Turns out the program isn’t exercising freedom. There’s logic behind its behavior.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/774/1*pbAjDxqs70EgN75BeRVb7g.png" /></figure><p>When the input number is not prime, it returns twice the input. When the input is prime, it returns the number back. Each kind of input points to only one output. If you look at each arrow as a different path, the user gets to choose with their input what path the application executes.</p><p>Of course these weren’t the options we wanted to give the user. So we delete the isPrime logic.</p><pre>const calculate = (userInput) =&gt; userInput * 2</pre><p>Turns out programs aren’t temperamental. They don’t exercise choice. A program just listens to the rules we give it. If it’s behaving non-deterministically, we know that we messed up one of these rules. In other words, we expect determinism from our programs. We leave choice up to the user.</p><h3>What is Choice?</h3><p>Our fixed application actually exposes an infinite number of paths for the user to take. This illustration:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/683/1*e_3Ne6Kdmr4bQ9JKd1bucg.png" /></figure><p>is actually a short hand for countless different mappings of input to output</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/660/1*p4HlNgSBXYf7W3GxNaWmaA.png" /></figure><p>Why do we even have so many paths? Why can’t we just hard code the result to 4?</p><p>Well, such a program would work if we knew all users would only input two. Unfortunately, the user appears non-deterministic and we have to be ready for whatever they do.</p><p>In the opening example, the user decided to do the unthinkable. They decided to just click ‘calculate’ without putting in any number. 😱 Not one of the infinite paths above account for this scenario. People will quickly say it’s the apps fault, but let’s stand up for the machine for a second.</p><p>What would this look like from the application’s perspective? The app is giving the user inputs with certain expectations. More specifically, the app is giving functions as inputs to the user. It is told that the user will call the function they are given with some number.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/846/1*UgZLaqTAHGZkCo9mzk7hVg.png" /></figure><p>So the app knows it can choose any function; so long as it takes a number as an input. Again, the arrow above is a shorthand for an infinite number of mappings.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/846/1*k4NZTP0OcXGY_GW1o0gHcA.png" /></figure><p>Now, the app tests the user out. It decides to give the user the same input (num) =&gt; num * 2 multiple times. First time, it gets a number. Next time, it gets a number. A third time 💥! The app already frustrated with humanity sends in God to figure out what’s the problem.</p><p>God uncovers choice.</p><pre>const executeWithSomeNumber = (fn) =&gt; fn(choice())</pre><p>Here, fn is the function the app gives as an input. The input to fn comes from the output of a function called choice. This is the source of the non-determinism. Apparently, one time choice didn’t give any value. That’s what blew up the app. But why? Is there a logic to choice?</p><p>When a person puts their hand on a stove, we can be pretty sure they will remove it once it gets hot. That action is technically a choice, but for most people we are guaranteed that every time we introduce the input of a hot stove, we will get this same response.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/835/1*k0ehrYFsd5cfOnewkqVVqA.png" /></figure><p>Even those who do not move their hand can be understood in a deterministic way. Perhaps they don’t move because they have a weak nervous system or just have a need to prove us wrong. Though at first it seems non-deterministic,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/849/1*Z2zEunmYBYUt7IfWK-0eyg.png" /></figure><p>we have basically identified that the result of heating a stove is governed by more inputs than just ‘hand on stove’.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/824/1*fCjzFnHApkVKkGbR0yUhhg.png" /></figure><p>Choice is really just a placeholder for all these circumstances that lead to one and only one output. When the user clicks calculate in our app without inputing a number, there is a logic behind it. There is a reason why the user did what they did even if the reason is subconscious. We claim the reason behind it is ‘choice’ and, out of laziness, that’s usually where our analysis ends. However, choice is not something outside of logic. It is a label for the same logic we see in machines just more complex. Yet we treat it differently. If a human operates unexpectedly we call it the result of a choice, but if a machine operates unexpectedly we call it a bug. Why the double standard?</p><p>What we’re trying to do is integrate two systems, one digital and one biological. Both of their behaviors follow from the inputs they are given. No one here is illogical. If one appears non-deterministic to the other, it is because the other has a simplistic understanding of its partner’s logic. In our example, the software team behind our application believed users will only input numbers when they see this field.</p><p>If we use the word ‘bug’ to mean any unexpected behavior of <em>any</em> system, then from the application’s perspective, the user is the one displaying the bug. Of course we can’t reprogram the user. So it’s the application that needs to adapt. Bugs like this reveal that the app was built with an improper, or simplistic, understanding of the universe it will inhabit. Bugs aren’t a sign of true non-determinism. Bugs emerge from the friction between reality’s actual determinism and the determinism we expect from systems, digital and biological.</p><p>Of course, most of this is just an excuse for not fixing the bug! But it’s also important to communicate with software teams that bugs can be an indication of a poor understanding of our world. That cuts deeper than just the developers. In order to develop software that can exist in the real world, we need business analysis, user experience, user testing, and QA-ing to create a decent model of how the universe may interact with the app.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2085347abff4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Beyonce is privileged and so is My Dad]]></title>
            <description><![CDATA[<div class="medium-feed-item"><p class="medium-feed-image"><a href="https://medium.com/swlh/beyonce-is-privileged-and-so-is-my-dad-72efa57b73b2?source=rss-3e6a3c49e24------2"><img src="https://cdn-images-1.medium.com/max/1920/1*tbmj-3YU_BeGJ14SjnPhaA.png" width="1920"></a></p><p class="medium-feed-snippet">Using Algebra to De-compose Successful People of Color</p><p class="medium-feed-link"><a href="https://medium.com/swlh/beyonce-is-privileged-and-so-is-my-dad-72efa57b73b2?source=rss-3e6a3c49e24------2">Continue reading on The Startup »</a></p></div>]]></description>
            <link>https://medium.com/swlh/beyonce-is-privileged-and-so-is-my-dad-72efa57b73b2?source=rss-3e6a3c49e24------2</link>
            <guid isPermaLink="false">https://medium.com/p/72efa57b73b2</guid>
            <category><![CDATA[math]]></category>
            <category><![CDATA[race]]></category>
            <category><![CDATA[class]]></category>
            <category><![CDATA[intersectionality]]></category>
            <category><![CDATA[racism]]></category>
            <dc:creator><![CDATA[Anirudh Eka]]></dc:creator>
            <pubDate>Thu, 14 Nov 2019 00:58:40 GMT</pubDate>
            <atom:updated>2019-12-17T10:56:26.570Z</atom:updated>
        </item>
        <item>
            <title><![CDATA[Our Last Chance to Save The World]]></title>
            <description><![CDATA[<div class="medium-feed-item"><p class="medium-feed-image"><a href="https://medium.com/@anirudheka/our-last-chance-to-save-the-world-9fb6b69958a6?source=rss-3e6a3c49e24------2"><img src="https://cdn-images-1.medium.com/max/2330/1*-QvYooq9lFX9XlMwkPMdLw.png" width="2330"></a></p><p class="medium-feed-snippet">Radical is the new pragmatic for a world at the brink.</p><p class="medium-feed-link"><a href="https://medium.com/@anirudheka/our-last-chance-to-save-the-world-9fb6b69958a6?source=rss-3e6a3c49e24------2">Continue reading on Medium »</a></p></div>]]></description>
            <link>https://medium.com/@anirudheka/our-last-chance-to-save-the-world-9fb6b69958a6?source=rss-3e6a3c49e24------2</link>
            <guid isPermaLink="false">https://medium.com/p/9fb6b69958a6</guid>
            <category><![CDATA[democratic-socialism]]></category>
            <category><![CDATA[politics]]></category>
            <category><![CDATA[climate-change]]></category>
            <category><![CDATA[environment]]></category>
            <dc:creator><![CDATA[Anirudh Eka]]></dc:creator>
            <pubDate>Thu, 05 Sep 2019 14:12:25 GMT</pubDate>
            <atom:updated>2019-09-11T13:35:04.807Z</atom:updated>
        </item>
        <item>
            <title><![CDATA[Mass Shootings prove that America is the Land of Opportunity]]></title>
            <description><![CDATA[<div class="medium-feed-item"><p class="medium-feed-image"><a href="https://medium.com/@anirudheka/mass-shootings-prove-that-america-is-the-land-of-opportunity-e6765a8dd0e9?source=rss-3e6a3c49e24------2"><img src="https://cdn-images-1.medium.com/max/2474/1*YBEPlydVCKmILjfxLPKcxA.png" width="2474"></a></p><p class="medium-feed-snippet">Our allergy to equal outcomes has denied the average American better health care, higher education, and even their lives.</p><p class="medium-feed-link"><a href="https://medium.com/@anirudheka/mass-shootings-prove-that-america-is-the-land-of-opportunity-e6765a8dd0e9?source=rss-3e6a3c49e24------2">Continue reading on Medium »</a></p></div>]]></description>
            <link>https://medium.com/@anirudheka/mass-shootings-prove-that-america-is-the-land-of-opportunity-e6765a8dd0e9?source=rss-3e6a3c49e24------2</link>
            <guid isPermaLink="false">https://medium.com/p/e6765a8dd0e9</guid>
            <category><![CDATA[healthcare]]></category>
            <category><![CDATA[politics]]></category>
            <category><![CDATA[socialism]]></category>
            <category><![CDATA[gun-control]]></category>
            <dc:creator><![CDATA[Anirudh Eka]]></dc:creator>
            <pubDate>Mon, 26 Aug 2019 12:41:11 GMT</pubDate>
            <atom:updated>2019-08-26T12:41:11.635Z</atom:updated>
        </item>
        <item>
            <title><![CDATA[Seeing The World Without Time]]></title>
            <description><![CDATA[<div class="medium-feed-item"><p class="medium-feed-image"><a href="https://medium.com/swlh/seeing-the-world-without-time-90fce1cbdb01?source=rss-3e6a3c49e24------2"><img src="https://cdn-images-1.medium.com/max/1080/1*TuWVxhKBkqRfghCHnEilIQ.jpeg" width="1080"></a></p><p class="medium-feed-snippet">How functional programming can help us think about society and the justice system</p><p class="medium-feed-link"><a href="https://medium.com/swlh/seeing-the-world-without-time-90fce1cbdb01?source=rss-3e6a3c49e24------2">Continue reading on The Startup »</a></p></div>]]></description>
            <link>https://medium.com/swlh/seeing-the-world-without-time-90fce1cbdb01?source=rss-3e6a3c49e24------2</link>
            <guid isPermaLink="false">https://medium.com/p/90fce1cbdb01</guid>
            <category><![CDATA[philosophy]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[unpopular-opinion]]></category>
            <dc:creator><![CDATA[Anirudh Eka]]></dc:creator>
            <pubDate>Tue, 21 May 2019 12:17:53 GMT</pubDate>
            <atom:updated>2019-05-23T12:21:30.860Z</atom:updated>
        </item>
        <item>
            <title><![CDATA[How to use the spread operator on a function]]></title>
            <description><![CDATA[<div class="medium-feed-item"><p class="medium-feed-image"><a href="https://medium.com/@anirudheka/how-to-use-the-spread-operator-on-a-function-b7dd9d13752a?source=rss-3e6a3c49e24------2"><img src="https://cdn-images-1.medium.com/max/2258/1*DQLbR8U4J_TC-X4TYcq2Pg.png" width="2258"></a></p><p class="medium-feed-snippet">You can&#x2019;t officially do it, but you can write a function that does virtually the same thing. Let&#x2019;s see how and maybe why you should.</p><p class="medium-feed-link"><a href="https://medium.com/@anirudheka/how-to-use-the-spread-operator-on-a-function-b7dd9d13752a?source=rss-3e6a3c49e24------2">Continue reading on Medium »</a></p></div>]]></description>
            <link>https://medium.com/@anirudheka/how-to-use-the-spread-operator-on-a-function-b7dd9d13752a?source=rss-3e6a3c49e24------2</link>
            <guid isPermaLink="false">https://medium.com/p/b7dd9d13752a</guid>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Anirudh Eka]]></dc:creator>
            <pubDate>Mon, 18 Mar 2019 22:45:30 GMT</pubDate>
            <atom:updated>2019-05-15T17:50:16.847Z</atom:updated>
        </item>
        <item>
            <title><![CDATA[A Formula for Happiness]]></title>
            <description><![CDATA[<div class="medium-feed-item"><p class="medium-feed-image"><a href="https://medium.com/@anirudheka/a-functional-programming-guide-to-happy-4988dc6c1764?source=rss-3e6a3c49e24------2"><img src="https://cdn-images-1.medium.com/max/2298/1*1Xfr6ehmVsCFFTc_20pl8g.jpeg" width="2298"></a></p><p class="medium-feed-snippet">How functional programming practices can be applied to the way we think</p><p class="medium-feed-link"><a href="https://medium.com/@anirudheka/a-functional-programming-guide-to-happy-4988dc6c1764?source=rss-3e6a3c49e24------2">Continue reading on Medium »</a></p></div>]]></description>
            <link>https://medium.com/@anirudheka/a-functional-programming-guide-to-happy-4988dc6c1764?source=rss-3e6a3c49e24------2</link>
            <guid isPermaLink="false">https://medium.com/p/4988dc6c1764</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[lifestyle]]></category>
            <category><![CDATA[mindfulness]]></category>
            <category><![CDATA[self]]></category>
            <dc:creator><![CDATA[Anirudh Eka]]></dc:creator>
            <pubDate>Mon, 10 Dec 2018 12:54:18 GMT</pubDate>
            <atom:updated>2019-01-03T08:29:59.081Z</atom:updated>
        </item>
        <item>
            <title><![CDATA[How to avoid looping multiple times through a list while chaining maps, and filters?]]></title>
            <link>https://medium.com/@anirudheka/how-to-avoid-looping-multiple-times-through-a-list-while-chaining-maps-and-filters-e2f113964b49?source=rss-3e6a3c49e24------2</link>
            <guid isPermaLink="false">https://medium.com/p/e2f113964b49</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[transducers]]></category>
            <category><![CDATA[functional-programming]]></category>
            <dc:creator><![CDATA[Anirudh Eka]]></dc:creator>
            <pubDate>Sun, 12 Aug 2018 07:03:51 GMT</pubDate>
            <atom:updated>2018-08-12T07:08:52.201Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/957/1*7o1OqSE_l8HtQp5htnGcvQ.png" /></figure><h3>How do I avoid looping multiple times through a list while chaining maps, and filters?</h3><p>Finding the answer took me step by step to implementing transducers in JavaScript. Id like to take you on this journey so that you too can utilize this powerful abstraction. So, shall we trance?</p><h3>The problem</h3><p>This:</p><pre>[1, 2, 3].map(x =&gt; x + 1).filter(x =&gt; x &gt; 3)</pre><p>And This:</p><pre>[1, 2, 3].reduce((a, x) =&gt; { <br>     let y = x + 1;  <br>     return y &gt; 3 ? a.concat(y) : a}, [])</pre><p>do the same thing. They both add 1 to each number in a list and then keep only the numbers that are greater than 3.</p><p>But deciding which one to use leads us to two important questions:</p><h4>1. Which implementation is more readable?</h4><p>If you are familiar with functional programming idioms then the first implementation should be much more readable. It maps very well to what we wanted the implementations to do,</p><blockquote>…add 1 to each number in a list and then keep only the numbers that are greater than 3.</blockquote><p>So long as you know that map transforms each item of the list by the function it is passed, and filter filters the list by the function it is passed, then the first implementation reads almost like a sentence.</p><p>The second implementation<em> </em>on the other hand follows a more imperative approach. When a new developer sees it they would be staring at <strong>how</strong> it does whatever it does and from that the developer would have to work out what the hell it actually does!</p><p>To be fair the second implementation is also using a functional idiom: reduce (also known as fold in some languages), but this highlights an important point that I find developers miss: <strong>just because you are using map, filter, or reduce, in your Javascript code doesn’t mean your code is as declarative as it could be!</strong></p><h4>2. How many times does the implementation loop through a list?</h4><p>map, filter, and reduce each go through all of the elements in a list.</p><p>So, at least theoretically, the first implementation would go through the list twice because it uses both map and filter, and the second will only go through the list once since it only uses reduce.</p><p>Does this mean the second one has a better performance? It depends on the browser. For example these are the benchmark results when running the implementations in my Safari:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/961/1*61ZYvyXeYuLCXpdralZCmQ.png" /></figure><p>As expected we see the map &amp; filter implementation to be slower than just using reduce. But when I ran the implementations in my Firefox:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/961/1*frsGGolLRlxXgUi2_keQMw.png" /></figure><p>The first implementation<em> </em>is faster! So as you can see, some browsers may perform optimizations on these chained functions. Perhaps overtime more browsers will adopt these optimization and we won’t have to choose between performance and readability.</p><p>But how can we guarantee that our implementation only loops once? (Promise this question will lead us down an interesting abstraction. 😏)</p><p>Well, instead of creating an intermediate list after map, we create a pipeline of transformations we want to do on a single item then iterate through the list once passing each item through the pipeline. So in our example we would go through the list only once first adding 1 as specified in the map to each item and then keeping it if it is greater than 3 as specified in filter.</p><p>Let’s start by implementing this sort of pipeline concept with an even simpler example.</p><h3>Composing Chained Maps</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/958/1*XQ8NrsVaR-uxwaXUzmCHdA.png" /></figure><p>Say we have 2 maps in a row:</p><pre>[1, 2, 3].map(x =&gt; x + 1).map(x =&gt; x * 3)</pre><p>Without any optimization we expect the first map to iterate over the list and return [2, 3, 4]. Then the second map to again iterate and produce [6, 9, 12]. But since we don’t care for the intermediate list, we would be just as happy if we iterate once adding 1 to each value and then multiplying it by 3.</p><p>So in other words we could create a single function that can combine x =&gt; x + 1 and x =&gt; x * 3. The term for combining functions like this where the output of one becomes the input of the next is called <em>composition</em>. So you could rewrite our double map into:</p><pre><strong>const </strong>add1 = x =&gt; x + 1;<br><strong>const</strong> multiply3 = x =&gt; x * 3;</pre><pre>[1, 2, 3].map(compose(multiply3, add1));</pre><p>Here you can easily see that we will be transforming each item in the list by adding 1 and then multiplying 3. <em>Note: Compose is not native to JavaScript, but is available in several </em><a href="https://ramdajs.com/docs/#compose"><em>libraries</em></a><em> and if you want to you can implement it yourself. Also in Ramda’s definition the functions are composed from right to left; hence why </em><em>multiply3 is first.</em></p><p><strong>The lesson here is that any chain of </strong><strong>maps can be turned into a single </strong><strong>map and a composition of all of the functions you want to apply passed as a single argument to that </strong><strong>map. </strong>This could provide some performance improvements and still remain, at least in my opinion, quite readable.</p><p>But what about if we want to chain maps and filters?</p><h3>Composing Chained Maps and Filters?</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/948/1*EFTj976wqgSsA73YpjTJOA.png" /></figure><p>It would be nice if we could just add a filter function into the list of composed functions like so:</p><pre>[1, 2, 3].map(compose(keepGreaterThan7, multiply3, add1))</pre><p>But the problem here is map transforms each item in the list, but with filter we want to remove items from a list. In order to do that in keepGreaterThan7 we would have to transform the item into something that represents nothingness:</p><pre><strong>const</strong> keepGreaterThan7 = x =&gt; x &gt; 7 ? x : undefined</pre><p><em>Here we are treating the value </em><em>undefined as meaning nothing. </em>Then we would have to remove all the nothing values:</p><pre>[1, 2, 3].map(compose(add1, multiply3, keepGreaterThan7))<br>         .filter(x =&gt; x !== undefined);</pre><p>Using this technique we limit the number of iterations through the list to 2 regardless of how long the chain is.</p><p>But what if we wanted to multiply3 after we keepGreaterThan7? Then we would have to make multiply3 aware that undefined means nothing so we shouldn’t operate on it. What if undefined is something meaningful? Then we need to think of another value to represent nothing. What if we want to chain a reduce too? 😖</p><p>As you can see composing the functions passed to map gets clunky quick if you want to do anything other than transform values. This is because filter cannot be derived from map. But they do have a common ancestor…</p><h3>Enter the Trance-ducers…</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/781/1*xwK9RIwOYYqiJipLl2f35g.png" /></figure><p><a href="https://medium.com/@anirudheka/maps-are-folds-in-functional-programming-heres-how-979b90eb657a">map and </a><a href="https://medium.com/@anirudheka/maps-are-folds-in-functional-programming-heres-how-979b90eb657a">filter can be defined with </a><a href="https://medium.com/@anirudheka/maps-are-folds-in-functional-programming-heres-how-979b90eb657a">reduce</a>. Just as we were able to use composition for specific uses of map, perhaps we can use composition for specific uses of reduce like map, filter, and even other things. <em>This is where things get fun! </em>😼</p><p>Let’s start with looking at the definition of map, and filter in terms of reduce:</p><pre>// map : add 1 to each item<br>[1, 2, 3].reduce(<strong>(a, x) =&gt; a.concat(x + 1)</strong>, []);</pre><pre>// filter : keep items greater than 2<br>[1, 2, 3].reduce(<strong>(a, x) =&gt; x &gt; 2 ? a.concat(x)</strong> <strong>: a</strong>, [])</pre><p>As you can see the function passed to reduce (in bold) is the only thing different between the two. We’ll call these functions <em>reducer</em>s. Reducers have the following method signature:</p><pre>(a, x) =&gt; a</pre><p>where a reducer takes as arguments:</p><ol><li>The current result a</li><li>The current item x</li></ol><p>And returns the new a (result).</p><p>OK, let’s extract just the reducers from the two reduce functions:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/dfcc5d3ab3592849c563ae84253c8ee1/href">https://medium.com/media/dfcc5d3ab3592849c563ae84253c8ee1/href</a></iframe><p>Hmm, well, one way we can bring the number of reduce down to one is by making filterGreaterThan2Reducer call mapAdd1Reducer whenever x &gt; 2.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1bb03cb55737d8dcf3df97d61e468a75/href">https://medium.com/media/1bb03cb55737d8dcf3df97d61e468a75/href</a></iframe><p>As you can see we created a chain of reducers where one reducer does it’s job on a and x and then passes them along to the next reducer.</p><p>But one issue is in filterGreaterThan2AndMapAdd1Reducer we are hard wiring filterGreaterThan2 to always be chained to mapAdd1Reducer. Let’s try to make it slightly more customize-able.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/372c12df9ec681043c479cc632938b26/href">https://medium.com/media/372c12df9ec681043c479cc632938b26/href</a></iframe><p>So now filterGreaterThan2Transducer let’s you choose what the next reducer in the chain is by passing it as an argument.</p><p>⏸ Wait, what’s a <em>transducer</em>?</p><p><em>A transducer is a function that returns a reducer when given as an argument the next reducer that the returned reducer should delegate to.* </em>So in our case filterGreaterThan2Transducer(mapAdd1Reducer) returns a reducer that calls mapAdd1Reducer(x, a) only when x &gt; 2.</p><p>Okay cool. But, what if we wanted to filter after we map? We could also turn mapAdd1Reducer into a transducer and pass in the filter as the next argument:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0d9056544e84b1053b579502991f3add/href">https://medium.com/media/0d9056544e84b1053b579502991f3add/href</a></iframe><p>But then what’s filterGreaterThan2Transducer’s next reducer ?! In it’s definition, we can see the next reducer is only invoked when x &gt; 2. In this condition we expect that the item will be added to list a; so let’s pass in a reducer that does that (a, x) =&gt; a.concat(x). <em>Remember the reducer signature is </em><em>(a, x) =&gt; a.</em></p><pre>[1, 2, 3].reduce(<br>    mapAdd1Transducer(<br>       filterGreaterThan2Transducer((a, x) =&gt; a.concat(x))), []);</pre><p>Nice, now we can put the reducers in any order making the last one always the concat!</p><p>Also, if you notice mapAdd1Transducer() takes the reducer returned by filterGreaterThan2Transducer((a, x) =&gt; a.concat(x)) as an input. Whenever you see one function take the output of another function as an input, you can compose them:</p><pre><strong>const</strong> trance = <br>          compose(mapAdd1Transducer, filterGreaterThan2Transducer);</pre><p>This leaves trance expecting the same input as the first function in the composition, filterGreaterThan2Transducer, which would be the next reducer after filtering. Remember the next and last reducer in the chain is (a, x) =&gt; a.concat(x). We can pass this at the call sight like this:</p><pre>[1, 2, 3].reduce(trance((a, x) =&gt; a.concat(x)));</pre><p>We did it! 🎉 We achieved composition across different kinds of reduces! So now we built a nice pipeline of reducers that a single item will travel through, which means we only have to loop once through the list! 👑</p><p>But let’s see if we can go one step further and make something that can create any kind of map and any kind of filter transducers, by extracting out the mapping and filtering logic:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a48795e29e9f69d9a096f6ab918e9b5d/href">https://medium.com/media/a48795e29e9f69d9a096f6ab918e9b5d/href</a></iframe><p>Okay, now mapping and filtering take the logic by which they do their mapping/filtering before producing a transducer. The impact on our composition is:</p><pre><strong>const</strong> trance = compose([filtering(x =&gt; x &gt; 2), mapping(x =&gt; x + 1)]);</pre><pre>[1, 2, 3].reduce(trance((a, x) =&gt; a.concat(x)), []);</pre><p>Nice, right? We, more or less, maintain the declarative style of our chained filter and map, but do all of the reducer logic in one iteration.</p><h3>Keep Trancin’ 🚨</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/951/1*VeW3wcbdLFcIHyrxmAOmqg.png" /></figure><p><strong>The deeper point is NOT that we did it in one iteration. </strong>It’s that we were able to distill the ‘essence’ of the transformation from the input and the output. In other words we were able to separate trance from the actual reduce.</p><p>This could potentially let us use the process described by trance on other inputs besides JS arrays, as long as those structures also offer something like reduce for us. If you want to know where this road leads check out <a href="https://github.com/cognitect-labs/transducers-js">transducer-js</a>. I also hope to expand on this in another post.</p><p><em>I tried to approach transducers the way I discovered them myself in hopes that it would be an approachable read. Let me know if this worked and what could have been better in the comments (or any other thoughts). If you found this post interesting drop of few 👏 Thanks! 🙏</em></p><h4>The One Footnote</h4><p>*My transducer definition is not actually the most general definition, but I think it’s easy to think of it in terms of reduce when you first start learning about it. In the words of Rich Hickey:</p><blockquote>Transducers are a powerful and composable way to build algorithmic transformations that you can reuse in many contexts</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e2f113964b49" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Seeing Javascript objects as functions totally changed the way I see mapping over an object!]]></title>
            <link>https://medium.com/@anirudheka/seeing-javascript-objects-as-functions-totally-changed-the-way-i-see-mapping-over-an-object-d8b834e1d0f9?source=rss-3e6a3c49e24------2</link>
            <guid isPermaLink="false">https://medium.com/p/d8b834e1d0f9</guid>
            <category><![CDATA[functional-programming]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[haskell]]></category>
            <dc:creator><![CDATA[Anirudh Eka]]></dc:creator>
            <pubDate>Tue, 19 Jun 2018 03:57:28 GMT</pubDate>
            <atom:updated>2018-06-19T03:57:28.464Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zKD3xp9dLtmr5m8ofoGMvQ.png" /></figure><p>So you probably know that functions are objects in javascript (if not go up the prototype chain of a function to find out). But recently, I noticed that javascript objects can be treated like functions. Which leads to some pretty cool implications!</p><h4>Functions</h4><p>According to wikipedia:</p><blockquote><a href="https://en.wikipedia.org/wiki/Function_(mathematics)#Definition">A <strong>function</strong> is originally the idealization of how a varying quantity depends on another quantity. For example, the position of a planet is a <em>function</em> of the time.</a></blockquote><p>Given an input (time) you can determine an output (position of the planet). Let’s look at a simple function:</p><pre><strong>const square </strong>= (x) =&gt; x ** 2;</pre><p>Here we have a function that given some inputs will produce some outputs:</p><pre>square(1); //=&gt; 1<br>square(2); //=&gt; 4 <br>square(3); //=&gt; 9</pre><p>This pairing of inputs and outputs are called a function’s domain and co-domain, respectively. We could draw them out like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/923/1*cdtVLUdAbc31k4B182MoEw.png" /></figure><p>That may already look like a key value pair to you, which is what a javascript object is. In fact we could just as well define an object that will have the same behavior.</p><pre><strong>const </strong>square = {1: 1, 2: 4, 3: 9};<br><br>square[1]; //=&gt; 1<br>square[2]; //=&gt; 4<br>square[3]; //=&gt; 9</pre><p>The only visible difference is we replaced the () with [].</p><p>Of course that’s not the only difference. The function implementation can produce the squared value for any number input, while the object implementation will produce undefined for anything except 1, 2, and 3.</p><p>Still, we can see the square object as function, but with a different codomain from the square() function:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CNsiQrdH14iWpaIwaWNz6g.png" /><figcaption>According to wikipedia’s mathematical definition, it is perfectly fine for a function to produce the same output given different input, but the reverse is not true. That is, a function cannot take in the same input and produce different outputs. When we speak of pure function in functional programming this is what we mean.</figcaption></figure><p>Of course nothing here is new or revelational to anyone who stayed awake in grade school math class, but for me programming in the wild is how I discover the genius of simple math truths I was too bored to care about as a kid. We should really re-think how we teach math in schools, but I digress...</p><p>Anyway, if the line between object and function is so blurry, which one should we use?</p><h4>Choosing between an Object and a Function</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pJXAkGuCBDWwC9D7l3UBUg.png" /></figure><p>Functions can be thought of as a succinct way of defining a Dictionary. If it’s possible to establish governing logic to get the right outputs for given inputs, then it’s better to go with a function.</p><p>Imagine maintaining an object with every number as a key and the square of every number as a value. That would be a lot of lines of code! Whereas with a function it would simply be one line: <strong>const square </strong>= (x) =&gt; x ** 2.</p><p>But when should we use an object?</p><ol><li>Well, first obviously if there is no governing formula to get the value from a key, you have no choice, but to go with an object. For example if we have <strong>const person</strong> = {name: &quot;Ada Lovelace&quot;, profession: &#39;Old School Engineer&#39;}, we can’t derive the name, and profession values from the keys with any common logic.</li><li>Performance. If the computation in a function is highly complex the time spent running it might overtake just storing the result of that function in an object. Take fibonacci for example. In <a href="https://jsperf.com/learning-javascript-objects-are-functions-code-sample/1">this comparison</a> we can see running a recursive fibonacci function with the input as 8 is much slower than getting it from a predefined object. (Yes, we could have used a loop, but that’s besides the point…)</li></ol><p>In fact we could get the best of both worlds by building an object within our function that stores the input as the key and output as the value; so that the second time the function is run instead of doing the computation, it can simply get the value from the object.</p><p><em>This technique is called memoization and works with pure functions. </em><a href="https://medium.com/developers-writing/fibonacci-sequence-algorithm-in-javascript-b253dc7e320e"><em>Checkout this article for an example.</em></a></p><p>But we still haven’t gotten to the cool part yet!</p><h4>Map on an Object</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RiPYs4jTaLXhH9VrPbg7wQ.png" /></figure><p>Have you ever wanted to call map on an object; just as you can on an array (e.g. [1, 2].map(n =&gt; n + 1))? How would that map be defined?</p><p>Before we get to that we need to understand what makes something mappable. In native Javascript only lists support it, but in Haskell any data type that is a <em>functor </em>will support the map functionality.</p><p>What is a functor? Often a functor is described as a box that contains a value. For example, [1, 2] contains number values that we can operate on through the map function. In Haskell the type signature would look like this:</p><pre>map :: (a -&gt; b) -&gt; [a] -&gt; [b]</pre><p>For those who aren’t familiar with Haskell type signatures, this roughly says that map will take as arguments:</p><ol><li>(a -&gt; b): a function that takes an input a and produces b</li><li>[a]: a list of a‘s</li></ol><p>and returns [b]: a list of b&#39;s.</p><p>Kinda fits for Javascript, na?</p><p>If we want the Javascript object to be a functor, we have to first decide what value we will be operating on in the structure. Let’s assume the values we want to map over are, well, the values of the object. For example, let’s say we have an object representing Jay Z’s age:</p><pre><strong>const</strong> jayZDetails = { <br>age: 48,<br>demeanorAge: 78 <br>}</pre><p>We wanted to map over with the function stringifyNumber() like so:</p><pre>mapObj(stringifyNumber, jayZDetails) <br>//=&gt; { age: &#39;forty eight&#39;, demeanorAge: &#39;seventy eight&#39; }</pre><p>We could define mapObj like so:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1bc60efe42d1d57256ce569dc5715739/href">https://medium.com/media/1bc60efe42d1d57256ce569dc5715739/href</a></iframe><p>One thing to note here is each time we call our mapObj we loop through the entire list of key-values and produce a new object. So if we did 2 mapObj&#39;s:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0679328ecceb8f76281d5ad589c9ba5c/href">https://medium.com/media/0679328ecceb8f76281d5ad589c9ba5c/href</a></iframe><p>We would loop twice through all the keys producing two objects: first, { age: ‘forty eight’, demeanorAge: ‘seventy eight’ }; and then { age: ‘forty eight years old’, demeanorAge: ‘seventy eight years old’ }.</p><p>We do all this work just so we can get one value from the object, result[‘demeanorAge’]. Is there a better way to do this? Well if objects are functions, maybe we could call map on a function instead?</p><h4>Map on a Function</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pNM-p_9W5RRKXhJfec5W4A.png" /></figure><p>To understand how we could map over a function it’s useful to look at the generalized definition of map in Haskell:</p><pre>fmap :: Functor f =&gt; (a -&gt; b) -&gt; f a -&gt; f b</pre><p><em>The ‘f’ in fmap stands for functor.</em></p><p>This is saying map will take as arguments:</p><ol><li>(a -&gt; b): a function that takes an input a and produces b</li><li>f a: a functor containing a.</li></ol><p>and return f b: the same kind of functor containing the new values. When you call map on an array, you’ll get back an array. When you call map on an object, you’ll get back an object.</p><p>Just as we did with objects, we need to decide what is the value a function ‘contains’. Well, if we look at a function as (input -&gt; output) we could think of the output as the value the function contains. A little weird (or mind blowing), but let’s go with it.</p><p>Ok, so if we replace f in the type signature above with a function that we’ll represent as (x -&gt; a), it would look something like this:</p><pre>fmap :: Functor f =&gt; (a -&gt; b) -&gt; (x -&gt; a) -&gt; (x -&gt; b)</pre><p>Huh?! Let’s break it down. The arguments are:</p><ol><li>(a -&gt; b): a function that takes an input a and produces b</li><li>(x -&gt; a): a functor that happens to be a function, which contains a.</li></ol><p>And what does it return? Well we said when you call map on a functor you produce the same type of functor with new values. map on an array you get an array. So if you call map on a function, you get…a function! And not just any function, but one with the same containing context, which in this case is (x -&gt;, a function that takes in the same input as the initial functor to make (x -&gt; b).</p><p>So if we had map for functions it could work like this:</p><pre><strong>const</strong> add2 = x =&gt; x + 2;<br><strong>const</strong> myFunctor = x =&gt; x - 2;</pre><pre><strong>const</strong> inTheEndItDoesentEvenMatter = mapFn(add2, myFunctor);<br>inTheEndItDoesentEvenMatter(5) //=&gt; 5</pre><p>This took me a while to grasp; so definitely read it again. (Also let me know in the comments if something is unclear.)</p><p>Okay, so here’s a way we could define mapFn:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fa95eb2f6da8cb5efa61b3abfa0fb37b/href">https://medium.com/media/fa95eb2f6da8cb5efa61b3abfa0fb37b/href</a></iframe><p>Let’s compare this to mapObj in our Jay Z example. Here is the mapObj implementation again:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0679328ecceb8f76281d5ad589c9ba5c/href">https://medium.com/media/0679328ecceb8f76281d5ad589c9ba5c/href</a></iframe><p>And here’s mapFn :</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ef589cc14ab9a3bbf110419545a172b4/href">https://medium.com/media/ef589cc14ab9a3bbf110419545a172b4/href</a></iframe><p>Looks fairly similar, the only thing we had to do is wrap our object in a function: <strong>const</strong> jayZDetailsFn = (k) =&gt; jayZDetails[k], but are there any benefits?</p><p>Well, the issue with our mapObj approach is even before we used result we had to iterate twice over the list and build two new objects. Even though we finally only needed one value result[‘demeanorAge’] we applied stringifyNumber and addAgeSuffix on all of the values. That’s a lot of extra effort.</p><p>In contrast, all mapFn does is returns a function that basically glues together the functions it’s given. When result is made no list of keys are looped over, and no objects are created. In fact, even when result(‘demeanorAge’)is called there is no looping or object creation!</p><p>It just passes ‘demeanorAge’ as an input into a pipeline of functions which begins with querying the initial object for just the value we are interested in. Then each function performs a subsequent transformation on the value of jayZDetails[&#39;demeanorAge&#39;].</p><p>If you know a little bit about functional programming, you might have realized this is function composition. So yes, to map on a function is to compose a function. Which means if you wrap an object in a function you can use it in function composition or any other fun function tricks, you know.</p><p><em>As of writing libraries like </em><a href="https://ramdajs.com/docs/#compose"><em>ramda</em></a><em> offer compose if you want to try it out!</em></p><h4>Take Away</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6PA9JqLXyJTkiCl98XrAiQ.png" /><figcaption>Just in case you are using these images as coding example, they probably won’t work. Mostly because my brain drawing is not native to javascript. Also the compose available in libraries do not usually add compose to the function prototype. The above would look more like compose(k =&gt; {mind: ‘blown’}[k], yourself).</figcaption></figure><p>The next time you see a javascript object remember, it can be seen as two things:</p><ol><li>A function</li><li>An array of inputs that can be retrieved from Object.keys()</li></ol><p>Ask yourself, how am I using this object? Can I treat it as a function?</p><p>In practice, treating an object as a function is simply wrapping it like so</p><pre><strong>const</strong> myFunction = (k) =&gt; myObject[k];</pre><p>Then just explore!</p><p><em>If you find any other cool implications leave a comment! If you find any flaw with anything in this post leave a comment! If you found this post interesting drop of few 👏 Thanks! 🙏</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d8b834e1d0f9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to extract logic from one Redux reducer to another using appendReducer]]></title>
            <link>https://medium.com/@anirudheka/how-to-extract-logic-from-one-redux-reducer-to-another-using-appendreducer-a9aca6ae7541?source=rss-3e6a3c49e24------2</link>
            <guid isPermaLink="false">https://medium.com/p/a9aca6ae7541</guid>
            <category><![CDATA[functional-programming]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[twbloggersclub]]></category>
            <category><![CDATA[redux]]></category>
            <dc:creator><![CDATA[Anirudh Eka]]></dc:creator>
            <pubDate>Wed, 02 May 2018 08:28:04 GMT</pubDate>
            <atom:updated>2018-05-03T13:19:19.416Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1WxFNunRsDDKrcAJ_8FxfA.jpeg" /></figure><p>If the history of our planet was scaled to 24 hours, the entire existence of our species would be less than 2 minutes, and the existence of Redux would probably be a fraction of a millisecond.</p><p>And yet…it’s still old enough to have legacy code written in it.</p><p>Have you ever faced a giant reducer that you wanted to break into smaller chunks?</p><p>Ideally you would use <a href="https://redux.js.org/api-reference/combinereducers">combineReducer</a>s to build your reducer from other reducers that handle the subtrees of the state. For example if you had a reducer called the historyOfEarthReducer and it operated on a state like the following:</p><pre>{<br>  jurassicEra: //...<br>  riseOfTheMongols: //...  <br>  afterAbramov: //...<br>}</pre><p>You could could compose historyOfEarthReducer with reducers responsible for each subtree of history:</p><pre><strong>let </strong>reducers = {<br>  jurassicEra: jurassicEraReducer,<br>  riseOfTheMongols: riseOfTheMongolsReducer,<br>  afterAbramov: afterAbramovReducer<br>};<br><br><strong>const </strong>reducer = combineReducers(reducers);</pre><p>But what if you or your ancestors didn’t think about making composable code way back when you started writing this reducer (after all who had the brain cells to think of that when we were algae)? So you had one big monolith historyOfEarthReducer. But then you discovered fire, the wheel, and decided it’s time break things up.</p><p>But unfortunately most of the logic of your reducer is incredibly messy and interdependent. What if the only part of the reducer logic that is relatively painless to extract is afterAbramov?</p><p>The limitation with combineReducer is it can only work if you have a reducer for each sibling of the tree. But you prefer the main reducer to continue to handle the reducing logic for jurassicEra, riseOfTheMongols, and whatever else; while you build out afterAbramovReducer.</p><pre>{<br>  jurassicEra: //...handled by historyOfEarthReducer<br>  riseOfTheMongols: //...handled by historyOfEarthReducer<br>  afterAbramov: //...handled by afterAbramovReducer<br>}</pre><h3>AppendReducer</h3><p>What you really want is not to combine smaller reducers to make a big one, but to <em>append</em> a small one to an already big one. Recently I faced such a situation in a codebase I was looking at.</p><p>In order to solve this problem I created something called appendReducer that’s used like this:</p><pre><strong>let</strong> reducersToAppend = {<br>  afterAbramov: afterAbramovReducer<br>}</pre><pre><strong>const</strong> appendReducer(historyOfEarthReducer, reducersToAppend);</pre><p>appendReducer takes as its first argument the core/main reducer that is responsible for most of the keys in the tree, historyOfEarthReducer in this case.</p><p>Its second argument (similar to combineReducers) is an object mapping keys to reducer functions. The key should refer to the subtree that the main reducer wants to delegate and the value should be the reducer it wants to delegate to. So here it would be delegating management of all state under the afterAbramov key to afterAbramovReducer.</p><p>This is how I implemented appendReducer:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ea2bc01b851ad95f63776a3a702ea91b/href">https://medium.com/media/ea2bc01b851ad95f63776a3a702ea91b/href</a></iframe><h4>In the wild</h4><p>In our project we used appendReducer along with <a href="https://redux.js.org/recipes/structuring-reducers/reusing-reducer-logic#customizing-behavior-with-higher-order-reducers">common generic reducers</a> to incrementally reduce duplication in our code.</p><h4>How did you solve this problem?</h4><p>I’m pretty new to Redux and am always looking for ways to improve. Definitely leave a comment if you found other/better ways to solve this! Also if there’s a better way to implement appendReducer, let me know!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a9aca6ae7541" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>