<?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" xmlns:media="http://search.yahoo.com/mrss/" version="2.0">
    <channel>
        
        <title>
            <![CDATA[ composition - freeCodeCamp.org ]]>
        </title>
        <description>
            <![CDATA[ Browse thousands of programming tutorials written by experts. Learn Web Development, Data Science, DevOps, Security, and get developer career advice. ]]>
        </description>
        <link>https://www.freecodecamp.org/news/</link>
        <image>
            <url>https://cdn.freecodecamp.org/universal/favicons/favicon.png</url>
            <title>
                <![CDATA[ composition - freeCodeCamp.org ]]>
            </title>
            <link>https://www.freecodecamp.org/news/</link>
        </image>
        <generator>Eleventy</generator>
        <lastBuildDate>Thu, 14 May 2026 22:44:34 +0000</lastBuildDate>
        <atom:link href="https://www.freecodecamp.org/news/tag/composition/rss.xml" rel="self" type="application/rss+xml" />
        <ttl>60</ttl>
        
            <item>
                <title>
                    <![CDATA[ How to Use Currying and Composition in JavaScript ]]>
                </title>
                <description>
                    <![CDATA[ By Tobias Parent A great conversation I had this evening got me thinking about and revisiting a concept I've toyed with before – currying. But this time, I'd like to explore it with you all! The concept of currying is not a new one, but it is very us... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/how-to-use-currying-and-composition-in-javascript/</link>
                <guid isPermaLink="false">66d4614b3a8352b6c5a2ab19</guid>
                
                    <category>
                        <![CDATA[ composition ]]>
                    </category>
                
                    <category>
                        <![CDATA[ currying ]]>
                    </category>
                
                    <category>
                        <![CDATA[ JavaScript ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ freeCodeCamp ]]>
                </dc:creator>
                <pubDate>Mon, 18 Oct 2021 22:06:59 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2021/10/lydia-tallent-SkY-jiMGYfA-unsplash.jpg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>By Tobias Parent</p>
<p>A great conversation I had this evening got me thinking about and revisiting a concept I've toyed with before – currying. But this time, I'd like to explore it with you all!</p>
<p>The concept of currying is not a new one, but it is very useful. It is also foundational for functional programming, and is sort of a gateway to thinking about functions in a more modular way. </p>
<p>And the idea of composition, of combining functions to create larger, more complex, more useful ones may seem pretty intuitive, but is also a key component in functional programming. </p>
<p>When we start combining them, then some fun things can happen. Let's see how this might work.</p>
<h2 id="heading-curry-anyone">Curry, anyone?</h2>
<p>Curried functions are doing much the same as any other function, but the way you approach them is a bit different. </p>
<p>Suppose we wanted a function that could check the distance between two points: <code>{x1, y1}</code> and <code>{x2, y2}</code>, for example. The formula for that is a little mathy, but nothing we can't handle:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2021/10/distance-formula.svg" alt="Image" width="600" height="400" loading="lazy">
<em>The formula for distance between two points, which is an application of the Pythagorean theorem.</em></p>
<p>Ordinarily, calling our function might look something like:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> distance = <span class="hljs-function">(<span class="hljs-params">start, end</span>) =&gt;</span> <span class="hljs-built_in">Math</span>.sqrt( <span class="hljs-built_in">Math</span>.pow(end.x-start.x, <span class="hljs-number">2</span>) + <span class="hljs-built_in">Math</span>.pow(end.y-start.y, <span class="hljs-number">2</span>) );

<span class="hljs-built_in">console</span>.log( distance( {<span class="hljs-attr">x</span>:<span class="hljs-number">2</span>, <span class="hljs-attr">y</span>:<span class="hljs-number">2</span>}, {<span class="hljs-attr">x</span>:<span class="hljs-number">11</span>, <span class="hljs-attr">y</span>:<span class="hljs-number">8</span>} );
<span class="hljs-comment">// logs 10.816653826391969</span>
</code></pre>
<p>Now, currying a function is forcing it to take a single parameter at a time. So rather than calling it like <code>distance( start, end )</code>, we would call it like this: <code>distance(start)(end)</code>. Each parameter is passed in individually, and each function call returns another function, until all parameters have been provided.</p>
<p>It might be easier to show than to explain, so let's look at the above distance function as a curried one:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> distance = <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">start</span>)</span>{
  <span class="hljs-comment">// we have a closed scope here, but we'll return a function that</span>
  <span class="hljs-comment">//  can access it - effectively creating a "closure".</span>
  <span class="hljs-keyword">return</span> <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">end</span>)</span>{
    <span class="hljs-comment">// now, in this function, we have everything we need. we can do</span>
    <span class="hljs-comment">//  the calculation and return the result.</span>
    <span class="hljs-keyword">return</span> <span class="hljs-built_in">Math</span>.sqrt( <span class="hljs-built_in">Math</span>.pow(end.x-start.x, <span class="hljs-number">2</span>) + <span class="hljs-built_in">Math</span>.pow(end.y-start.y, <span class="hljs-number">2</span>) );
  }
}

<span class="hljs-built_in">console</span>.log( distance({<span class="hljs-attr">x</span>:<span class="hljs-number">2</span>, <span class="hljs-attr">y</span>:<span class="hljs-number">2</span>})({<span class="hljs-attr">x</span>:<span class="hljs-number">11</span>, <span class="hljs-attr">y</span>:<span class="hljs-number">8</span>});
<span class="hljs-comment">// logs 10.816653826391969 again</span>
</code></pre>
<p>That seems like an awful lot of work to get the same result! We <em>can</em> shorten it some, by using ES6 arrow functions:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> distancewithCurrying = 
        <span class="hljs-function">(<span class="hljs-params">start</span>) =&gt;</span> 
          <span class="hljs-function">(<span class="hljs-params">end</span>) =&gt;</span> <span class="hljs-built_in">Math</span>.sqrt( <span class="hljs-built_in">Math</span>.pow(end.x-start.x, <span class="hljs-number">2</span>) +
                              <span class="hljs-built_in">Math</span>.pow(end.y-start.y, <span class="hljs-number">2</span>) );
</code></pre>
<p>But again, it seems a lot of hoopla for no real gain, unless we start thinking about our functions in a more abstract way. </p>
<p>Remember, functions can only return one thing. While we might provide any number of parameters, we will only get back a single value, whether it's a number, array, object, or function. We only get one thing back. And now, with a curried function, we have a function that can receive only one thing. There may be a connection there.</p>
<p>As it happens, the power of curried functions comes in being able to combine and <em>compose</em> them. </p>
<p>Consider our distance formula – what if we were writing a "capture the flag" game, and it might be useful to quickly and easily calculate each player's distance from the flag. We might have an array of players, each of which contains an <code>{x, y}</code> location. With an array of <code>{x,y}</code> values, a re-usable function could come in pretty handy. Let's play with that idea for a minute:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> players = [
  {
    <span class="hljs-attr">name</span>: <span class="hljs-string">'Alice'</span>,
    <span class="hljs-attr">color</span>: <span class="hljs-string">'aliceblue'</span>,
    <span class="hljs-attr">position</span>: { <span class="hljs-attr">x</span>: <span class="hljs-number">3</span>, <span class="hljs-attr">y</span>: <span class="hljs-number">5</span>}
  },{
    <span class="hljs-attr">name</span>: <span class="hljs-string">'Benji'</span>,
    <span class="hljs-attr">color</span>: <span class="hljs-string">'goldenrod'</span>,
    <span class="hljs-attr">position</span>: { <span class="hljs-attr">x</span>: <span class="hljs-number">-4</span>, <span class="hljs-attr">y</span>: <span class="hljs-number">-4</span>}
  },{
    <span class="hljs-attr">name</span>: <span class="hljs-string">'Clarissa'</span>,
    <span class="hljs-attr">color</span>: <span class="hljs-string">'firebrick'</span>,
    <span class="hljs-attr">position</span>: { <span class="hljs-attr">x</span>: <span class="hljs-number">-2</span>, <span class="hljs-attr">y</span>: <span class="hljs-number">8</span>}
  }
];
<span class="hljs-keyword">const</span> flag = { <span class="hljs-attr">x</span>:<span class="hljs-number">0</span>, <span class="hljs-attr">y</span>:<span class="hljs-number">0</span>};
</code></pre>
<p>There's our setup: we have a starting location, <code>flag</code>, and we have an array of players. We have two different functions defined to calculate the difference, let's see the difference:</p>
<pre><code class="lang-js"><span class="hljs-comment">// Given those, let's see if we can find a way to map </span>
<span class="hljs-comment">//  out those distances! Let's do it first with the first</span>
<span class="hljs-comment">//  distance formula.</span>
<span class="hljs-keyword">const</span> distances = players.map( <span class="hljs-function"><span class="hljs-params">player</span> =&gt;</span> distance(flag, player.position) );
<span class="hljs-comment">/***
 * distances == [
 *   5.830951894845301, 
 *   5.656854249492381, 
 *   8.246211251235321
 * ]
 ***/</span>

<span class="hljs-comment">// using a curried function, we can create a function that already</span>
<span class="hljs-comment">//  contains our starting point.</span>
<span class="hljs-keyword">const</span> distanceFromFlag = distanceWithCurrying(flag);
<span class="hljs-comment">// Now, we can map over our players to extract their position, and</span>
<span class="hljs-comment">//  map again with that distance formula:</span>
<span class="hljs-keyword">const</span> curriedDistances = players.map(<span class="hljs-function"><span class="hljs-params">player</span>=&gt;</span>player.position)
                                .map(distanceFromFlag)
<span class="hljs-comment">/***
 * curriedDistances == [
 *   5.830951894845301, 
 *   5.656854249492381, 
 *   8.246211251235321
 * ]
 ***/</span>
</code></pre>
<p>So here, we have used our <code>distanceCurried</code> function to apply one parameter, the starting point. That returned a function which takes another parameter, the ending point. By mapping over the players, we can create a new array with <em>just</em> the data we need, and then pass that data into our curried function!</p>
<p>It's a powerful tool, and one that might take some getting used to. But by creating curried functions and composing them with other functions, we can create some very complex functions from smaller, simpler parts.</p>
<h2 id="heading-how-to-compose-curried-functions">How to Compose Curried Functions</h2>
<p>Being able to map curried functions is very useful, but you'll also find other great uses for them. This is the beginning of "Functional Programming": writing small, pure functions that perform properly as these atomic bits and then combining them like building blocks.</p>
<p>Let's look at how we might take curried functions, and compose them into larger ones. This next exploration will get into filter functions.</p>
<p>First, a little groundwork. <code>Array.prototype.filter()</code>, the ES6 filtering function, allows us to define a callback function, one that takes an input value or values and return a true or false based on that. Here's an example:</p>
<pre><code class="lang-js"><span class="hljs-comment">// a source array,</span>
<span class="hljs-keyword">const</span> ages = [<span class="hljs-number">11</span>, <span class="hljs-number">14</span>, <span class="hljs-number">26</span>, <span class="hljs-number">9</span>, <span class="hljs-number">41</span>, <span class="hljs-number">24</span>, <span class="hljs-number">108</span>];
<span class="hljs-comment">// a filter function. Takes an input, and returns true/false from it.</span>
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">isEven</span>(<span class="hljs-params">num</span>)</span>{
  <span class="hljs-keyword">if</span>(num%<span class="hljs-number">2</span>===<span class="hljs-number">0</span>){
    <span class="hljs-keyword">return</span> <span class="hljs-literal">true</span>;
  } <span class="hljs-keyword">else</span> {
    <span class="hljs-keyword">return</span> <span class="hljs-literal">false</span>;
  }
}
<span class="hljs-comment">// or, in ES6-style:</span>
<span class="hljs-keyword">const</span> isEven = <span class="hljs-function">(<span class="hljs-params">num</span>) =&gt;</span> num%<span class="hljs-number">2</span>===<span class="hljs-number">0</span> ? <span class="hljs-literal">true</span> : <span class="hljs-literal">false</span>;
<span class="hljs-comment">// and applied:</span>
<span class="hljs-built_in">console</span>.log( ages.filter(isEven) );
<span class="hljs-comment">// [14, 26, 24, 108]</span>
</code></pre>
<p>Now that filter function, <code>isEven</code>, is written in a very specific way: it takes a value (or values, if we want to include the array's index for example), performs some sort of internal hoojinkery, and returns a true or false. Every time. </p>
<p>This is the essence of a "filter callback function," though it isn't exclusive to filters – the <code>Array.prototype.every</code> and <code>Array.prototype.some</code> use the same style. A callback is tested against each member of an array, and the callback takes in some value and returns true or false.</p>
<p>Let's create a few more useful filter functions, but this time a little more advanced. In this case, we might want to "abstract" our functions a bit, letting us make them more re-usable. </p>
<p>For example, some useful functions might be <code>isEqualTo</code> or <code>isGreaterThan</code>. These are more advanced in that they require <em>two</em> values: one to define as one term of a comparison (call it a <code>comparator</code>), and one coming in from the array <em>being</em> compared (we'll call it the <code>value</code>). Here's a bit more code:</p>
<pre><code class="lang-js"><span class="hljs-comment">// we write a function that takes in a value...</span>
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">isEqualTo</span>(<span class="hljs-params">comparator</span>)</span>{
  <span class="hljs-comment">// and that function *returns* a function that takes a second value</span>
  <span class="hljs-keyword">return</span> <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">value</span>)</span>{
    <span class="hljs-comment">// and we simply compare those two values.</span>
    <span class="hljs-keyword">return</span> value === comparator;
  }
}
<span class="hljs-comment">// again, in ES6:</span>
<span class="hljs-keyword">const</span> isEqualTo = <span class="hljs-function">(<span class="hljs-params">comparator</span>) =&gt;</span> <span class="hljs-function">(<span class="hljs-params">value</span>) =&gt;</span> value === comparator;
</code></pre>
<p>From this point, I'm going to stick with the ES6 version, unless there is a particularly challenging reason to expand the code out to the classic version. Moving on:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> isEqualTo = <span class="hljs-function">(<span class="hljs-params">comparator</span>) =&gt;</span> <span class="hljs-function">(<span class="hljs-params">value</span>) =&gt;</span> value === comparator;
<span class="hljs-keyword">const</span> isGreaterThan = <span class="hljs-function">(<span class="hljs-params">comparator</span>) =&gt;</span> <span class="hljs-function">(<span class="hljs-params">value</span>) =&gt;</span> value &gt; comparator;

<span class="hljs-comment">// and in application:</span>
<span class="hljs-keyword">const</span> isSeven = isEqualTo(<span class="hljs-number">7</span>);
<span class="hljs-keyword">const</span> isOfLegalMajority = isGreaterThan(<span class="hljs-number">18</span>);
</code></pre>
<p>So there, the first two functions are our curried functions. They expect a single parameter, and return a function that in turn also expects a single parameter.</p>
<p>Based on those two single parameter functions, we do a simple comparison. The second two, <code>isSeven</code> and <code>isOfLegalMajority</code>, are simply implementations of those two functions.</p>
<p>Thus far, we haven't gotten to complex or involved, and we can stay small for a few more:</p>
<pre><code><span class="hljs-comment">// function to simply invert a value: true &lt;=&gt; false</span>
<span class="hljs-keyword">const</span> isNot = <span class="hljs-function">(<span class="hljs-params">value</span>) =&gt;</span> !value;

<span class="hljs-keyword">const</span> isNotEqual = <span class="hljs-function">(<span class="hljs-params">comparator</span>) =&gt;</span> <span class="hljs-function">(<span class="hljs-params">value</span>) =&gt;</span> isNot( isEqual(comparator)(value) );
<span class="hljs-keyword">const</span> isLessThanOrEqualTo = <span class="hljs-function">(<span class="hljs-params">comparator</span>) =&gt;</span> <span class="hljs-function">(<span class="hljs-params">value</span>) =&gt;</span> isNot( isGreaterThan(comparator)(value) );
</code></pre><p>Here, we have a utility function that simply inverts the <em>truthiness</em> of a value, <code>isNot</code>. Using that, we can begin composing larger pieces: we take our comparator and value, run them through the <code>isEqual</code> function, and then we <code>isNot</code> that value to say <code>isNotEqual</code>.</p>
<p>This is the beginning of composition, and let's be fair – it looks absolutely silly. What possible use would there be to write all that to get this:</p>
<pre><code class="lang-js"><span class="hljs-comment">// all of the building blocks...</span>
<span class="hljs-keyword">const</span> isGreaterThan = <span class="hljs-function">(<span class="hljs-params">comparator</span>) =&gt;</span> <span class="hljs-function">(<span class="hljs-params">value</span>) =&gt;</span> value &gt; comparator;
<span class="hljs-keyword">const</span> isNot = <span class="hljs-function">(<span class="hljs-params">value</span>) =&gt;</span> !value;
<span class="hljs-keyword">const</span> isLessThanOrEqualTo = <span class="hljs-function">(<span class="hljs-params">comparator</span>) =&gt;</span> <span class="hljs-function">(<span class="hljs-params">value</span>) =&gt;</span> isNot( isGreaterThan(comparator)(value) );

<span class="hljs-comment">// simply to get this?</span>
<span class="hljs-keyword">const</span> isTooYoungToRetire = isLessThanOrEqualTo(<span class="hljs-number">65</span>)

<span class="hljs-comment">// and in implementation:</span>
<span class="hljs-keyword">const</span> ages = [<span class="hljs-number">31</span>, <span class="hljs-number">24</span>, <span class="hljs-number">86</span>, <span class="hljs-number">57</span>, <span class="hljs-number">67</span>, <span class="hljs-number">19</span>, <span class="hljs-number">93</span>, <span class="hljs-number">75</span>, <span class="hljs-number">63</span>];
<span class="hljs-built_in">console</span>.log(ages.filter(isTooYoungToRetire)

<span class="hljs-comment">// is that any cleaner than:</span>
<span class="hljs-built_in">console</span>.log(ages.filter( <span class="hljs-function"><span class="hljs-params">num</span> =&gt;</span> num &lt;= <span class="hljs-number">65</span> ) )
</code></pre>
<p>"The final result is pretty similar in this case, so it doesn't really save us anything. In fact, given the setup in those first three functions, it took a <strong>lot</strong> more to build than simply doing a comparison!"</p>
<p>And that is true. I won't argue that. But it is only seeing a small piece of a much larger puzzle. </p>
<ul>
<li>First, we are writing code that is much more <em>self-documenting</em>. By using expressive function names, we are able to see at a glance that we are filtering <code>ages</code> for values <code>isTooYoungToRetire</code>. We aren't seeing the math, we are seeing the description.</li>
<li>Second, by using very small atomic functions, we are able to test each piece in isolation, making sure that it performs exactly the same every time. Later on, when we reuse those small functions, we can be confident that they will work –freeing us up from testing each little piece as our function's complexity grows.</li>
<li>Third, by creating abstract functions, we might find applications for them in other projects later. Building a library of functional components is a very powerful asset, and one I strongly recommend cultivating.  </li>
</ul>
<p>With all that said, we can also take those smaller functions and begin combining them into larger and larger pieces. Let's try that now: having both an <code>isGreaterThan</code> and <code>isLessThan</code>, we can write a nice <code>isInRange</code> function!</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> isInRange = <span class="hljs-function">(<span class="hljs-params">minComparator</span>) 
                 =&gt;</span> <span class="hljs-function">(<span class="hljs-params">maxComparator</span>)
                   =&gt;</span> <span class="hljs-function">(<span class="hljs-params">value</span>) =&gt;</span> isGreaterThan(minComparator)(value)
                              &amp;&amp; isLessThan(maxComparator)(value)

<span class="hljs-keyword">const</span> isTwentySomething = isInRange(<span class="hljs-number">19</span>)(<span class="hljs-number">30</span>);
</code></pre>
<p>That is great – we now have a means to test for multiple conditions at a single go. But looking at that, it doesn't seem very self-documenting. The <code>&amp;&amp;</code> in the middle there isn't terrible, but we can do better. </p>
<p>Perhaps if we were to write <em>another</em> function, one we can call <code>and()</code>. The <code>and</code> function can take any number of conditions, and test them against a given value. That would be useful, and extensible.</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> and = (conditions) = 
             <span class="hljs-function">(<span class="hljs-params">value</span>) =&gt;</span> conditions.every(<span class="hljs-function"><span class="hljs-params">condition</span> =&gt;</span> condition(value) )

<span class="hljs-keyword">const</span> isInRange = <span class="hljs-function">(<span class="hljs-params">min</span>)
                 =&gt;</span><span class="hljs-function">(<span class="hljs-params">max</span>) 
                  =&gt;</span> and([isGreaterThan(min), isLessThan(max) ])
</code></pre>
<p>So the <code>and</code> function takes any number of filter functions, and only returns true if they are all true against a given value. That <code>isInRange</code> function in the last does the exact same thing as the prior one, but it seems much more readable, and self-documenting. </p>
<p>Further, it will allow us to combine any number of functions: suppose we wanted to get even numbers between 20 and 40, we would simply combine our <code>isEven</code> function from WAY up top with our <code>isInRange</code> one using an <code>and</code>, and it simply works.</p>
<h2 id="heading-recap">Recap</h2>
<p>By using curried functions, we are able to compose functions together cleanly. We can wire the output of one function directly into the input of the next, as both now take a single parameter. </p>
<p>By using composition, we can combine smaller functions or curried functions into much larger and more complicated structures, with the confidence that the smallest parts are working as expected.</p>
<p>This is a lot to digest, and it's a deep concept. But if you take the time and explore this more, I think you'll start seeing applications we haven't even touched on, and you might write the next article like this instead of me!</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ A quick introduction to pipe() and compose() in JavaScript ]]>
                </title>
                <description>
                    <![CDATA[ By Yazeed Bzadough Functional programming’s been quite the eye-opening journey for me. This post, and posts like it, are an attempt to share my insights and perspectives as I trek new functional programming lands. Ramda’s been my go-to FP library bec... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/pipe-and-compose-in-javascript-5b04004ac937/</link>
                <guid isPermaLink="false">66d461af787a2a3b05af441f</guid>
                
                    <category>
                        <![CDATA[ composition ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Functional Programming ]]>
                    </category>
                
                    <category>
                        <![CDATA[ JavaScript ]]>
                    </category>
                
                    <category>
                        <![CDATA[ General Programming ]]>
                    </category>
                
                    <category>
                        <![CDATA[ technology ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ freeCodeCamp ]]>
                </dc:creator>
                <pubDate>Wed, 10 Jan 2018 02:30:12 +0000</pubDate>
                <media:content url="https://cdn-media-1.freecodecamp.org/images/1*FKEc-DbmFn54VPLQmCOLRA.jpeg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>By Yazeed Bzadough</p>
<p>Functional programming’s been quite the eye-opening journey for me. This post, and posts like it, are an attempt to share my insights and perspectives as I trek new functional programming lands.</p>
<p><a target="_blank" href="http://ramdajs.com/">Ramda’s</a> been my go-to FP library because of how much easier it makes functional programming in JavaScript. I highly recommend it.</p>
<h3 id="heading-pipe">Pipe</h3>
<p>The concept of <code>pipe</code> is simple — it combines <code>n</code> functions. It’s a pipe flowing left-to-right, calling each function with the output of the last one.</p>
<p>Let’s write a function that returns someone’s <code>name</code>.</p>
<pre><code class="lang-js">getName = <span class="hljs-function">(<span class="hljs-params">person</span>) =&gt;</span> person.name;

getName({ <span class="hljs-attr">name</span>: <span class="hljs-string">'Buckethead'</span> });
<span class="hljs-comment">// 'Buckethead'</span>
</code></pre>
<p>Let’s write a function that uppercases strings.</p>
<pre><code class="lang-js">uppercase = <span class="hljs-function">(<span class="hljs-params">string</span>) =&gt;</span> string.toUpperCase();

uppercase(<span class="hljs-string">'Buckethead'</span>);
<span class="hljs-comment">// 'BUCKETHEAD'</span>
</code></pre>
<p>So if we wanted to get and capitalize <code>person</code>'s name, we could do this:</p>
<pre><code class="lang-js">name = getName({ <span class="hljs-attr">name</span>: <span class="hljs-string">'Buckethead'</span> });
uppercase(name);

<span class="hljs-comment">// 'BUCKETHEAD'</span>
</code></pre>
<p>That’s fine but let’s eliminate that intermediate variable <code>name</code>.</p>
<pre><code class="lang-js">uppercase(getName({ <span class="hljs-attr">name</span>: <span class="hljs-string">'Buckethead'</span> }));
</code></pre>
<p>Better, but I’m not fond of that nesting. It can get too crowded. What if we want to add a function that gets the first 6 characters of a string?</p>
<pre><code class="lang-js">get6Characters = <span class="hljs-function">(<span class="hljs-params">string</span>) =&gt;</span> string.substring(<span class="hljs-number">0</span>, <span class="hljs-number">6</span>);

get6Characters(<span class="hljs-string">'Buckethead'</span>);
<span class="hljs-comment">// 'Bucket'</span>
</code></pre>
<p>Resulting in:</p>
<pre><code class="lang-js">get6Characters(uppercase(getName({ <span class="hljs-attr">name</span>: <span class="hljs-string">'Buckethead'</span> })));

<span class="hljs-comment">// 'BUCKET';</span>
</code></pre>
<p>Let’s get really crazy and add a function to reverse strings.</p>
<pre><code class="lang-js">reverse = <span class="hljs-function">(<span class="hljs-params">string</span>) =&gt;</span>
  string
    .split(<span class="hljs-string">''</span>)
    .reverse()
    .join(<span class="hljs-string">''</span>);

reverse(<span class="hljs-string">'Buckethead'</span>);
<span class="hljs-comment">// 'daehtekcuB'</span>
</code></pre>
<p>Now we have:</p>
<pre><code class="lang-js">reverse(get6Characters(uppercase(getName({ <span class="hljs-attr">name</span>: <span class="hljs-string">'Buckethead'</span> }))));
<span class="hljs-comment">// 'TEKCUB'</span>
</code></pre>
<p>It can get a bit…much.</p>
<h3 id="heading-pipe-to-the-rescue">Pipe to the rescue!</h3>
<p>Instead of jamming functions within functions or creating a bunch of intermediate variables, let’s <code>pipe</code> all the things!</p>
<pre><code class="lang-js">pipe(
  getName,
  uppercase,
  get6Characters,
  reverse
)({ <span class="hljs-attr">name</span>: <span class="hljs-string">'Buckethead'</span> });
<span class="hljs-comment">// 'TEKCUB'</span>
</code></pre>
<p>Pure art. It’s like a todo list!</p>
<p>Let’s step through it.</p>
<p>For demo purposes, I’ll use a <code>pipe</code> implementation from one of <a target="_blank" href="https://medium.com/@_ericelliott">Eric Elliott</a>’s <a target="_blank" href="https://medium.com/javascript-scene/reduce-composing-software-fe22f0c39a1d">functional programming articles</a>.</p>
<pre><code class="lang-js">pipe = <span class="hljs-function">(<span class="hljs-params">...fns</span>) =&gt;</span> <span class="hljs-function">(<span class="hljs-params">x</span>) =&gt;</span> fns.reduce(<span class="hljs-function">(<span class="hljs-params">v, f</span>) =&gt;</span> f(v), x);
</code></pre>
<p>I love this little one-liner.</p>
<p>Using <em>rest</em> parameters, <a target="_blank" href="https://medium.com/@yazeedb/how-do-javascript-rest-parameters-actually-work-227726e16cc8">see my article on that</a>, we can pipe <code>n</code> functions. Each function takes the output of the previous one and it’s all <em>reduced</em> ? to a single value.</p>
<p>And you can use it just like we did above.</p>
<pre><code class="lang-js">pipe(
  getName,
  uppercase,
  get6Characters,
  reverse
)({ <span class="hljs-attr">name</span>: <span class="hljs-string">'Buckethead'</span> });
<span class="hljs-comment">// 'TEKCUB'</span>
</code></pre>
<p>I’ll expand <code>pipe</code> and add some debugger statements, and we’ll go line by line.</p>
<pre><code class="lang-js">pipe = <span class="hljs-function">(<span class="hljs-params">...functions</span>) =&gt;</span> <span class="hljs-function">(<span class="hljs-params">value</span>) =&gt;</span> {
  <span class="hljs-keyword">debugger</span>;

  <span class="hljs-keyword">return</span> functions.reduce(<span class="hljs-function">(<span class="hljs-params">currentValue, currentFunction</span>) =&gt;</span> {
    <span class="hljs-keyword">debugger</span>;

    <span class="hljs-keyword">return</span> currentFunction(currentValue);
  }, value);
};
</code></pre>
<p><img src="https://cdn-media-1.freecodecamp.org/images/1*jqrKgVeO-raAUJjuN-adug.png" alt="1*jqrKgVeO-raAUJjuN-adug" width="600" height="400" loading="lazy"></p>
<p>Call <code>pipe</code> with our example and let the wonders unfold.</p>
<p><img src="https://cdn-media-1.freecodecamp.org/images/1*rqi22p06rTtc2m0k1yHrRw.png" alt="1*rqi22p06rTtc2m0k1yHrRw" width="600" height="400" loading="lazy"></p>
<p>Check out the local variables. <code>functions</code> is an array of the 4 functions, and <code>value</code> is <code>{ name: 'Buckethead' }</code>.</p>
<p>Since we used <em>rest</em> parameters, <code>pipe</code> allows any number of functions to be used. It’ll just loop and call each one.</p>
<p><img src="https://cdn-media-1.freecodecamp.org/images/1*UjM5plW8s--8chfQQg3cMg.png" alt="1*UjM5plW8s--8chfQQg3cMg" width="600" height="400" loading="lazy"></p>
<p>On the next debugger, we’re inside <code>reduce</code>. This is where <code>currentValue</code> is passed to <code>currentFunction</code> and returned.</p>
<p>We see the result is <code>'Buckethead'</code> because <code>currentFunction</code> returns the <code>.name</code> property of any object. That will be returned in <code>reduce</code>, meaning it becomes the new <code>currentValue</code> next time. Let’s hit the next debugger and see.</p>
<p><img src="https://cdn-media-1.freecodecamp.org/images/1*sEcE5tBFSpCzJZrKz8mmEQ.png" alt="1*sEcE5tBFSpCzJZrKz8mmEQ" width="600" height="400" loading="lazy"></p>
<p>Now <code>currentValue</code> is <code>‘Buckethead’</code> because that’s what got returned last time. <code>currentFunction</code> is <code>uppercase</code>, so <code>'BUCKETHEAD'</code> will be the next <code>currentValue</code>.</p>
<p><img src="https://cdn-media-1.freecodecamp.org/images/1*Va6taGFU8dSyhz1wLVMWMQ.png" alt="1*Va6taGFU8dSyhz1wLVMWMQ" width="600" height="400" loading="lazy"></p>
<p>The same idea, pluck <code>‘BUCKETHEAD’</code>'s first 6 characters and hand them off to the next function.</p>
<p><img src="https://cdn-media-1.freecodecamp.org/images/1*YaI1oxsZW5qZZUC146DYoQ.png" alt="1*YaI1oxsZW5qZZUC146DYoQ" width="600" height="400" loading="lazy"></p>
<p><code>reverse(‘.aedi emaS’)</code></p>
<p><img src="https://cdn-media-1.freecodecamp.org/images/1*moIMQxr82r2Z8IuXwuZfKQ.png" alt="1*moIMQxr82r2Z8IuXwuZfKQ" width="600" height="400" loading="lazy"></p>
<p>And you’re done!</p>
<h3 id="heading-what-about-compose">What about compose()?</h3>
<p>It’s just <code>pipe</code> in the other direction.</p>
<p>So if you wanted the same result as our <code>pipe</code> above, you’d do the opposite.</p>
<pre><code class="lang-js">compose(
  reverse,
  get6Characters,
  uppercase,
  getName
)({ <span class="hljs-attr">name</span>: <span class="hljs-string">'Buckethead'</span> });
</code></pre>
<p>Notice how <code>getName</code> is last in the chain and <code>reverse</code> is first?</p>
<p>Here’s a quick implementation of <code>compose</code>, again courtesy of the Magical <a target="_blank" href="https://medium.com/@_ericelliott">Eric Elliott</a>, from <a target="_blank" href="https://medium.com/javascript-scene/reduce-composing-software-fe22f0c39a1d">the same article</a>.</p>
<pre><code class="lang-js">compose = <span class="hljs-function">(<span class="hljs-params">...fns</span>) =&gt;</span> <span class="hljs-function">(<span class="hljs-params">x</span>) =&gt;</span> fns.reduceRight(<span class="hljs-function">(<span class="hljs-params">v, f</span>) =&gt;</span> f(v), x);
</code></pre>
<p>I’ll leave expanding this function with <code>debugger</code>s as an exercise to you. Play around with it, use it, appreciate it. And most importantly, have fun!</p>
 ]]>
                </content:encoded>
            </item>
        
    </channel>
</rss>
