<?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 Shanon Jackson on Medium]]></title>
        <description><![CDATA[Stories by Shanon Jackson on Medium]]></description>
        <link>https://medium.com/@shanonjackson?source=rss-2d0041eb6c4------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*9cpEmbvUOb_pGf-0.</url>
            <title>Stories by Shanon Jackson on Medium</title>
            <link>https://medium.com/@shanonjackson?source=rss-2d0041eb6c4------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 20 Nov 2026 13:50:11 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@shanonjackson/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[FP — The power of reduce]]></title>
            <link>https://medium.com/@shanonjackson/fp-the-power-of-reduce-f2c9609823cc?source=rss-2d0041eb6c4------2</link>
            <guid isPermaLink="false">https://medium.com/p/f2c9609823cc</guid>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Shanon Jackson]]></dc:creator>
            <pubDate>Thu, 27 Dec 2018 08:51:00 GMT</pubDate>
            <atom:updated>2018-12-27T08:51:00.875Z</atom:updated>
            <content:encoded><![CDATA[<h3>FP — Advanced reduce power.</h3><p>the true power of reduce.</p><p>This is going to be one of two articles where I present functional programming concepts in a (hopefully) digestible way. This one which will mostly be about “reduce” and arrays, and another one which will be a long one about objects.</p><p>The single most important and compelling thing about <em>Array.prototype.reduce</em>, and something that is just missed in every other article, is that it’s capable of <strong>solving all possible collections problems.</strong> In (F.P) the generalization of a fold (<em>javascript reduce)</em> is known as a <em>Catamorphism</em> and if you’re interested in the mathematics of how folds work I would suggest starting there. This generalization also applies to all algebraic data types.</p><p>But this article is meant to be pragmatic, so let&#39;s start. For people instantly skeptical about the “all possible collections problems”, here’s all the Array.prototype methods implemented immutably in terms of reduce just as a starting point.</p><pre><br>// note i&#39;ll be using my definition of concat in rest of implementations but you can use easily swap it out for the Array.prototype one.<br>/* helper method */<br>const isArray = (arg) =&gt; Object.prototype.toString.call(arg) === &#39;[object Array]&#39;;</pre><pre>// Array.prototype.concat<br>const concat = (arr) =&gt; (item) =&gt; isArray(item) ? [...arr, ...item] : [...arr, item];</pre><pre>// <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/entries">Array.prototype.entries()</a><br>const entries = (arr) =&gt; arr.reduce((accum, curr, idx) =&gt; concat(accum)([[idx, curr]]), [])</pre><pre>// <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/every">Array.prototype.every()</a><br>const every = (arr) =&gt; (f) =&gt; arr.reduce((accum, curr) =&gt; !accum ? accum : f(curr), true)</pre><pre>// <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/fill">Array.prototype.fill()</a><br>const fill = (arr) =&gt; (element) =&gt; arr.reduce((accum) =&gt; concat(accum)(element), []);</pre><pre>// <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter">Array.prototype.filter()</a><br>const filter = (arr) =&gt; (predicate) =&gt; arr.reduce((accum, curr) =&gt; predicate(curr) ? concat(accum)(curr) : accum, []);</pre><pre>// <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/find">Array.prototype.find()</a><br>const find = (arr) =&gt; (f) =&gt; arr.reduce((a,c) =&gt; {<br> if(a) return a;<br> return f(c) ? c : undefined;<br>}, undefined)</pre><pre>// <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/findIndex">Array.prototype.findIndex()</a><br>const findIndex = (arr) =&gt; (f) =&gt; arr.reduce((a, c, i) =&gt; {<br>    if(a &gt; -1) return a;<br>    return f(c) ? i : a;<br>}, -1);</pre><pre>// <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/flat">Array.prototype.flat()</a><br>const flat = (arr) =&gt; (num) =&gt; arr.reduce((a, c, i) =&gt; {<br>    if(isArray(c) &amp;&amp; num &gt; 0) return concat(a)(flat(c)(num - 1));<br>    return concat(a)([c]);<br>}, []);</pre><pre>// <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/flatMap">Array.prototype.flatMap()</a><br>const flatMap = (arr) =&gt; (f) =&gt; arr.reduce((a, c) =&gt; concat(a)(f(c)), []);</pre><pre>// <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach">Array.prototype.forEach()</a><br>const forEach = (arr) =&gt; (f) =&gt; arr.reduce((_, c) =&gt; f(c), []);</pre><pre>// <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/includes">Array.prototype.includes()</a><br>const includes = (arr) =&gt; (ele) =&gt; arr.reduce((a, c) =&gt; a ? a : c === ele, false);</pre><pre>// <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/indexOf">Array.prototype.indexOf()</a></pre><pre>const indexOf = (arr) =&gt; (ele) =&gt; arr.reduce((a,c, i) =&gt; {<br> if(a &gt; -1) return a;<br> return c === ele ? i : -1;<br>}, -1)</pre><pre>// <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/join">Array.prototype.join()</a><br>const join = (arr) =&gt; (str) =&gt; arr.reduce((a, c , i) =&gt; i === 0 ? (a + c) : (a + str + c), &quot;&quot;);</pre><pre>// <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/keys">Array.prototype.keys()</a><br>const keys = (arr) =&gt; arr.reduce((a,c, i) =&gt; concat(a)(i), []);</pre><pre>// <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/lastIndexOf">Array.prototype.lastIndexOf()</a><br>const lastIndexOf = (arr) =&gt; (ele) =&gt; arr.reduce((a, c, i) =&gt; c === ele ? i : a, -1)</pre><pre>// <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map">Array.prototype.map()</a><br>const map = (arr) =&gt; (f) =&gt; arr.reduce((a, c) =&gt; concat(a)(f(c)), []);</pre><pre>// <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/pop">Array.prototype.pop()</a><br>const pop = (arr) =&gt; arr.reduce((a, c, i) =&gt; i === arr.length - 1 ? a : concat(a)(c), [])</pre><pre>// <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/push">Array.prototype.push()</a><br>const push = (arr) =&gt; (ele) =&gt; {<br>    if(arr.length === 0) return [ele];<br>    return arr.reduce((a, c, i) =&gt; {<br>        if(i === arr.length - 1) return concat(a)([c, ele]);<br>        return concat(a)(c);<br>    }, [])<br>}</pre><pre>// <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/Reduce">Array.prototype.reduce()</a><br>// no black magic going on behind the scenes.<br>const reduce = (arr) =&gt; (f) =&gt; (accum) =&gt; {<br>    const looper = ([head, ...tail]) =&gt; (f) =&gt; (accum) =&gt; (i) =&gt; {<br>        if(head === undefined) return accum; // we&#39;re done.<br>        return looper(tail)(f)(f(accum, head, i))(i + 1)<br>    }<br>    return looper(arr)(f)(accum)(0)<br>}</pre><pre>// <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/unshift">Array.prototype.unshift()</a><br>const unshift = (arr) =&gt; (ele) =&gt; {<br>    if(arr.length === 0) return [ele];<br>    return arr.reduce((a, c, i) =&gt; {<br>        if(i === 0)  return concat(a)([ele, c]);<br>        return concat(a)(c);<br>    }, [])<br>}</pre><pre>// <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reverse">Array.prototype.reverse()</a><br>const reverse = (arr) =&gt; arr.reduce((a, c) =&gt; {<br>     return unshift(a)(c)<br>}, []);</pre><pre>// <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/ReduceRight">Array.prototype.reduceRight()</a><br>const reduceRight = (arr) =&gt; (f) =&gt; (accum, i = 0) =&gt; reduce(reverse(arr))(f)(accum)</pre><pre>// <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/slice">Array.prototype.slice()</a><br>// basic slice but you get the idea.<br>const slice = (arr) =&gt; (start, end) =&gt; arr.reduce((accum, curr, i) =&gt; {<br>    if(i &lt;= end &amp;&amp; i &gt;= start) return concat(accum)(curr);<br>    return accum;<br>}, []);</pre><pre>// <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort">Array.prototype.sort()</a><br>// sorry about formatting, its a long-sort aswell but i hope it atleast shows the idea.</pre><pre>const sort = (arr) =&gt; (f) =&gt; {<br>    const swap = (arr) =&gt; (idx1, idx2) =&gt; arr.reduce((a, c, i) =&gt; {<br>        if(i === idx1) return concat(a)(arr[idx2]);<br>        if(i === idx2) return concat(a)(arr[idx1]);<br>        return concat(a)(c);<br>    }, []); <br>    const loopSort = (arr) =&gt; (f) =&gt; {<br>        return arr.reduce((accum, curr, i) =&gt; {<br>            if(accum.completed) return accum;<br>            if(i === arr.length - 1) {<br>                return {result: concat(accum.result)(curr), completed: true}<br>            }<br>            if(f(arr[i], arr[i + 1]) &gt; 0) return loopSort(swap(arr)(i, i + 1))(f);<br>            return {result: concat(accum.result)(curr), completed: false};<br>        }, {result: [], completed: false})<br>    }<br>    return loopSort(arr)(f).result;<br>}</pre><pre>// note: if any of these deviate from the actual specification its because im only showing this as a guide, if you think something can&#39;t be implemented in terms of .reduce please leave a comment and i&#39;ll get back to you.</pre><p>There’s a reason this is possible and the reason comes from first understanding that you’ve actually been “reducing” already you’ve just been using the long-hand, for example, take the following imperative/mutable code and then let’s go on a journey accidentally invent reduce together.</p><pre>const sumNumbers = (arr) =&gt; {<br>    let total = 0;<br>    for(var i = 0;i &lt; arr.length; i++) {<br>        total = total + arr[i]<br>    }<br>    return total;<br>}</pre><p>look familiar? let’s take a closer look with the help of MS paint.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/357/1*4mMqhhGYwjbokh_zx1vAZg.png" /></figure><p>When marked it starts to become a little more obvious, now this pattern can pretty much generalize all for(i) loops and for-in loops in your application.</p><p><strong>Accumulator</strong>: Some type “B” which normally has some value that represents the starting point and the return if our collection is empty.<br><strong>Iterator</strong>: Some structure that loops over all elements in your collection<br><strong>Modification</strong>: Some expression that modifies the accumulator based on the current iterated element.<br><strong>Return</strong>: Return the accumulator.</p><p>interesting let’s see if we can write something that can <strong>generalize </strong>this pattern Let’s do it piece by piece, <strong>first</strong> let’s write an abstraction for that accumulator by parameterizing it, adding the functionality of allowing any starting number or possibly the possibility of passing a string through.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/345/1*dT6nu2rXTBdh8nuwqUEt4w.png" /></figure><p>ok cool, we’re getting there, it still works now we have a generic “sum” that can optionally start at any number. But it can <strong>only </strong>sum numbers, what if we want to multiply the numbers? what if we want to average the numbers? we’d need a new function every time. So, let’s write an abstraction that allows us to control “how” we <strong>modify </strong>the value.</p><p>Now I don’t want to lose people here because we’re going to jump very fast so the only thing we’re going to change is we’re going to pass our function another function which is given the accumulator and the current value and returns a new accumulator <em>(accum, current) =&gt; newAccum</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/493/1*y7FSKI4W8P7CUvUnS0rKDg.png" /></figure><p>Now we’ve accidentally built something that can handle more than just numbers, in fact this <em>genericIterator </em>can handle all<strong>*</strong> possible array transformations but there are still some problems with it.<br>we’re mutating “i” each iteration | AND | we’re mutating ‘start’ the accumulator. But there’s good news, the good news is <strong>ALL* mutable algorithms can be implemented immutably.</strong></p><p>So let’s apply a final abstraction one that removes the mutation and leaves the rest intact, by swapping out the <strong>mutable iteration for immutable recursion</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/539/1*KxQ8Pz38a6SWPiemudHpxg.png" /></figure><p>There we go, we’ve implemented reduce in 2 lines which has (i haven’t read the ECMAScript specification for reduce but essentially more-or-less the same functionality).</p><p>Now we’ve stayed away from Map / Filter for this whole article but that’s because this article is about “reduce” and also that Map / Filter are just syntactic sugar for “Reduce” where some of the arguments are applied/structured for you. Here’s an example of that.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/777/1*GwFQmniObTVow7ciboxZ6g.png" /></figure><p>That’s it. I hope I&#39;ve helped you to grasp why we have “reduce” how powerful it actually is and shed some light on how map/filter work under the hood. Hopefully, you’ll be able to refactor out some disgusting for-in and for(i) loops left in your codebase.</p><p>Also this generalization of map/filter in terms of reduce is also how transducers work.</p><p>I’ll also be doing a probably more interesting article follow up article for objects.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f2c9609823cc" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>