<?xml version="1.0" encoding="UTF-8"?><rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>flow &#8211; Software, Fitness, and Gaming &#8211; Jesse Warden</title>
	<atom:link href="https://jessewarden.com/tag/flow/feed" rel="self" type="application/rss+xml" />
	<link>https://jessewarden.com</link>
	<description>Software &#124; Fitness &#124; Gaming</description>
	<lastBuildDate>Tue, 08 Jan 2019 18:37:20 +0000</lastBuildDate>
	<language>en-US</language>
	<sy:updatePeriod>
	hourly	</sy:updatePeriod>
	<sy:updateFrequency>
	1	</sy:updateFrequency>
	

<image>
	<url>https://jessewarden.com/wp-content/uploads/2016/08/cropped-Lambda2-32x32.png</url>
	<title>flow &#8211; Software, Fitness, and Gaming &#8211; Jesse Warden</title>
	<link>https://jessewarden.com</link>
	<width>32</width>
	<height>32</height>
</image> 
	<item>
		<title>Four Ways to Compose Synchronous Functions in JavaScript: Nest, Promise, Compose, &#038; Pipeline</title>
		<link>https://jessewarden.com/2019/01/four-ways-to-compose-synchronous-functions-in-javascript.html</link>
		
		<dc:creator><![CDATA[JesterXL]]></dc:creator>
		<pubDate>Tue, 01 Jan 2019 23:40:26 +0000</pubDate>
				<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[compose]]></category>
		<category><![CDATA[flow]]></category>
		<category><![CDATA[functionalprogramming]]></category>
		<category><![CDATA[javascript]]></category>
		<guid isPermaLink="false">http://jessewarden.com/?p=5750</guid>

					<description><![CDATA[Introduction Functional Programming is built around composing pure functions. Composing functions means taking all those useful functions you wrote and using them together to build more powerful functions, and even applications. This article will cover the 4 main ways to do that with synchronous code which includes the new pipeline operator. A future article will [&#8230;]]]></description>
										<content:encoded><![CDATA[
<h2 class="wp-block-heading">Introduction</h2>



<p>Functional Programming is built around composing <a href="http://jessewarden.com/2016/08/beginners-guide-to-functional-programming-part-1.html#purefunctions">pure functions</a>. Composing functions means taking all those useful functions you wrote and using them together to build more powerful functions, and even applications. This article will cover the 4 main ways to do that with synchronous code which includes the <a href="https://babeljs.io/blog/2018/07/19/whats-happening-with-the-pipeline-proposal">new pipeline operator</a>.  A future article will handle asynchronous options as well as dealing with partial applications and curried functions. If you&#8217;d like to play with the examples yourself, I have a <a href="https://codesandbox.io/s/ymxx6vnwoz">Code Sandbox setup</a> with basic and advanced examples.</p>



<span id="more-5750"></span>



<h2 class="wp-block-heading">Preface: The Parsing Code</h2>



<p>The four examples below will parse the same data composing the same functions. Let&#8217;s define that data and parsing code here first so you can see the various ways of combining functions.</p>



<h3 class="wp-block-heading">Logging</h3>



<p>To save us some typing, we&#8217;ll store <code>log</code> as our console.log function:</p>


<pre class="wp-block-code"><span><code class="hljs language-javascript"><span class="hljs-keyword">const</span> log = <span class="hljs-built_in">console</span>.log</code></span></pre>


<h3 class="wp-block-heading"> People JSON String</h3>



<p>Our data is a JSON String list of 2 people and 1 dog. </p>


<pre class="wp-block-code"><span><code class="hljs language-php"><span class="hljs-keyword">const</span> peopleString = `&#91;
	{
		<span class="hljs-string">"firstName"</span>: <span class="hljs-string">"jesse"</span>,
		<span class="hljs-string">"lastName"</span>: <span class="hljs-string">"warden"</span>,
		<span class="hljs-string">"type"</span>: <span class="hljs-string">"Human"</span>
	},
	{
		<span class="hljs-string">"firstName"</span>: <span class="hljs-string">"albus"</span>,
		<span class="hljs-string">"lastName"</span>: <span class="hljs-string">"dumbledog"</span>,
		<span class="hljs-string">"type"</span>: <span class="hljs-string">"Dog"</span>
	},
	{
		<span class="hljs-string">"firstName"</span>: <span class="hljs-string">"brandy"</span>,
		<span class="hljs-string">"lastName"</span>: <span class="hljs-string">"fortune"</span>,
		<span class="hljs-string">"type"</span>: <span class="hljs-string">"Human"</span>
	}
]`</code></span></pre>


<h3 class="wp-block-heading">Parsing Function</h3>



<p>Our mostly pure parsing function will take a string and parse it to a JSON Object:</p>


<pre class="wp-block-code"><span><code class="hljs language-javascript"><span class="hljs-keyword">const</span> parsePeople = <span class="hljs-function"><span class="hljs-params">str</span> =&gt;</span>
	<span class="hljs-built_in">JSON</span>.parse(str)</code></span></pre>


<h3 class="wp-block-heading">Filter Humans</h3>



<p>We need 2 functions to filter out the dog. The first is a <a href="http://jessewarden.com/2016/08/beginners-guide-to-functional-programming-part-1.html#predicates">predicate function</a> that ensures a person&#8217;s type is &#8220;Human&#8221;. </p>


<pre class="wp-block-code"><span><code class="hljs language-javascript"><span class="hljs-keyword">const</span> filterHuman = <span class="hljs-function"><span class="hljs-params">person</span> =&gt;</span>
	person.type === <span class="hljs-string">"Human"</span></code></span></pre>


<p>So <code>filterHuman({type: 'Human'})</code>would return <code>true</code>and <code>filterHuman({type: 'Dog'})</code>would return <code>false</code>. </p>



<p>The 2nd function will use that predicate in the <code>Array.filter</code> function so only humans will remain.</p>


<pre class="wp-block-code"><span><code class="hljs language-javascript"><span class="hljs-keyword">const</span> filterHumans = <span class="hljs-function"><span class="hljs-params">peeps</span> =&gt;</span>
	peeps.filter(filterHuman)</code></span></pre>


<h3 class="wp-block-heading">Format Names</h3>



<p>We want to format the names so instead of 2 separate <code>firstName</code>and <code>lastName</code> variables, instead they&#8217;re combined into a single string.</p>


<pre class="wp-block-code"><span><code class="hljs language-javascript"><span class="hljs-keyword">const</span> formatName = <span class="hljs-function"><span class="hljs-params">human</span> =&gt;</span>
	<span class="hljs-string">`<span class="hljs-subst">${human.firstName}</span> <span class="hljs-subst">${
		human.lastName
	}</span>`</span></code></span></pre>


<p>We can use it to take <code>formatName({firstName: 'bruce', lastName: 'campbell'})</code> which will result in &#8220;bruce campbell&#8221;.</p>



<p>Next is to use that function on everyone in the list using <code>map</code>:</p>


<pre class="wp-block-code"><span><code class="hljs language-javascript"><span class="hljs-keyword">const</span> formatNames = <span class="hljs-function"><span class="hljs-params">humans</span> =&gt;</span>
	humans.map(formatName)</code></span></pre>


<h3 class="wp-block-heading">Fixing The Name Case</h3>



<p>The 4th and final thing to do is fix the name casing. All the names are lowercased and we want it to be proper with the first and last name having the first character uppercased. The easiest way is to simply us <a href="https://lodash.com/docs/4.17.11#startCase">Lodash&#8217; startCase</a> function to do it for us. </p>


<pre class="wp-block-code"><span><code class="hljs language-javascript"><span class="hljs-keyword">const</span> startCaseName = <span class="hljs-function"><span class="hljs-params">name</span> =&gt;</span>
	startCase(name)</code></span></pre>


<p>That will take <code>startCaseName('bruce campbell')</code> and produce &#8220;Bruce Campbell&#8221;. Taking that function we can again apply it to every person in the list using <code>map</code>:</p>


<pre class="wp-block-code"><span><code class="hljs language-javascript"><span class="hljs-keyword">const</span> startCaseNames = <span class="hljs-function"><span class="hljs-params">humans</span> =&gt;</span>
	humans.map(startCaseName)</code></span></pre>


<h2 class="wp-block-heading">Nesting</h2>



<p>The most common way to compose functions is to nest them. If we want to parse the JSON, we&#8217;ll first call <code>parsePeople</code>:</p>


<pre class="wp-block-code"><span><code class="hljs language-javascript"><span class="hljs-keyword">const</span> parse1 = <span class="hljs-function"><span class="hljs-params">str</span> =&gt;</span>
    parsePeople(str)</code></span></pre>


<p>That&#8217;ll give us our Array of people Objects, so we can next filter out the humans:</p>


<pre class="wp-block-code"><span><code class="hljs language-javascript"><span class="hljs-keyword">const</span> parse1 = <span class="hljs-function"><span class="hljs-params">str</span> =&gt;</span>
    filterHumans(parsePeople(str))</code></span></pre>


<p>The <code>filterHumans</code>function will take in whatever <code>parsePeople(str)</code>returns. Next is to format all the human names:</p>


<pre class="wp-block-code"><span><code class="hljs language-javascript"><span class="hljs-keyword">const</span> parse1 = <span class="hljs-function"><span class="hljs-params">str</span> =&gt;</span>
    formatNames(filterHumans(parsePeople(str)))</code></span></pre>


<p>Two nested functions is where people start to draw the line on things being unreadable, similar to nested <code>if</code> statements. However, there is only 1 more left, and that&#8217;s fixing the case of the names:</p>


<pre class="wp-block-code"><span><code class="hljs language-javascript"><span class="hljs-keyword">const</span> parse1 = <span class="hljs-function"><span class="hljs-params">str</span> =&gt;</span>
    startCaseNames(formatNames(filterHumans(parsePeople(str))))</code></span></pre>


<p>Calling <code>parse1(peopleString)</code> will result in:</p>


<pre class="wp-block-code"><span><code class="hljs language-json">&#91;<span class="hljs-string">"Jesse Warden"</span>, <span class="hljs-string">"Brandy Fortune"</span>]</code></span></pre>


<p>One thing you can possibly do to make it more readable is to treat it like nested <code>if</code> blocks and space it appropriately:</p>


<pre class="wp-block-code"><span><code class="hljs language-javascript"><span class="hljs-keyword">const</span> parse1 = <span class="hljs-function"><span class="hljs-params">str</span> =&gt;</span>
	startCaseNames(
		formatNames(
			filterHumans(
				parsePeople(str)
			)
		)
	)</code></span></pre>


<h2 class="wp-block-heading">Promise</h2>



<p>Given each of these operations is done one after the other, you can use <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise">Promises</a>. They have the nice feature in their <code>then</code> statement, you can return a value, not just a <code>Promise</code>. Normally you&#8217;ll see people return a Promise:</p>


<pre class="wp-block-code"><span><code class="hljs language-javascript"><span class="hljs-keyword">const</span> twoThings = <span class="hljs-function"><span class="hljs-params">()</span> =&gt;</span>
    <span class="hljs-built_in">Promise</span>.resolve(<span class="hljs-number">1</span>)
    .then(<span class="hljs-function"><span class="hljs-params">result</span> =&gt;</span> <span class="hljs-built_in">Promise</span>.resolve(result + <span class="hljs-number">1</span>))
twoThings()
.then(<span class="hljs-function"><span class="hljs-params">result</span> =&gt;</span> log(<span class="hljs-string">"result:"</span>, result) <span class="hljs-comment">// 2</span></code></span></pre>


<p>However, once you&#8217;re in a Promise chain, as long as it&#8217;s not an <code>Error</code>, you can return whatever you want and it&#8217;ll resolve into the next then. Rewriting the same function above using that would be:</p>


<pre class="wp-block-code"><span><code class="hljs language-javascript"><span class="hljs-keyword">const</span> twoThings = <span class="hljs-function"><span class="hljs-params">()</span> =&gt;</span>
    <span class="hljs-built_in">Promise</span>.resolve(<span class="hljs-number">1</span>)
    .then(<span class="hljs-function"><span class="hljs-params">result</span> =&gt;</span> result + <span class="hljs-number">1</span>)
twoThings()
.then(<span class="hljs-function"><span class="hljs-params">result</span> =&gt;</span> log(<span class="hljs-string">"result:"</span>, result) <span class="hljs-comment">// 2</span></code></span></pre>


<p>Or just defining the intermediate function separately:</p>


<pre class="wp-block-code"><span><code class="hljs language-javascript"><span class="hljs-keyword">const</span> add1 = <span class="hljs-function"><span class="hljs-params">result</span> =&gt;</span>
    result + <span class="hljs-number">1</span>
<span class="hljs-keyword">const</span> twoThings = <span class="hljs-function"><span class="hljs-params">()</span> =&gt;</span>
    <span class="hljs-built_in">Promise</span>.resolve(<span class="hljs-number">1</span>)
    .then(add1)</code></span></pre>


<p>Which means, we can take our nested function:</p>


<pre class="wp-block-code"><span><code class="hljs language-javascript"><span class="hljs-keyword">const</span> parse1 = <span class="hljs-function"><span class="hljs-params">str</span> =&gt;</span>
    startCaseNames(formatNames(filterHumans(parsePeople(str))))</code></span></pre>


<p>And convert it to a more readable Promise version, even though it&#8217;s synchronous code: </p>


<pre class="wp-block-code"><span><code class="hljs language-javascript"><span class="hljs-keyword">const</span> parse2 = <span class="hljs-function"><span class="hljs-params">str</span> =&gt;</span>
    <span class="hljs-built_in">Promise</span>.resolve(str)
        .then(parsePeople)
        .then(filterHumans)
        .then(formatNames)
        .then(startCaseNames)</code></span></pre>


<p>The downside is it still has to be called like a normal asynchronous Promise:</p>


<pre class="wp-block-code"><span><code class="hljs language-javascript">parse2(peopleString)
.then(log) <span class="hljs-comment">// &#91;"Jesse Warden", "Brandy Fortune"]</span></code></span></pre>


<p>However, it does have the advantage of being a bit easier to read, easier to follow in terms of what is happening when and in what order. Additionally, Promises have built-in try/catch so the error handling is in one place. Finally, because of the chaining, you can quickly comment out a section of the chain to debug what&#8217;s going up to a certain point:</p>


<pre class="wp-block-code"><span><code class="hljs language-javascript"><span class="hljs-keyword">const</span> parse2 = <span class="hljs-function"><span class="hljs-params">str</span> =&gt;</span>
    <span class="hljs-built_in">Promise</span>.resolve(str)
        .then(parsePeople)
        .then(filterHumans)
        <span class="hljs-comment">//.then(formatNames)</span>
        <span class="hljs-comment">//.then(startCaseNames)</span></code></span></pre>


<p>You can also do a <code>tap</code>function to determine how things are progressing up to a certain point as well. For now, we&#8217;ll use a modified <code>log</code>function to take a value, log it out, then return whatever you were passed:</p>


<pre class="wp-block-code"><span><code class="hljs language-javascript"><span class="hljs-keyword">const</span> tap = <span class="hljs-function">(<span class="hljs-params">...args</span>) =&gt;</span> {
    log(args)
    <span class="hljs-keyword">return</span> <span class="hljs-built_in">Promise</span>.resolve.apply(<span class="hljs-built_in">Promise</span>, args)
}</code></span></pre>


<p>Notice below, we can use tap to log things out, or use <code>log</code> manually if we want more detail: </p>


<pre class="wp-block-code"><span><code class="hljs language-javascript"><span class="hljs-keyword">const</span> parse2 = <span class="hljs-function"><span class="hljs-params">str</span> =&gt;</span>
    <span class="hljs-built_in">Promise</span>.resolve(str)
        .then(tap)
        .then(parsePeople)
        .then(tap)
        .then(filterHumans)
        .then(<span class="hljs-function"><span class="hljs-params">humans</span> =&gt;</span> log(<span class="hljs-string">"humans:"</span>, humans) || humans)
        .then(formatNames)
        .then(tap)
        .then(startCaseNames)
        .then(<span class="hljs-function"><span class="hljs-params">final</span> =&gt;</span> log(<span class="hljs-string">"final is:"</span>, final))</code></span></pre>


<h2 class="wp-block-heading">Flow / Compose</h2>



<p>Ramda uses <a href="https://ramdajs.com/docs/#compose">compose</a> and Lodash calls it <a href="https://lodash.com/docs/4.17.11#flow">flow</a>. They take a bunch of functions you want piped together and give you a new one. Taking our nested function:</p>


<pre class="wp-block-code"><span><code class="hljs language-javascript"><span class="hljs-keyword">const</span> parse1 = <span class="hljs-function"><span class="hljs-params">str</span> =&gt;</span>
    startCaseNames(formatNames(filterHumans(parsePeople(str))))</code></span></pre>


<p>Which is parsing people JSON, then filtering the dog out, then formatting the names as strings, and finally fixing the casing. We can do that, in order like we did in the promise. Using Lodash&#8217; <code>flow</code> to make 1 function of all them:</p>


<pre class="wp-block-code"><span><code class="hljs language-javascript"><span class="hljs-keyword">const</span> supaParse =
    flow(&#91;
        parsePeople
        , filterHumans
        , formatNames
        , startCaseNames
    ])</code></span></pre>


<p>However, instead of storing it as <code>supaParse</code>, we can you can just use it inline. </p>


<pre class="wp-block-code"><span><code class="hljs language-javascript"><span class="hljs-keyword">const</span> parse3 = <span class="hljs-function"><span class="hljs-params">str</span> =&gt;</span>
	flow(&#91;
		parsePeople
		, filterHumans
		, formatNames
		, startCaseNames
	])(str)</code></span></pre>


<p>Calling <code>parse3(peopleString)</code>will result in <code>["Jesse Warden", "Brandy Fortune"]</code>. Like the <code>Promise</code>example, it&#8217;s easier to read and follow the order of what&#8217;s happening. Unlike the Promise, it&#8217;s synchronous, so there is no need to worry about Promise chains, async/await, etc.  However, error handling is on you, and some of your intermediate functions may not know how to handle errors as their inputs when they were expecting a string of Arrays like <code>startCaseNames</code>for example.</p>



<p>Like the <code>Promise</code>example, you can comment out parse of the sequence to better debug how your data is being modified up to a certain point:</p>


<pre class="wp-block-code"><span><code class="hljs language-javascript"><span class="hljs-keyword">const</span> parse3 = <span class="hljs-function"><span class="hljs-params">str</span> =&gt;</span>
	flow(&#91;
		parsePeople
		, filterHumans
		<span class="hljs-comment">// , formatNames</span>
		<span class="hljs-comment">// , startCaseNames</span>
	])(str)</code></span></pre>


<p>You can log out each part using a modified tap:</p>


<pre class="wp-block-code"><span><code class="hljs language-javascript"><span class="hljs-keyword">const</span> tap = <span class="hljs-function"><span class="hljs-params">arg</span> =&gt;</span> {
    log(arg)
    <span class="hljs-keyword">return</span> arg
}</code></span></pre>


<p>And then use it:</p>


<pre class="wp-block-code"><span><code class="hljs language-javascript"><span class="hljs-keyword">const</span> parse3 = <span class="hljs-function"><span class="hljs-params">str</span> =&gt;</span>
	flow(&#91;
		parsePeople
		, tap
		, filterHumans
		, tap
		, formatNames
		, arg =&gt; log(<span class="hljs-string">"after format names:"</span>, arg) || arg
		, startCaseNames
	])(str)</code></span></pre>


<a name="pipeline"></a><h2 class="wp-block-heading">Pipeline Operator</h2>



<p>There is a proposal to add a <a href="https://github.com/tc39/proposal-pipeline-operator">pipeline operator</a> to JavaScript like F#, Elm, and Elixir have.  At the time of this writing, you can play with 2 of the 3 proposed styles: Minimal, F#, and Smart in Babel 7.2. I&#8217;ll show just Minimal and Smart below for now.</p>



<p>Taking our existing nested function:</p>


<pre class="wp-block-code"><span><code class="hljs language-javascript"><span class="hljs-keyword">const</span> parse1 = <span class="hljs-function"><span class="hljs-params">str</span> =&gt;</span>
    startCaseNames(formatNames(filterHumans(parsePeople(str))))</code></span></pre>


<p>We can use the pipeline operator <code>|&gt;</code> to accomplish the same thing:</p>


<pre class="wp-block-code"><span><code class="hljs language-javascript"><span class="hljs-keyword">const</span> parse4 = <span class="hljs-function"><span class="hljs-params">str</span> =&gt;</span>
    parsePeople(str)
    |&gt; filterHumans
    |&gt; formatNames
    |&gt; startCaseNames</code></span></pre>


<p>Calling <code>parse4(peopleString)</code>will result in <code>["Jesse Warden", "Brandy Fortune"]</code>.</p>



<p>Like the others, you can comment out the parts at the bottom to see how things are progressing:</p>


<pre class="wp-block-code"><span><code class="hljs language-javascript"><span class="hljs-keyword">const</span> parse4 = <span class="hljs-function"><span class="hljs-params">str</span> =&gt;</span>
    parsePeople(str)
    |&gt; filterHumans
    <span class="hljs-comment">// |&gt; formatNames</span>
    <span class="hljs-comment">// |&gt; startCaseNames</span></code></span></pre>


<p>You can re-use the same tap function as <code>flow</code> / <code>compose</code>:</p>


<pre class="wp-block-code"><span><code class="hljs language-javascript"><span class="hljs-keyword">const</span> parse4 = <span class="hljs-function"><span class="hljs-params">str</span> =&gt;</span>
    parsePeople(str)
    |&gt; tap
    |&gt; filterHumans
    |&gt; tap
    |&gt; formatNames
    |&gt; (<span class="hljs-function"><span class="hljs-params">arg</span> =&gt;</span> log(<span class="hljs-string">"after format names:"</span>, arg) || arg)
    |&gt; startCaseNames</code></span></pre>


<h2 class="wp-block-heading">Conclusions</h2>



<p>When composing pure functions together to build more specific functions, hopefully now you can see you have some options. While nested functions work, like nested if&#8217;s, they&#8217;re hard to read and reason about. Promises are nice and flexible between sync and async with built-in error handling, but sometimes adding that level of complication isn&#8217;t what you want. The flow from Lodash and compose from Ramda are a lot nicer and more specific, but all the error handling is on you. The pipeline operator is probably the easiest to read, but has the same problem with flow / compose around error handling.</p>
]]></content:encoded>
					
		
		
			</item>
	</channel>
</rss>
